Skip to content

The open-source app everyone uses to manage agents at work

feat(chat): simplify Slack onboarding and account linking (#13638)

Dotta924f07be8c4c
diff --git a/AGENTS.md b/AGENTS.md
index 0e31e80d7c..c957ca41ea 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -198,6 +198,7 @@ When adding endpoints:
- Keep routes and nav aligned with available API surface
- Use company selection context for company-scoped pages
- Surface failures clearly; do not silently ignore API errors
+- Form and wizard footers: keep Save & exit (or Cancel/Back) left and the primary action right in the same vertically aligned row. Each step owns the entire footer; never append Save & exit as a separate row. See `DESIGN.md`.
## 10. Pull Request Requirements
diff --git a/DESIGN.md b/DESIGN.md
index 56c43fb5e6..16f428bffa 100644
--- a/DESIGN.md
+++ b/DESIGN.md
@@ -35,6 +35,14 @@ Existing tiers already in index.css (~80+ tokens) — extraction maps to these o
7. **Words are part of the system.** One name per concept across the entire UI — the canonical term is *task* (never *issue* or *ticket* in copy, labels, or empty states). Buttons name the action ("Approve hire," not "Submit"). Errors say what happened and what to do. Empty states say what to do first. **Note:** enforcing the task rename is a visible change and is explicitly OUT of the zero-visual-change extraction run; it happens in its own follow-up run.
8. **Agent-modifiable by design.** The system must be changeable via instructions: single token source, lint rules that enforce it, and this document kept current. A correct change should be expressible as "edit tokens + run checks," not "visit 40 files."
+## Form and wizard footers
+
+Keep **Save & exit** (or Cancel/Back) and the primary Continue/Connect/Finish
+action in one shared footer row, vertically centered. Put the subdued secondary
+action on the left and the primary action on the right. A step owns its whole
+footer: do not render Save & exit in a separate parent block below it. Check this
+alignment in every step and conditional state, not just the first screen.
+
## Contextual feedback
Do not show a toast for task or run state already visible on the current screen.
diff --git a/doc/DEVELOPING.md b/doc/DEVELOPING.md
index 157589b00c..65c8c956c5 100644
--- a/doc/DEVELOPING.md
+++ b/doc/DEVELOPING.md
@@ -479,6 +479,68 @@ preserves all companies, agents, and secrets and ignores the bootstrap flags.
The worktree execution setting is the only value it may reconcile in that
case.
+### Slack chat setup in a test drive
+
+Enable **Chat connectors** in Instance Settings, then open **Connectors → Slack →
+Chat with an agent**. Before connecting, configure a public HTTPS URL that Slack
+can reach. The setup page shows this requirement above the app details.
+Slack app name, bot display name, and slash command are editable while the
+connection is a draft; valid edits save when a field loses focus. **Create Slack
+app** opens Slack with the generated manifest prefilled. **View Slack App Manifest**
+opens the read-only manifest in a modal to inspect or copy it. Once connected,
+the app details are locked so reconnecting cannot silently change the registered
+command. Slack still requires workspace selection, installation approval, and
+copying the bot token and signing secret back into Paperclip.
+
+After Slack verifies its Events Request URL, the wizard asks you to send
+`/<your-command> connect`. This command works before a sender or channel is
+allowed to start work. It records the Slack identity and sends a private,
+one-time confirmation link that expires after 15 minutes; it creates no task
+and grants no access. You can confirm **This is my Slack account** in the wizard,
+or follow the private link and sign into Paperclip. Both paths check company
+membership before linking, and future messages use the linked user's current
+permissions. The wizard only lists identities that sent the connect command to
+this endpoint during the current test.
+
+New Slack connections disable **Allow unlinked people** by default. The Access
+page includes the shareable connect command and instructions for other users.
+Other Slack users join through the same connect command after setup. A signed-in
+nonmember can **Request access** from the confirmation page. This creates a
+pending human join request in the company's existing admin approval queue; it
+does not grant membership or link the identity. After approval, confirm the
+identity, or send the connect command again if the link has expired. Successful
+confirmation also queues a private Slack acknowledgement.
+
+Slack identity invitation pages retain the cloud authentication and bootstrap
+checks. Signed-in nonmembers may open a valid private invitation to request
+membership, but confirmation still requires membership in the invitation's
+company. Preview, access-request, and confirmation APIs also enforce the chat
+connector rollout flag on the server; invitees cannot read board experimental
+settings before they join. Expired or consumed tokens grant no access.
+
+The final wizard step suggests `@<your-bot> you there?`, then continuing in
+the agent's thread. Select the bot from Slack's @mention suggestions so the
+message includes a real mention. It detects a message or task command from the current user's
+linked Slack identity during this setup session and shows a checkmark. This
+conversation test is optional: **I've sent the test message** and **Skip test and
+finish** both finish setup once webhook verification and account linking are
+complete. The separate strict connection-test API retains its conversation and
+delivery checks.
+
+### Chat activity pagination and callback diagnostics
+
+The connection Activity tab loads 25 records per page. `GET /api/chat-endpoints/:id/activity?limit=25`
+returns `{ items, nextCursor }`; pass `cursor` to read older records. The limit must be 1–100.
+A timestamp and ID cursor preserves records with equal timestamps and avoids shifts from new arrivals.
+The first page refreshes automatically; older pages do not poll. Mutable action status can move an
+entry forward in time, so this is a live ledger, not a historical snapshot. Requests without pagination
+parameters retain the recent-100 array response for existing clients.
+
+Slack callback diagnostics tolerate HTTP between a TLS proxy and Paperclip when the public host,
+port, and path still match. A changed authority or path remains stale. This comparison only affects
+health display; it does not trust forwarded headers or alter Slack signature verification.
+
+
## Docker Quickstart (No local Node install)
Build and run Paperclip in Docker:
diff --git a/packages/shared/src/types/chat-channels.ts b/packages/shared/src/types/chat-channels.ts
index 7c09cd06e9..e17e5e4bef 100644
--- a/packages/shared/src/types/chat-channels.ts
+++ b/packages/shared/src/types/chat-channels.ts
@@ -181,15 +181,24 @@ export interface ChatEndpointCallbackSurfaces {
slashCommands: ChatEndpointCallbackSurfaceState;
}
+export interface SlackAppConfiguration {
+ appName: string;
+ botName: string;
+ command: string;
+}
+
export interface ChatEndpointSetupState {
step: "choose_agent" | "provider_setup" | "test" | "complete";
/** Server-generated boundary; only provider events at or after this time can complete setup. */
testStartedAt?: string | null;
+ /** Onboarding was finished without requiring a full conversation test. */
+ testSkipped?: boolean;
/** Set only after the provider has delivered a signed callback challenge. */
webhookVerifiedAt?: string | null;
authorizationUrl?: string | null;
providerUrl?: string | null;
command?: string | null;
+ slackApp?: SlackAppConfiguration;
webhookUrl?: string | null;
messagingEndpoint?: string | null;
/** Safe presence signal only; the secret value is returned once by its generation endpoint. */
@@ -279,6 +288,8 @@ export interface ChatIdentityLink {
companyId: string;
endpointId: string;
principalId: string;
+ /** Latest discovery-only connect command received by this endpoint. */
+ lastConnectAt?: string | null;
externalLabel: string;
externalDetail?: string | null;
paperclipUserId?: string | null;
@@ -462,6 +473,7 @@ export interface CreateChatEndpointInput {
}
export interface UpdateChatEndpointInput {
+ slackApp?: SlackAppConfiguration;
allowDirectMessages?: boolean;
allowGroupChats?: boolean;
allowUnlinkedPeople?: boolean;
diff --git a/packages/shared/src/validators/chat-channels.ts b/packages/shared/src/validators/chat-channels.ts
index 4be41d5d61..75f805738b 100644
--- a/packages/shared/src/validators/chat-channels.ts
+++ b/packages/shared/src/validators/chat-channels.ts
@@ -76,8 +76,15 @@ export const createChatEndpointSchema = z
})
.strict();
+export const slackAppConfigurationSchema = z.object({
+ appName: z.string().trim().min(1, "Enter a Slack app name.").max(35),
+ botName: z.string().trim().min(1).max(80).regex(/^[a-z0-9._-]+$/, "Use lowercase letters, numbers, dots, hyphens, or underscores for the bot name."),
+ command: z.string().trim().min(2).max(32).regex(/^\/[a-z0-9_-]+$/, "Start the command with / and use lowercase letters, numbers, hyphens, or underscores."),
+}).strict();
+
export const updateChatEndpointSchema = z
.object({
+ slackApp: slackAppConfigurationSchema.optional(),
allowDirectMessages: z.boolean().optional(),
allowGroupChats: z.boolean().optional(),
allowUnlinkedPeople: z.boolean().optional(),
diff --git a/server/src/__tests__/chat-channels.integration.test.ts b/server/src/__tests__/chat-channels.integration.test.ts
index 27009fa58d..ec4a96a053 100644
--- a/server/src/__tests__/chat-channels.integration.test.ts
+++ b/server/src/__tests__/chat-channels.integration.test.ts
@@ -48,6 +48,7 @@ import {
chatEndpoints,
chatExternalPrincipals,
chatIdentityLinks,
+ joinRequests,
chatMessageLinks,
chatPublications,
chatSdkState,
@@ -119,6 +120,7 @@ import {
} from "../services/chat-teams-personal-recipient.js";
import * as discordQuestionForms from "../services/chat-discord-question-forms.js";
import { issueService } from "../services/issues.js";
+import { instanceSettingsService } from "../services/instance-settings.js";
import { getExternalChannelBindingSummary } from "../services/chat-channel-binding.js";
import { PaperclipRunnerToolAuthority } from "../services/native-runtime/paperclip-runner-tool-authority.js";
import { NativeChatAttachmentReadScope } from "../services/native-runtime/chat-attachment-read.js";
@@ -1575,15 +1577,11 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => {
},
"owner-user",
);
- if (overrides?.allowUnlinkedPeople !== undefined) {
- await context.service.update(
- endpoint.id,
- {
- allowUnlinkedPeople: overrides.allowUnlinkedPeople,
- },
- "owner-user",
- );
- }
+ // Most transport fixtures exercise restricted guests explicitly. Production
+ // Slack creation defaults to linked accounts only (covered separately).
+ await context.service.update(endpoint.id, {
+ allowUnlinkedPeople: overrides.allowUnlinkedPeople ?? true,
+ }, "owner-user");
await context.service.configure(
endpoint.id,
{
@@ -2912,6 +2910,7 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => {
assignedAgentId: fixture.assignedAgentId,
assignedAgentName: "Maya",
status: "draft",
+ allowUnlinkedPeople: false,
setup: { command: expect.stringMatching(/^\/maya-[a-z0-9]{6}$/) },
});
const createdCommand = createResponse.body.setup.command as string;
@@ -2947,6 +2946,26 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => {
);
});
+ it("persists Slack manifest draft details and the registered command, then locks them once connected", async () => {
+ const fixture = await seedCompany();
+ const { service } = createService();
+ const app = routesApp(db, fixture.companyId, service);
+ const endpoint = await service.create(fixture.companyId, { provider: "slack", assignedAgentId: fixture.assignedAgentId });
+ const slackApp = { appName: "Research Ops", botName: "research-ops", command: "/research" };
+ await request(app).patch(`/api/chat-endpoints/${endpoint.id}`).send({ slackApp }).expect(200);
+ expect((await service.get(endpoint.id)).setup).toMatchObject({ slackApp, command: "/research" });
+ const [stored] = await db.select().from(chatEndpoints).where(eq(chatEndpoints.id, endpoint.id));
+ expect(stored.setup.command).toBe("/research");
+ await request(app).patch(`/api/chat-endpoints/${endpoint.id}`)
+ .send({ slackApp: { ...slackApp, command: "not-a-command" } }).expect(400);
+ await db.update(chatEndpoints).set({ status: "verifying" }).where(eq(chatEndpoints.id, endpoint.id));
+ await request(app).patch(`/api/chat-endpoints/${endpoint.id}`)
+ .send({ slackApp: { ...slackApp, command: "/different" } }).expect(409);
+ expect((await service.get(endpoint.id)).setup.command).toBe("/research");
+ const github = await service.create(fixture.companyId, { provider: "github", assignedAgentId: fixture.assignedAgentId });
+ await request(app).patch(`/api/chat-endpoints/${github.id}`).send({ slackApp }).expect(422);
+ });
+
it("rejects chat endpoints for non-invokable agents", async () => {
const fixture = await seedCompany();
const { service } = createService();
@@ -12546,6 +12565,8 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => {
},
"owner-user",
);
+ expect(endpoint.allowUnlinkedPeople).toBe(false);
+ await service.update(endpoint.id, { allowUnlinkedPeople: true }, "owner-user");
const configured = await service.configure(
endpoint.id,
@@ -12673,6 +12694,7 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => {
{ provider: "slack", assignedAgentId: fixture.assignedAgentId },
"owner-user",
);
+ await service.update(endpoint.id, { allowUnlinkedPeople: true }, "owner-user");
await service.configure(
endpoint.id,
{
@@ -12795,6 +12817,63 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => {
}
});
+ it("paginates mixed activity beyond 100 rows without losing timestamp ties", async () => {
+ const fixture = await seedCompany();
+ const { service } = createService(new FakeChatSdkRuntime(), fakeSlackFetch());
+ const endpoint = await service.create(fixture.companyId, { provider: "slack", assignedAgentId: fixture.assignedAgentId }, "owner-user");
+ const other = await service.create(fixture.companyId, { provider: "slack", assignedAgentId: fixture.assignedAgentId }, "owner-user");
+ const createdAt = new Date("2026-01-01T00:00:00.123Z");
+ const deliveries = await db.insert(chatDeliveries).values(Array.from({ length: 110 }, (_, index) => ({
+ companyId: fixture.companyId, endpointId: endpoint.id,
+ providerEventId: `page-${index}`, deduplicationKey: `page-${index}`,
+ eventKind: "message" as const, normalizedEvent: {}, state: "processed" as const, createdAt,
+ }))).returning();
+ const actions = await db.insert(chatActions).values(Array.from({ length: 15 }, (_, index) => ({
+ companyId: fixture.companyId, endpointId: endpoint.id,
+ kind: "slack_session_sync", providerActionId: `page-${index}`,
+ // Activity for session actions follows updatedAt, not createdAt.
+ createdAt: new Date("2025-01-01T00:00:00Z"), updatedAt: createdAt,
+ }))).returning();
+ await db.insert(chatActions).values({ companyId: fixture.companyId, endpointId: other.id, kind: "slash_task_start", providerActionId: "other-endpoint", createdAt });
+ const expected = [...deliveries, ...actions].map((row) => row.id).sort((a, b) => b.localeCompare(a));
+ const found: string[] = [];
+ let cursor: string | undefined;
+ for (let page = 0; page < 5; page++) {
+ const result = await service.listActivityPage(endpoint.id, 25, cursor);
+ expect(result.items).toHaveLength(25);
+ found.push(...result.items.map((row) => row.id));
+ expect(Boolean(result.nextCursor)).toBe(page < 4);
+ cursor = result.nextCursor ?? undefined;
+ if (page === 0) {
+ // New arrivals must not shift the older pages.
+ await db.insert(chatActions).values({ companyId: fixture.companyId, endpointId: endpoint.id, kind: "slash_task_start", providerActionId: "new-arrival", createdAt: new Date("2026-01-02T00:00:00Z") });
+ }
+ }
+ expect(found).toEqual(expected);
+ expect(await service.listActivity(endpoint.id)).toHaveLength(100);
+ await expect(service.listActivityPage(endpoint.id, 0)).rejects.toMatchObject({ status: 400 });
+ await expect(service.listActivityPage(endpoint.id, 101)).rejects.toMatchObject({ status: 400 });
+ await expect(service.listActivityPage(endpoint.id, 25, "invalid")).rejects.toMatchObject({ status: 400 });
+ });
+
+ it("recognizes Slack callbacks behind TLS termination without trusting forwarded headers", async () => {
+ const fixture = await seedCompany();
+ const { endpoint, service } = await configuredSlackEndpoint(fixture);
+ const path = `/api/chat-webhooks/${endpoint.publicId}/slack`;
+ const body = JSON.stringify({ type: "url_verification", challenge: "proxy-check" });
+ const request = signedSlackWebhookRequest({ url: `http://paperclip.example${path}`, contentType: "application/json", body });
+ request.headers.set("x-forwarded-host", "untrusted.example");
+ request.headers.set("x-forwarded-proto", "https");
+ await service.handleWebhook(endpoint.publicId, "slack", request);
+ await expect(service.get(endpoint.id)).resolves.toMatchObject({ setup: { callbacksNeedUpdate: false, callbackSurfaces: { events: { status: "current" } } } });
+ // A different public host or port is still drift, even with TLS termination.
+ for (const publicBaseUrl of ["https://moved.example", "https://paperclip.example:8443"]) {
+ const moved = createService(new FakeChatSdkRuntime(), fakeSlackFetch(), { publicBaseUrl });
+ await expect(moved.service.get(endpoint.id)).resolves.toMatchObject({ setup: { callbacksNeedUpdate: true, callbackSurfaces: { events: { status: "stale" } } } });
+ await moved.service.shutdown();
+ }
+ });
+
it("tracks Slack callback surfaces independently and reports public URL drift", async () => {
const fixture = await seedCompany();
const { endpoint, runtime, service } =
@@ -13898,6 +13977,7 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => {
{ provider: "slack", assignedAgentId: fixture.assignedAgentId },
"owner-user",
);
+ await service.update(endpoint.id, { allowUnlinkedPeople: true }, "owner-user");
await service.configure(
endpoint.id,
{
@@ -19349,6 +19429,7 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => {
{ provider: "slack", assignedAgentId: fixture.assignedAgentId },
"owner-user",
);
+ await first.service.update(endpoint.id, { allowUnlinkedPeople: true }, "owner-user");
await first.service.configure(
endpoint.id,
{
@@ -19487,6 +19568,7 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => {
{ provider: "slack", assignedAgentId: fixture.assignedAgentId },
"owner-user",
);
+ await service.update(endpoint.id, { allowUnlinkedPeople: true }, "owner-user");
await service.configure(
endpoint.id,
{
@@ -20058,6 +20140,7 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => {
{ provider: "slack", assignedAgentId: fixture.assignedAgentId },
"owner-user",
);
+ await service.update(endpoint.id, { allowUnlinkedPeople: true }, "owner-user");
const signingSecret = "durable-ingress-signing-secret";
await service.configure(
endpoint.id,
@@ -20711,6 +20794,7 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => {
{ provider: "slack", assignedAgentId: fixture.assignedAgentId },
"owner-user",
);
+ await service.update(endpoint.id, { allowUnlinkedPeople: true }, "owner-user");
await service.configure(
endpoint.id,
{
@@ -22527,6 +22611,7 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => {
{ provider: "slack", assignedAgentId: fixture.assignedAgentId },
"owner-user",
);
+ await service.update(endpoint.id, { allowUnlinkedPeople: true }, "owner-user");
await service.configure(
endpoint.id,
{
@@ -27593,6 +27678,7 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => {
},
"owner-user",
);
+ await service.update(endpoint.id, { allowUnlinkedPeople: true }, "owner-user");
await service.configure(
endpoint.id,
{
@@ -28460,6 +28546,7 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => {
[blockedEndpoint, "xoxb-blocked-outbox"],
[readyEndpoint, "xoxb-ready-outbox"],
] as const) {
+ await service.update(endpoint.id, { allowUnlinkedPeople: true }, "owner-user");
await service.configure(
endpoint.id,
{
@@ -46228,6 +46315,94 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => {
});
});
+ it("discovers a Slack connect identity without starting work or granting access", async () => {
+ await instanceSettingsService(db).updateExperimental({ enableChatConnectors: true });
+ const fixture = await seedCompany();
+ const { callbacks, endpoint, runtime, service, wakeup } = await configuredSlackEndpoint(fixture, { allowUnlinkedPeople: false });
+ const post = vi.fn();
+ const postEphemeral = vi.fn(async () => ({ id: "connect-notice", usedFallback: false }));
+ const event = {
+ endpointId: endpoint.id, provider: "slack" as const,
+ event: {
+ channel: { id: "C-CONNECT", isDM: false, post, postEphemeral } as never,
+ command: endpoint.setup.command!, text: "connect", triggerId: "connect-discovery-1",
+ user: { userId: "U-CONNECT", userName: "connector", fullName: "Connect Person", isBot: false, isMe: false, isSystem: false },
+ raw: { trigger_id: "connect-discovery-1" }, adapter: {} as never, openModal: async () => undefined,
+ },
+ };
+ await callbacks.onSlashCommand!(event);
+ await callbacks.onSlashCommand!(event);
+ await vi.waitFor(() => expect(postEphemeral).toHaveBeenCalledTimes(1));
+ const [identity] = await service.listPrincipals(endpoint.id);
+ expect(identity).toMatchObject({ externalLabel: "Connect Person", status: "pending", paperclipUserId: null, lastConnectAt: expect.any(String) });
+ expect(await service.listConversations(endpoint.id)).toHaveLength(0);
+ expect(wakeup).not.toHaveBeenCalled();
+ expect(post).not.toHaveBeenCalled();
+ expect(await db.select().from(chatActions).where(and(eq(chatActions.endpointId, endpoint.id), eq(chatActions.kind, "slack_connect")))).toHaveLength(1);
+ expect(await db.select().from(chatActions).where(and(eq(chatActions.endpointId, endpoint.id), eq(chatActions.kind, "slash_task_start")))).toHaveLength(0);
+ const other = await service.create(fixture.companyId, { provider: "slack", assignedAgentId: fixture.assignedAgentId }, "owner-user");
+ await db.update(chatEndpoints).set({ status: "verifying", providerAccountId: (await service.get(endpoint.id)).providerAccountId }).where(eq(chatEndpoints.id, other.id));
+ expect((await service.listPrincipals(other.id))[0]?.lastConnectAt).toBeNull();
+ const notice = String((postEphemeral.mock.calls[0] as unknown[])[1]);
+ const token = /token=([A-Za-z0-9_-]+)/.exec(notice)![1];
+ expect(notice).toContain("Connect your Paperclip account");
+ expect((postEphemeral.mock.calls[0] as unknown[])[2]).toEqual({ fallbackToDM: false });
+ expect(await service.previewIdentityLink(token, "owner-user")).toMatchObject({ selfService: true, canConfirm: true, externalLabel: "Connect Person" });
+ expect(await service.setupTestStatus(endpoint.id, "owner-user")).toEqual({ messageReceivedAt: null });
+ await expect(service.finishSlackSetup(endpoint.id, "owner-user")).rejects.toMatchObject({ status: 403 });
+ const outsiderId = `outsider-${fixture.companyId}`;
+ const now = new Date();
+ await db.insert(authUsers).values({ id: outsiderId, name: "Outside Person", email: `${outsiderId}@example.test`, emailVerified: true, createdAt: now, updatedAt: now });
+ const outsideApp = routesApp(db, randomUUID(), service, outsiderId);
+ expect((await request(outsideApp).get(`/api/chat-identity-links/preview?token=${token}`)).body).toMatchObject({ selfService: true, canConfirm: false });
+ await expect(service.confirmIdentityLink(token, outsiderId)).rejects.toMatchObject({ status: 403 });
+ await request(outsideApp).post("/api/chat-identity-links/confirm").send({ token }).expect(403);
+ expect((await request(outsideApp).post("/api/chat-identity-links/request-access").send({ token })).body).toMatchObject({ status: "pending_approval" });
+ await service.requestIdentityAccess(token, outsiderId, "test");
+ expect(await db.select().from(joinRequests).where(eq(joinRequests.companyId, fixture.companyId))).toHaveLength(1);
+ expect(await db.select().from(companyMemberships).where(and(eq(companyMemberships.companyId, fixture.companyId), eq(companyMemberships.principalId, outsiderId)))).toHaveLength(0);
+ const adminOnly = await service.createLinkIntent(other.id, identity.principalId, 600);
+ const adminToken = new URL(adminOnly.confirmationUrl).searchParams.get("token")!;
+ expect((await request(outsideApp).get(`/api/chat-identity-links/preview?token=${adminToken}`)).status).toBe(404);
+ await expect(service.requestIdentityAccess(adminToken, outsiderId, "test")).rejects.toMatchObject({ status: 403 });
+ const providerRuntime = runtime.endpoints.get(endpoint.id)!;
+ const originalThread = providerRuntime.thread.bind(providerRuntime);
+ const confirmationNotice = vi.fn(async () => ({ id: "linked-notice", threadId: "C-CONNECT" }));
+ providerRuntime.thread = (id: string) => ({ ...originalThread(id), postEphemeral: confirmationNotice });
+ await service.confirmIdentityLink(token, "owner-user");
+ await vi.waitFor(() => expect(confirmationNotice).toHaveBeenCalledWith("U-CONNECT", expect.stringContaining("account is connected"), { fallbackToDM: false }));
+ expect((await service.listPrincipals(endpoint.id))[0]).toMatchObject({ status: "linked", paperclipUserId: "owner-user" });
+ await expect(service.test(endpoint.id)).rejects.toMatchObject({ details: { code: "chat_test_follow_up_missing" } });
+ await expect(service.confirmIdentityLink(token, "owner-user")).rejects.toMatchObject({ status: 422 });
+ await request(outsideApp).post("/api/chat-identity-links/request-access").send({ token }).expect(422);
+ expect(await service.setupTestStatus(endpoint.id, "owner-user")).toEqual({ messageReceivedAt: null });
+ const finished = await service.finishSlackSetup(endpoint.id, "owner-user");
+ expect(finished).toMatchObject({ status: "active", setup: { step: "complete", testSkipped: true } });
+ expect(wakeup).not.toHaveBeenCalled();
+ });
+
+ it.each(["message", "mention", "slash"] as const)("scopes Slack setup %s detection to the linked user and current test", async (kind) => {
+ const fixture = await seedCompany();
+ const { endpoint, service } = await configuredSlackEndpoint(fixture);
+ const now = new Date();
+ const [principal] = await db.insert(chatExternalPrincipals).values({ companyId: fixture.companyId, provider: "slack", providerAccountId: (await service.get(endpoint.id)).providerAccountId!, externalId: "U-TEST", kind: "user", displayName: "Test" }).returning();
+ const intent = await service.createLinkIntent(endpoint.id, principal.id, 600);
+ const token = new URL(intent.confirmationUrl).searchParams.get("token")!;
+ await db.update(chatIdentityLinks).set({ expiresAt: new Date(now.getTime() - 1) }).where(eq(chatIdentityLinks.principalId, principal.id));
+ await expect(service.confirmIdentityLink(token, "owner-user")).rejects.toMatchObject({ status: 422 });
+ const fresh = await service.createLinkIntent(endpoint.id, principal.id, 600);
+ await service.confirmIdentityLink(new URL(fresh.confirmationUrl).searchParams.get("token")!, "owner-user");
+ await db.insert(chatActions).values({ companyId: fixture.companyId, endpointId: endpoint.id, principalId: principal.id, kind: "slash_task_start", providerActionId: "old-test-message", createdAt: new Date(now.getTime() - 60_000), status: "processed" });
+ expect(await service.setupTestStatus(endpoint.id, "owner-user")).toEqual({ messageReceivedAt: null });
+ if (kind === "slash") {
+ await db.insert(chatActions).values({ companyId: fixture.companyId, endpointId: endpoint.id, principalId: principal.id, kind: "slash_task_start", providerActionId: "current-test-message", status: "processed" });
+ } else {
+ await db.insert(chatDeliveries).values({ companyId: fixture.companyId, endpointId: endpoint.id, principalId: principal.id, providerEventId: "current-test-message", deduplicationKey: "current-test-message", eventKind: kind, normalizedEvent: {}, state: "processed" });
+ }
+ expect(await service.setupTestStatus(endpoint.id, "owner-user")).toMatchObject({ messageReceivedAt: expect.any(String) });
+ expect(await service.setupTestStatus(endpoint.id, "someone-else")).toEqual({ messageReceivedAt: null });
+ });
+
it("turns a Slack slash command into a new native thread and one Paperclip task", async () => {
const fixture = await seedCompany();
const { callbacks, endpoint, runtime, service } =
diff --git a/server/src/__tests__/openapi-routes.test.ts b/server/src/__tests__/openapi-routes.test.ts
index 9e29753867..f7b4698803 100644
--- a/server/src/__tests__/openapi-routes.test.ts
+++ b/server/src/__tests__/openapi-routes.test.ts
@@ -573,7 +573,7 @@ describe("openapi routes", () => {
const activity =
spec.paths["/api/chat-endpoints/{endpointId}/activity"].get.responses[
"200"
- ].content["application/json"].schema.items;
+ ].content["application/json"].schema.oneOf[0].items;
expect(activity.properties.actionType.enum).toEqual([
"slash_task_start",
"provider_effect",
diff --git a/server/src/routes/chat-channels.identity.test.ts b/server/src/routes/chat-channels.identity.test.ts
index c54c785136..67aa4d9dec 100644
--- a/server/src/routes/chat-channels.identity.test.ts
+++ b/server/src/routes/chat-channels.identity.test.ts
@@ -1,12 +1,16 @@
import express, { type Request } from "express";
import type { Db } from "@paperclipai/db";
import request from "supertest";
-import { describe, expect, it, vi } from "vitest";
+import { beforeEach, describe, expect, it, vi } from "vitest";
import { HttpError, unprocessable } from "../errors.js";
import { errorHandler } from "../middleware/index.js";
import type { ChatChannelService } from "../services/chat-channels.js";
import { chatChannelRoutes } from "./chat-channels.js";
+const settings = vi.hoisted(() => ({ getExperimental: vi.fn() }));
+vi.mock("../services/instance-settings.js", () => ({ instanceSettingsService: () => settings }));
+beforeEach(() => settings.getExperimental.mockResolvedValue({ enableChatConnectors: true }));
+
const token = "synthetic-identity-preview-token-for-route-test";
const preview = {
companyId: "company-a",
@@ -30,7 +34,10 @@ function fixture(
},
) {
const previewIdentityLink = vi.fn().mockResolvedValue(preview);
+ const confirmIdentityLink = vi.fn();
+ const requestIdentityAccess = vi.fn();
const app = express();
+ app.use(express.json());
app.use((req, _res, next) => {
req.actor = actor;
next();
@@ -38,15 +45,26 @@ function fixture(
app.use(
"/api",
chatChannelRoutes({} as Db, {
- service: { previewIdentityLink } as unknown as ChatChannelService,
+ service: { previewIdentityLink, confirmIdentityLink, requestIdentityAccess } as unknown as ChatChannelService,
heartbeat: { wakeup: vi.fn() },
}),
);
app.use(errorHandler);
- return { app, previewIdentityLink };
+ return { app, previewIdentityLink, confirmIdentityLink, requestIdentityAccess };
}
describe("chat identity-link preview authority", () => {
+ it.each([false, undefined])("blocks every identity API when chat rollout is disabled (%s)", async (enabled) => {
+ settings.getExperimental.mockResolvedValue({ enableChatConnectors: enabled });
+ const f = fixture();
+ await request(f.app).get("/api/chat-identity-links/preview").query({ token }).expect(403);
+ await request(f.app).post("/api/chat-identity-links/confirm").send({ token }).expect(403);
+ await request(f.app).post("/api/chat-identity-links/request-access").send({ token }).expect(403);
+ expect(f.previewIdentityLink).not.toHaveBeenCalled();
+ expect(f.confirmIdentityLink).not.toHaveBeenCalled();
+ expect(f.requestIdentityAccess).not.toHaveBeenCalled();
+ });
+
it("returns the preview to a Board member of its exact company", async () => {
const { app, previewIdentityLink } = fixture();
const response = await request(app)
@@ -54,7 +72,7 @@ describe("chat identity-link preview authority", () => {
.query({ token });
expect(response.status).toBe(200);
expect(response.body).toEqual(preview);
- expect(previewIdentityLink).toHaveBeenCalledExactlyOnceWith(token);
+ expect(previewIdentityLink).toHaveBeenCalledExactlyOnceWith(token, "viewer");
});
it.each([false, true])(
diff --git a/server/src/routes/chat-channels.ts b/server/src/routes/chat-channels.ts
index f0eac96246..260caa4c56 100644
--- a/server/src/routes/chat-channels.ts
+++ b/server/src/routes/chat-channels.ts
@@ -26,6 +26,7 @@ import {
type ChatChannelServiceOptions,
} from "../services/chat-channels.js";
import { accessService } from "../services/access.js";
+import { instanceSettingsService } from "../services/instance-settings.js";
import { recordChatWebhookStage } from "../services/chat-webhook-diagnostics.js";
import {
createInviteRateLimiter,
@@ -87,6 +88,18 @@ export function chatChannelRoutes(db: Db, options: ChatChannelRouteOptions) {
const service = options.service ?? chatChannelService(db, options);
const access = accessService(db);
+ async function assertIdentityLinkAccess(req: ExpressRequest): Promise<string> {
+ assertBoard(req);
+ const userId = actorUserId(req);
+ if (!userId) throw badRequest("A signed-in Paperclip user is required");
+ // Enforce rollout here: invited nonmembers cannot read the board's
+ // experimental-settings API. A private token never bypasses this gate.
+ if (!(await instanceSettingsService(db).getExperimental()).enableChatConnectors) {
+ throw forbidden("Chat connectors are not enabled on this instance");
+ }
+ return userId;
+ }
+
async function assertConnectionManager(
req: ExpressRequest,
companyId: string,
@@ -186,6 +199,20 @@ export function chatChannelRoutes(db: Db, options: ChatChannelRouteOptions) {
res.json(await service.test(endpointId(req)));
});
+ router.post("/chat-endpoints/:endpointId/finish", async (req, res) => {
+ if (!(await assertEndpointManagementAccess(req, res))) return;
+ const userId = actorUserId(req);
+ if (!userId) throw badRequest("A signed-in Paperclip user is required");
+ res.json(await service.finishSlackSetup(endpointId(req), userId));
+ });
+ router.get("/chat-endpoints/:endpointId/test-status", async (req, res) => {
+ if (!(await assertEndpointAccess(req, res, service))) return;
+ const userId = actorUserId(req);
+ if (!userId) throw badRequest("A signed-in Paperclip user is required");
+ res.set("Cache-Control", "no-store");
+ res.json(await service.setupTestStatus(endpointId(req), userId));
+ });
+
router.get("/chat-endpoints/:endpointId/resources", async (req, res) => {
if (!(await assertEndpointAccess(req, res, service))) return;
res.json(await service.listResources(endpointId(req)));
@@ -244,28 +271,30 @@ export function chatChannelRoutes(db: Db, options: ChatChannelRouteOptions) {
"/chat-identity-links/confirm",
validate(confirmChatIdentityLinkSchema),
async (req, res) => {
- assertBoard(req);
- const userId = actorUserId(req);
- if (!userId) throw badRequest("A signed-in Paperclip user is required");
+ const userId = await assertIdentityLinkAccess(req);
res.json(await service.confirmIdentityLink(req.body.token, userId));
},
);
+ router.post("/chat-identity-links/request-access", validate(confirmChatIdentityLinkSchema), async (req, res) => {
+ const userId = await assertIdentityLinkAccess(req);
+ res.json(await service.requestIdentityAccess(req.body.token, userId, req.ip ?? "unknown"));
+ });
+
router.get("/chat-identity-links/preview", async (req, res) => {
- assertBoard(req);
+ const userId = await assertIdentityLinkAccess(req);
const token = typeof req.query.token === "string" ? req.query.token : "";
if (token.length < 32 || token.length > 4096)
throw badRequest("A valid identity-link token is required");
- const preview = await getAccessibleResource(
- req,
- res,
- service.previewIdentityLink(token).catch((error) => {
- // Do not distinguish a valid foreign-company token from an invalid or
- // expired token. Confirmation keeps its own validation contract.
- if (error instanceof HttpError && error.status === 422) return null;
- throw error;
- }),
- "Identity-link request not found",
+ res.set("Cache-Control", "no-store");
+ const invitation = await service.previewIdentityLink(token, userId).catch((error) => {
+ if (error instanceof HttpError && error.status === 422) return null;
+ throw error;
+ });
+ // A link privately issued to a signed Slack sender is an invitation to
+ // request membership. Other link intents retain company-access checks.
+ const preview = invitation?.selfService ? invitation : await getAccessibleResource(
+ req, res, Promise.resolve(invitation), "Identity-link request not found",
);
if (!preview) return;
res.json(preview);
@@ -278,7 +307,13 @@ export function chatChannelRoutes(db: Db, options: ChatChannelRouteOptions) {
router.get("/chat-endpoints/:endpointId/activity", async (req, res) => {
if (!(await assertEndpointAccess(req, res, service))) return;
- res.json(await service.listActivity(endpointId(req)));
+ if (req.query.limit !== undefined || req.query.cursor !== undefined) {
+ if ((req.query.limit !== undefined && (typeof req.query.limit !== "string" || !/^\d+$/.test(req.query.limit)))
+ || (req.query.cursor !== undefined && typeof req.query.cursor !== "string")) throw badRequest("Invalid activity pagination parameters");
+ res.json(await service.listActivityPage(endpointId(req), req.query.limit === undefined ? 25 : Number(req.query.limit), req.query.cursor as string | undefined));
+ } else {
+ res.json(await service.listActivity(endpointId(req)));
+ }
});
router.post(
diff --git a/server/src/routes/openapi.ts b/server/src/routes/openapi.ts
index ec4b76f2d1..2b1a21d03a 100644
--- a/server/src/routes/openapi.ts
+++ b/server/src/routes/openapi.ts
@@ -860,6 +860,8 @@ const chatIdentityLinkIntentResponseSchema = z
const chatIdentityLinkPreviewResponseSchema = z
.object({
+ selfService: z.boolean().optional(),
+ canConfirm: z.boolean().optional(),
endpointId: z.string().uuid(),
companyId: z.string().uuid(),
companyName: z.string(),
@@ -1474,6 +1476,8 @@ const BOARD_ONLY_OPERATIONS = new Set([
"POST /api/chat-endpoints/{endpointId}/setup",
"POST /api/chat-endpoints/{endpointId}/setup-secret",
"POST /api/chat-endpoints/{endpointId}/test",
+ "POST /api/chat-endpoints/{endpointId}/finish",
+ "GET /api/chat-endpoints/{endpointId}/test-status",
"POST /api/chat-endpoints/{endpointId}/photon/inspect",
"GET /api/chat-endpoints/{endpointId}/resources",
"PUT /api/chat-endpoints/{endpointId}/resources",
@@ -1482,6 +1486,7 @@ const BOARD_ONLY_OPERATIONS = new Set([
"DELETE /api/chat-endpoints/{endpointId}/principals/{principalId}/link",
"POST /api/chat-identity-links/confirm",
"GET /api/chat-identity-links/preview",
+ "POST /api/chat-identity-links/request-access",
"GET /api/chat-endpoints/{endpointId}/conversations",
"GET /api/chat-endpoints/{endpointId}/activity",
"POST /api/chat-endpoints/{endpointId}/deliveries/{deliveryId}/replay",
@@ -2223,6 +2228,27 @@ registry.registerPath({
},
});
+registry.registerPath({
+ method: "post", path: "/api/chat-endpoints/{endpointId}/finish", tags: ["chat-channels"],
+ summary: "Finish Slack onboarding with an optional conversation test",
+ description: "Requires a verified Slack webhook and an authorized identity linked to the current user. Records that a full conversation test was not required.",
+ request: { params: z.object({ endpointId: z.string().uuid() }) },
+ responses: { 200: r.ok(chatEndpointResponseSchema), 401: r.unauthorized, 403: r.forbidden, 404: r.notFound, 409: r.conflict },
+});
+registry.registerPath({
+ method: "get", path: "/api/chat-endpoints/{endpointId}/test-status", tags: ["chat-channels"],
+ summary: "Check for the current user's first setup message",
+ request: { params: z.object({ endpointId: z.string().uuid() }) },
+ responses: { 200: r.ok(z.object({ messageReceivedAt: z.string().nullable() })), 401: r.unauthorized, 403: r.forbidden, 404: r.notFound },
+});
+registry.registerPath({
+ method: "post", path: "/api/chat-identity-links/request-access", tags: ["chat-channels"],
+ summary: "Request company membership using a private Slack identity link",
+ description: "Creates a pending human join request for admin approval. Requires a valid, unexpired self-service token and a signed-in user. Does not grant access or link an identity.",
+ request: { body: jsonBody(confirmChatIdentityLinkSchema) },
+ responses: { 200: r.ok(z.object({ status: z.enum(["member", "pending_approval"]) })), 401: r.unauthorized, 403: r.forbidden, 422: r.unprocessable },
+});
+
registry.registerPath({
method: "post",
path: "/api/chat-endpoints/{endpointId}/test",
@@ -2346,7 +2372,7 @@ registry.registerPath({
tags: ["chat-channels"],
summary: "Preview an external identity-link intent",
description:
- "Returns the company and provider identity that a valid, unexpired confirmation token would link. Company membership is checked before returning the preview.",
+ "Returns the company and provider identity that a valid, unexpired confirmation token would link. Admin-created links require company access. Private links issued to a signed Slack sender allow a signed-in recipient to preview that identity and request company access.",
request: {
query: z.object({ token: z.string().min(32).max(4096) }).strict(),
},
@@ -2399,10 +2425,11 @@ registry.registerPath({
tags: ["chat-channels"],
summary: "List chat endpoint delivery and publication activity",
description:
- "Returns the endpoint's recent redacted inbound-delivery and outbound-publication ledger, including whether a failed item can be replayed.",
- request: { params: z.object({ endpointId: z.string().uuid() }) },
+ "Returns the endpoint's recent redacted inbound-delivery and outbound-publication ledger, including whether a failed item can be replayed. Supply limit (1–100) for a page object and follow nextCursor for older activity. Requests without pagination parameters retain the legacy recent-100 array.",
+ request: { params: z.object({ endpointId: z.string().uuid() }), query: z.object({ limit: z.coerce.number().int().min(1).max(100).optional(), cursor: z.string().max(256).optional() }) },
responses: {
- 200: r.ok(z.array(chatActivityResponseSchema)),
+ 200: r.ok(z.union([z.array(chatActivityResponseSchema), z.object({ items: z.array(chatActivityResponseSchema), nextCursor: z.string().nullable() })])),
+ 400: r.badRequest,
401: r.unauthorized,
403: r.forbidden,
404: r.notFound,
diff --git a/server/src/services/chat-channels.ts b/server/src/services/chat-channels.ts
index a8531e21df..6edefa604a 100644
--- a/server/src/services/chat-channels.ts
+++ b/server/src/services/chat-channels.ts
@@ -89,6 +89,8 @@ import {
issueThreadInteractions,
issueQuestionResponseDeliveries,
issues,
+ invites,
+ joinRequests,
toolApplications,
toolConnections,
} from "@paperclipai/db";
@@ -520,6 +522,21 @@ function canonicalCallbackUrl(value: string): string | null {
}
}
+// TLS terminates at a reverse proxy in many self-hosted deployments. The
+// transport scheme is not evidence of URL drift; authority and path still are.
+// This is diagnostic only: it does not trust forwarded headers or change auth.
+function slackCallbackMatchesPublicUrl(observed: string, current: string): boolean {
+ const canonical = canonicalCallbackUrl(observed);
+ if (canonical === current) return true;
+ if (!canonical) return false;
+ const observedUrl = new URL(canonical);
+ const currentUrl = new URL(current);
+ return observedUrl.protocol === "http:"
+ && currentUrl.protocol === "https:"
+ && observedUrl.host === currentUrl.host
+ && observedUrl.pathname === currentUrl.pathname;
+}
+
type SlackCallbackInspection = {
surface: SlackCallbackSurface;
url: string;
@@ -2629,7 +2646,7 @@ function providerSetupState(
return {
status:
currentUrl !== null &&
- canonicalCallbackUrl(observation.url) === currentUrl
+ slackCallbackMatchesPublicUrl(observation.url, currentUrl)
? "current"
: "stale",
observedAt: observation.observedAt,
@@ -2642,6 +2659,8 @@ function providerSetupState(
};
return {
step,
+ testStartedAt: endpoint.setup.testStartedAt ?? null,
+ testSkipped: endpoint.setup.testSkipped ?? false,
authorizationUrl: "https://api.slack.com/apps?new_app=1",
providerUrl: "https://app.slack.com/",
webhookUrl,
@@ -2650,6 +2669,7 @@ function providerSetupState(
callbacksNeedUpdate: Object.values(callbackSurfaces).some(
(surface) => surface.status === "stale",
),
+ slackApp: endpoint.setup.slackApp,
// Slack registers the slash command in the provider configuration.
// Keep that identity immutable when the assigned agent is renamed;
// deriving it remains only a compatibility path for older rows.
@@ -5978,7 +5998,7 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) {
// enables that surface, even when this process is running against a
// database created before the column default was hardened.
allowGroupChats: input.provider !== "microsoft-teams",
- allowUnlinkedPeople: input.provider !== "imessage-photon",
+ allowUnlinkedPeople: !["slack", "imessage-photon"].includes(input.provider),
capabilities: CAPABILITIES[input.provider],
setup: {
step: "provider_setup",
@@ -6023,6 +6043,19 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) {
const values: Partial<typeof chatEndpoints.$inferInsert> = {
updatedAt: new Date(),
};
+ if (input.slackApp) {
+ if (existing.endpoint.provider !== "slack") {
+ throw unprocessable("Slack app details only apply to Slack connections");
+ }
+ if (existing.endpoint.status !== "draft" || existing.endpoint.botExternalId) {
+ throw conflict("Slack app details can only be edited before connecting the app");
+ }
+ values.setup = {
+ ...existing.endpoint.setup,
+ slackApp: input.slackApp,
+ command: input.slackApp.command,
+ };
+ }
if (input.allowDirectMessages !== undefined)
values.allowDirectMessages = input.allowDirectMessages;
if (input.allowGroupChats && existing.endpoint.provider === "imessage-photon" && (!existing.endpoint.botExternalId || existing.endpoint.botExternalId.startsWith("photon-project:")))
@@ -9879,7 +9912,44 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) {
return get(endpoint.id);
}
- async function test(endpointId: string) {
+ async function findAuthorizedIdentityLink(endpoint: EndpointRow, userId: string) {
+ return db.select({ id: chatIdentityLinks.id }).from(chatIdentityLinks)
+ .innerJoin(companyMemberships, and(
+ eq(companyMemberships.companyId, chatIdentityLinks.companyId), eq(companyMemberships.principalType, "user"),
+ eq(companyMemberships.principalId, userId), eq(companyMemberships.status, "active"), ne(companyMemberships.membershipRole, "viewer"),
+ ))
+ .where(and(eq(chatIdentityLinks.companyId, endpoint.companyId), eq(chatIdentityLinks.endpointId, endpoint.id),
+ eq(chatIdentityLinks.paperclipUserId, userId), eq(chatIdentityLinks.status, "linked")))
+ .limit(1).then((rows) => rows[0] ?? null);
+ }
+
+ async function setupTestStatus(endpointId: string, userId: string) {
+ const record = await endpointRecord(endpointId);
+ if (!record) throw notFound("Chat endpoint not found");
+ const startedAt = record.endpoint.setup.testStartedAt;
+ if (!startedAt) return { messageReceivedAt: null };
+ const links = await db.select({ principalId: chatIdentityLinks.principalId }).from(chatIdentityLinks).where(and(
+ eq(chatIdentityLinks.companyId, record.endpoint.companyId), eq(chatIdentityLinks.endpointId, endpointId),
+ eq(chatIdentityLinks.paperclipUserId, userId), eq(chatIdentityLinks.status, "linked"),
+ ));
+ if (!links.length) return { messageReceivedAt: null };
+ const principalIds = links.map((link) => link.principalId);
+ const [delivery, command] = await Promise.all([
+ db.select({ at: chatDeliveries.createdAt }).from(chatDeliveries).where(and(
+ eq(chatDeliveries.companyId, record.endpoint.companyId), eq(chatDeliveries.endpointId, endpointId),
+ inArray(chatDeliveries.principalId, principalIds), gte(chatDeliveries.createdAt, new Date(startedAt)),
+ inArray(chatDeliveries.eventKind, ["message", "mention"]),
+ )).orderBy(asc(chatDeliveries.createdAt)).limit(1).then((rows) => rows[0]),
+ db.select({ at: chatActions.createdAt }).from(chatActions).where(and(
+ eq(chatActions.companyId, record.endpoint.companyId), eq(chatActions.endpointId, endpointId),
+ inArray(chatActions.principalId, principalIds), eq(chatActions.kind, "slash_task_start"), gte(chatActions.createdAt, new Date(startedAt)),
+ )).orderBy(asc(chatActions.createdAt)).limit(1).then((rows) => rows[0]),
+ ]);
+ const at = [delivery?.at, command?.at].filter((value): value is Date => Boolean(value)).sort((a, b) => a.getTime() - b.getTime())[0];
+ return { messageReceivedAt: at?.toISOString() ?? null };
+ }
+
+ async function test(endpointId: string, finishOptions?: { optionalSlackTestForUser: string }) {
const initial = await endpointRecord(endpointId);
if (!initial) throw notFound("Chat endpoint not found");
return withCredentialMutationLease(
@@ -9901,135 +9971,151 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) {
const testStartedAt = testStartedAtValue
? new Date(testStartedAtValue)
: null;
- if (
- !endpoint.lastEventAt ||
- !testStartedAtValue ||
- !testStartedAt ||
- Number.isNaN(testStartedAt.getTime()) ||
- endpoint.lastEventAt < testStartedAt
- ) {
- throw conflict(
- "Send the test message in the provider before completing setup",
- {
- code: "chat_test_message_missing",
- },
- );
+ const optionalSlackTest = Boolean(finishOptions?.optionalSlackTestForUser);
+ if (optionalSlackTest) {
+ if (endpoint.provider !== "slack" || !endpoint.setup.webhookVerifiedAt || !endpoint.providerAccountId) {
+ throw conflict("Verify the Slack connection before finishing setup");
+ }
+ const linked = await findAuthorizedIdentityLink(endpoint, finishOptions!.optionalSlackTestForUser);
+ if (!linked) throw forbidden("Connect your Slack account before finishing setup");
}
- const requiredTrigger =
- ["telegram", "imessage-photon"].includes(endpoint.provider)
- ? "direct_message"
- : "subscribed_message";
- const qualifyingDelivery = await db
- .select({
- id: chatDeliveries.id,
- conversationId: chatDeliveries.conversationId,
- processedAt: chatDeliveries.processedAt,
- })
- .from(chatDeliveries)
- .where(
- and(
- eq(chatDeliveries.companyId, endpoint.companyId),
- eq(chatDeliveries.endpointId, endpoint.id),
- eq(chatDeliveries.state, "processed"),
- gte(chatDeliveries.processedAt, testStartedAt),
- sql`${chatDeliveries.normalizedEvent}->>'trigger' = ${requiredTrigger}`,
- ),
- )
- .orderBy(desc(chatDeliveries.processedAt))
- .limit(1)
- .then((rows) => rows[0] ?? null);
- if (
- !qualifyingDelivery?.conversationId ||
- !qualifyingDelivery.processedAt
- ) {
- throw conflict(
+ if (!optionalSlackTest) {
+ if (
+ !endpoint.lastEventAt ||
+ !testStartedAtValue ||
+ !testStartedAt ||
+ Number.isNaN(testStartedAt.getTime()) ||
+ endpoint.lastEventAt < testStartedAt
+ ) {
+ throw conflict(
+ "Send the test message in the provider before completing setup",
+ {
+ code: "chat_test_message_missing",
+ },
+ );
+ }
+ const requiredTrigger =
["telegram", "imessage-photon"].includes(endpoint.provider)
- ? "Send the test direct message before completing setup"
- : "Reply once without mentioning the agent before completing setup",
- { code: "chat_test_follow_up_missing" },
- );
- }
- const finalPublication = await db
- .select({
- commentId: chatPublications.commentId,
- payload: chatPublications.payload,
- })
- .from(chatPublications)
- .innerJoin(
- issueComments,
- and(
- eq(issueComments.id, chatPublications.commentId),
- eq(issueComments.companyId, chatPublications.companyId),
- eq(issueComments.issueId, chatPublications.issueId),
- eq(issueComments.authorType, "agent"),
- eq(issueComments.authorAgentId, endpoint.assignedAgentId),
- ),
- )
- .innerJoin(
- chatMessageLinks,
- and(
- eq(chatMessageLinks.companyId, chatPublications.companyId),
- eq(chatMessageLinks.endpointId, chatPublications.endpointId),
- eq(
- chatMessageLinks.conversationId,
- chatPublications.conversationId,
+ ? "direct_message"
+ : "subscribed_message";
+ const qualifyingDelivery = await db
+ .select({
+ id: chatDeliveries.id,
+ conversationId: chatDeliveries.conversationId,
+ processedAt: chatDeliveries.processedAt,
+ })
+ .from(chatDeliveries)
+ .where(
+ and(
+ eq(chatDeliveries.companyId, endpoint.companyId),
+ eq(chatDeliveries.endpointId, endpoint.id),
+ eq(chatDeliveries.state, "processed"),
+ gte(chatDeliveries.processedAt, testStartedAt),
+ sql`${chatDeliveries.normalizedEvent}->>'trigger' = ${requiredTrigger}`,
),
- eq(chatMessageLinks.deliveryId, qualifyingDelivery.id),
- eq(chatMessageLinks.direction, "inbound"),
- isNotNull(chatMessageLinks.commentId),
- ),
- )
- .innerJoin(
- heartbeatRuns,
- and(
- eq(heartbeatRuns.id, issueComments.createdByRunId),
- eq(heartbeatRuns.companyId, chatPublications.companyId),
- eq(heartbeatRuns.agentId, endpoint.assignedAgentId),
- eq(heartbeatRuns.status, "succeeded"),
- eq(
- sql<string>`${heartbeatRuns.contextSnapshot} ->> 'issueId'`,
- sql<string>`${chatPublications.issueId}::text`,
+ )
+ .orderBy(desc(chatDeliveries.processedAt))
+ .limit(1)
+ .then((rows) => rows[0] ?? null);
+ if (
+ !qualifyingDelivery?.conversationId ||
+ !qualifyingDelivery.processedAt
+ ) {
+ throw conflict(
+ ["telegram", "imessage-photon"].includes(endpoint.provider)
+ ? "Send the test direct message before completing setup"
+ : "Reply once without mentioning the agent before completing setup",
+ { code: "chat_test_follow_up_missing" },
+ );
+ }
+ const finalPublication = await db
+ .select({
+ commentId: chatPublications.commentId,
+ payload: chatPublications.payload,
+ })
+ .from(chatPublications)
+ .innerJoin(
+ issueComments,
+ and(
+ eq(issueComments.id, chatPublications.commentId),
+ eq(issueComments.companyId, chatPublications.companyId),
+ eq(issueComments.issueId, chatPublications.issueId),
+ eq(issueComments.authorType, "agent"),
+ eq(issueComments.authorAgentId, endpoint.assignedAgentId),
),
- or(
- sql`${chatMessageLinks.commentId}::text = ${heartbeatRuns.contextSnapshot} ->> 'wakeCommentId'`,
- sql`${chatMessageLinks.commentId}::text = ${heartbeatRuns.contextSnapshot} ->> 'commentId'`,
- sql`coalesce(${heartbeatRuns.contextSnapshot} -> 'wakeCommentIds', '[]'::jsonb) ? ${chatMessageLinks.commentId}::text`,
+ )
+ .innerJoin(
+ chatMessageLinks,
+ and(
+ eq(chatMessageLinks.companyId, chatPublications.companyId),
+ eq(chatMessageLinks.endpointId, chatPublications.endpointId),
+ eq(
+ chatMessageLinks.conversationId,
+ chatPublications.conversationId,
+ ),
+ eq(chatMessageLinks.deliveryId, qualifyingDelivery.id),
+ eq(chatMessageLinks.direction, "inbound"),
+ isNotNull(chatMessageLinks.commentId),
),
- ),
- )
- .where(
- and(
- eq(chatPublications.companyId, endpoint.companyId),
- eq(chatPublications.endpointId, endpoint.id),
- eq(
- chatPublications.conversationId,
- qualifyingDelivery.conversationId,
+ )
+ .innerJoin(
+ heartbeatRuns,
+ and(
+ eq(heartbeatRuns.id, issueComments.createdByRunId),
+ eq(heartbeatRuns.companyId, chatPublications.companyId),
+ eq(heartbeatRuns.agentId, endpoint.assignedAgentId),
+ eq(heartbeatRuns.status, "succeeded"),
+ eq(
+ sql<string>`${heartbeatRuns.contextSnapshot} ->> 'issueId'`,
+ sql<string>`${chatPublications.issueId}::text`,
+ ),
+ or(
+ sql`${chatMessageLinks.commentId}::text = ${heartbeatRuns.contextSnapshot} ->> 'wakeCommentId'`,
+ sql`${chatMessageLinks.commentId}::text = ${heartbeatRuns.contextSnapshot} ->> 'commentId'`,
+ sql`coalesce(${heartbeatRuns.contextSnapshot} -> 'wakeCommentIds', '[]'::jsonb) ? ${chatMessageLinks.commentId}::text`,
+ ),
),
- eq(chatPublications.state, "published"),
- gte(chatPublications.publishedAt, qualifyingDelivery.processedAt),
- ),
- )
- .orderBy(desc(chatPublications.publishedAt))
- .then((rows) =>
- rows.find(
- (row) =>
- row.payload.interactionId === undefined &&
- row.payload.progressState === undefined &&
- row.commentId !== null,
- ),
- );
- if (!finalPublication) {
- throw conflict(
- "Wait for the Paperclip agent to reply to the setup turn before completing setup",
- {
- code: "chat_test_round_trip_incomplete",
- },
- );
+ )
+ .where(
+ and(
+ eq(chatPublications.companyId, endpoint.companyId),
+ eq(chatPublications.endpointId, endpoint.id),
+ eq(
+ chatPublications.conversationId,
+ qualifyingDelivery.conversationId,
+ ),
+ eq(chatPublications.state, "published"),
+ gte(chatPublications.publishedAt, qualifyingDelivery.processedAt),
+ ),
+ )
+ .orderBy(desc(chatPublications.publishedAt))
+ .then((rows) =>
+ rows.find(
+ (row) =>
+ row.payload.interactionId === undefined &&
+ row.payload.progressState === undefined &&
+ row.commentId !== null,
+ ),
+ );
+ if (!finalPublication) {
+ throw conflict(
+ "Wait for the Paperclip agent to reply to the setup turn before completing setup",
+ {
+ code: "chat_test_round_trip_incomplete",
+ },
+ );
+ }
}
await options.setupTestActivationBarrier?.();
const expectedGeneration = runtimeGeneration(endpoint.setup);
await db.transaction(async (tx) => {
await credentialLease.assertOwned(tx);
+ if (optionalSlackTest) {
+ const linked = await tx.select({ principalId: chatIdentityLinks.principalId }).from(chatIdentityLinks).where(and(
+ eq(chatIdentityLinks.endpointId, endpoint.id), eq(chatIdentityLinks.paperclipUserId, finishOptions!.optionalSlackTestForUser), eq(chatIdentityLinks.status, "linked"),
+ )).limit(1).then((rows) => rows[0]);
+ if (!linked || !(await lockCurrentPrincipalAuthorization(tx, endpoint, linked.principalId)).allowed) throw forbidden("Your Slack account is no longer authorized");
+ }
const [activated] = await tx
.update(chatEndpoints)
.set({
@@ -10038,8 +10124,9 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) {
...endpoint.setup,
step: "complete",
testStartedAt: null,
+ testSkipped: optionalSlackTest,
},
- healthMessage: "Connected",
+ healthMessage: optionalSlackTest ? "Connected; conversation test optional" : "Connected",
activatedAt: endpoint.activatedAt ?? new Date(),
updatedAt: new Date(),
})
@@ -10064,12 +10151,17 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) {
status: "active",
enabled: true,
healthStatus: "healthy",
- healthMessage: "Connected",
+ healthMessage: optionalSlackTest ? "Connected; conversation test optional" : "Connected",
lastError: null,
healthCheckedAt: new Date(),
updatedAt: new Date(),
})
.where(eq(toolConnections.id, endpoint.connectionId));
+ if (optionalSlackTest) await logActivity(tx as unknown as Db, {
+ companyId: endpoint.companyId, actorType: "user", actorId: finishOptions!.optionalSlackTestForUser,
+ action: "chat.setup_completed", entityType: "chat_endpoint", entityId: endpointId,
+ details: { conversationTestOptional: true },
+ });
await credentialLease.assertOwned(tx);
});
return get(endpointId);
@@ -23121,37 +23213,22 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) {
createHash("sha256")
.update(JSON.stringify(event.event.raw))
.digest("hex");
- const queueSlackNotice = async (
- notice: string,
- principalId?: string | null,
- ) => {
- const noticeKey = createHash("sha256")
- .update(
- JSON.stringify([
- event.event.command,
- event.event.user.userId,
- providerCommandId,
- event.event.text,
- ]),
- )
- .digest("hex");
- const effect = await db.transaction((tx) =>
- stageProviderEffect(tx, {
- endpoint: record.endpoint,
- principalId: principalId ?? null,
- providerActionId: `provider_effect:slash_notice:${noticeKey}`,
- payload: {
- version: 1,
- effect: "ephemeral_message",
- authorizationMode: "safe_notice",
- threadId: event.event.channel.id,
- userId: event.event.user.userId,
- text: notice,
- settleDelivery: false,
- },
- runtimeContext,
- }),
- );
+ const stageSlackNotice = (tx: DbTransaction, notice: string, principalId?: string | null) =>
+ stageProviderEffect(tx, {
+ endpoint: record.endpoint,
+ principalId: principalId ?? null,
+ providerActionId: `provider_effect:slash_notice:${createHash("sha256").update(JSON.stringify([
+ event.event.command, event.event.user.userId, providerCommandId, event.event.text,
+ ])).digest("hex")}`,
+ payload: {
+ version: 1, effect: "ephemeral_message", authorizationMode: "safe_notice",
+ threadId: event.event.channel.id, userId: event.event.user.userId,
+ text: notice, settleDelivery: false,
+ },
+ runtimeContext,
+ });
+ const queueSlackNotice = async (notice: string, principalId?: string | null) => {
+ const effect = await db.transaction((tx) => stageSlackNotice(tx, notice, principalId));
if (!effect) throw new Error("Slack notice was not persisted");
scheduleProviderEffect(effect.id, event.event.channel);
};
@@ -23177,6 +23254,59 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) {
event.event.user,
event.event.raw,
);
+ if (text.toLowerCase() === "connect") {
+ // Discovery must work before identity and channel access are granted.
+ // It records no task and grants no permissions; linking still requires
+ // explicit confirmation by a company member in the board.
+ if (principal.principal.kind !== "user" || principal.principal.isBot) return;
+ const effect = await db.transaction(async (tx) => {
+ if (!(await runtimeCallbackEndpoint(tx, event.endpointId, runtimeContext, ["verifying", "active"]))) {
+ throw conflict("This Slack connection changed; send the connect command again");
+ }
+ await tx.execute(sql`select pg_advisory_xact_lock(hashtextextended(${`chat-identity:${record.endpoint.companyId}:${principal.principal.id}`}, 0))`);
+ const inserted = await tx.insert(chatActions).values({
+ companyId: record.endpoint.companyId, endpointId: event.endpointId,
+ principalId: principal.principal.id, kind: "slack_connect",
+ providerActionId: `slack_connect:${providerCommandId}`,
+ payload: { version: 1, channelId: event.event.channel.id, userId: event.event.user.userId },
+ status: "processed", result: { code: "slack_identity_discovered" },
+ }).onConflictDoNothing().returning({ id: chatActions.id });
+ if (!inserted.length) return null;
+ const currentLink = await tx.select().from(chatIdentityLinks).where(and(
+ eq(chatIdentityLinks.endpointId, event.endpointId), eq(chatIdentityLinks.principalId, principal.principal.id),
+ )).then((rows) => rows[0]);
+ let notice = "Your Slack account is already connected to Paperclip. You can return to Slack and message the agent.";
+ if (currentLink?.status !== "linked") {
+ const token = randomBytes(32).toString("base64url");
+ const tokenHash = createHash("sha256").update(token).digest("hex");
+ const expiresAt = new Date(Date.now() + 15 * 60 * 1000);
+ await tx.insert(chatIdentityLinks).values({
+ companyId: record.endpoint.companyId, endpointId: event.endpointId, principalId: principal.principal.id,
+ status: "pending", confirmationTokenHash: tokenHash, expiresAt,
+ }).onConflictDoUpdate({
+ target: [chatIdentityLinks.endpointId, chatIdentityLinks.principalId],
+ set: { paperclipUserId: null, status: "pending", confirmationTokenHash: tokenHash, expiresAt, confirmedAt: null, revokedAt: null, updatedAt: new Date() },
+ });
+ await tx.update(chatActions).set({ payload: {
+ version: 1, channelId: event.event.channel.id, userId: event.event.user.userId, identityLinkHash: tokenHash,
+ } }).where(eq(chatActions.id, inserted[0].id));
+ const url = `${publicBaseUrl}/chat-identity/confirm?token=${encodeURIComponent(token)}`;
+ notice = publicBaseUrl
+ ? `[Connect your Paperclip account](${url}) — sign in and confirm this Slack identity. This private link expires in 15 minutes and works once. You can also confirm in the setup wizard. No agent work has started.`
+ : "Return to the Paperclip setup wizard to confirm your Slack account. No agent work has started.";
+ }
+ await logActivity(tx as unknown as Db, {
+ companyId: record.endpoint.companyId, actorType: "system", actorId: `chat:${principal.principal.id}`,
+ action: "chat.slack_identity_discovered", entityType: "chat_endpoint", entityId: event.endpointId,
+ details: { principalId: principal.principal.id },
+ });
+ const staged = await stageSlackNotice(tx, notice, principal.principal.id);
+ if (!staged) throw new Error("Slack identity link notice was not persisted");
+ return staged;
+ });
+ if (effect) scheduleProviderEffect(effect.id, event.event.channel);
+ return;
+ }
const resource = await db
.select()
.from(chatEndpointResources)
@@ -27691,6 +27821,17 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) {
.select()
.from(chatIdentityLinks)
.where(eq(chatIdentityLinks.endpointId, endpointId));
+ const connects = record.endpoint.provider === "slack" ? await db
+ .select({ principalId: chatActions.principalId, lastConnectAt: sql<string>`max(${chatActions.createdAt})::text` })
+ .from(chatActions)
+ .where(and(
+ eq(chatActions.companyId, record.endpoint.companyId),
+ eq(chatActions.endpointId, endpointId),
+ eq(chatActions.kind, "slack_connect"),
+ eq(chatActions.status, "processed"),
+ ))
+ .groupBy(chatActions.principalId) : [];
+ const connectByPrincipal = new Map(connects.map((row) => [row.principalId, new Date(row.lastConnectAt).toISOString()]));
const userIds = links.flatMap((link) =>
link.paperclipUserId ? [link.paperclipUserId] : [],
);
@@ -27724,6 +27865,7 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) {
paperclipUserId: link?.paperclipUserId ?? null,
paperclipUserLabel: user?.name ?? user?.email ?? null,
status: link?.status ?? "pending",
+ lastConnectAt: connectByPrincipal.get(principal.id) ?? null,
};
});
}
@@ -27807,7 +27949,7 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) {
};
}
- async function previewIdentityLink(token: string) {
+ async function previewIdentityLink(token: string, userId?: string | null) {
const tokenHash = createHash("sha256").update(token).digest("hex");
const row = await db
.select({
@@ -27843,7 +27985,18 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) {
if (!row || !row.link.expiresAt || row.link.expiresAt <= new Date()) {
throw unprocessable("This identity-link request is invalid or expired");
}
+ if (!["active", "verifying"].includes(row.endpoint.status)) throw unprocessable("This connection is not available");
+ const selfService = Boolean(await db.select({ id: chatActions.id }).from(chatActions).where(and(
+ eq(chatActions.companyId, row.link.companyId), eq(chatActions.endpointId, row.link.endpointId),
+ eq(chatActions.principalId, row.link.principalId), eq(chatActions.kind, "slack_connect"),
+ sql`${chatActions.payload}->>'identityLinkHash' = ${tokenHash}`,
+ )).limit(1).then((rows) => rows[0]));
+ const membership = userId ? await db.select({ status: companyMemberships.status }).from(companyMemberships).where(and(
+ eq(companyMemberships.companyId, row.link.companyId), eq(companyMemberships.principalType, "user"), eq(companyMemberships.principalId, userId),
+ )).then((rows) => rows[0]) : null;
return {
+ selfService,
+ canConfirm: membership?.status === "active",
endpointId: row.endpoint.id,
companyId: row.endpoint.companyId,
companyName: row.companyName,
@@ -27862,6 +28015,43 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) {
};
}
+ async function requestIdentityAccess(token: string, userId: string, requestIp: string) {
+ const preview = await previewIdentityLink(token, userId);
+ if (!preview.selfService) throw forbidden("This identity link cannot request access");
+ if (preview.canConfirm) return { status: "member" as const };
+ return db.transaction(async (tx) => {
+ await tx.execute(sql`select pg_advisory_xact_lock(hashtextextended(${`chat-join:${preview.companyId}:${userId}`}, 0))`);
+ const tokenHash = createHash("sha256").update(token).digest("hex");
+ const validLink = await tx.select({ id: chatIdentityLinks.id }).from(chatIdentityLinks).where(and(
+ eq(chatIdentityLinks.companyId, preview.companyId), eq(chatIdentityLinks.endpointId, preview.endpointId),
+ eq(chatIdentityLinks.confirmationTokenHash, tokenHash), eq(chatIdentityLinks.status, "pending"), gt(chatIdentityLinks.expiresAt, new Date()),
+ )).for("update").then((rows) => rows[0]);
+ if (!validLink) throw unprocessable("This identity-link request is invalid or expired");
+ const user = await tx.select({ email: authUsers.email }).from(authUsers).where(eq(authUsers.id, userId)).then((rows) => rows[0]);
+ if (!user) throw forbidden("Sign in to request company access");
+ const existing = await tx.select({ id: joinRequests.id }).from(joinRequests).where(and(
+ eq(joinRequests.companyId, preview.companyId), eq(joinRequests.requestType, "human"), eq(joinRequests.status, "pending_approval"),
+ or(eq(joinRequests.requestingUserId, userId), sql`lower(${joinRequests.requestEmailSnapshot}) = ${user.email.toLowerCase()}`),
+ )).then((rows) => rows[0]);
+ if (existing) return { status: "pending_approval" as const };
+ const now = new Date();
+ const [invite] = await tx.insert(invites).values({
+ companyId: preview.companyId, tokenHash: createHash("sha256").update(randomBytes(32)).digest("hex"),
+ inviteType: "company_join", allowedJoinTypes: "human", acceptedAt: now, expiresAt: now,
+ defaultsPayload: { human: { role: "operator" }, source: "slack_identity_link" },
+ }).returning({ id: invites.id });
+ const [request] = await tx.insert(joinRequests).values({
+ inviteId: invite.id, companyId: preview.companyId, requestType: "human", status: "pending_approval",
+ requestIp, requestingUserId: userId, requestEmailSnapshot: user.email,
+ }).returning({ id: joinRequests.id });
+ await logActivity(tx as unknown as Db, {
+ companyId: preview.companyId, actorType: "user", actorId: userId, action: "join.requested",
+ entityType: "join_request", entityId: request.id, details: { requestType: "human", source: "slack_identity_link", endpointId: preview.endpointId },
+ });
+ return { status: "pending_approval" as const };
+ });
+ }
+
async function confirmIdentityLink(token: string, paperclipUserId: string) {
const tokenHash = createHash("sha256").update(token).digest("hex");
const link = await db
@@ -27876,6 +28066,13 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) {
.then((rows) => rows[0] ?? null);
if (!link || !link.expiresAt || link.expiresAt <= new Date())
throw unprocessable("This identity-link request is invalid or expired");
+ const endpointRecordForLink = await endpointRecord(link.endpointId);
+ if (!endpointRecordForLink || !["active", "verifying"].includes(endpointRecordForLink.endpoint.status)) throw unprocessable("This connection is not available");
+ const connectReceipt = endpointRecordForLink.endpoint.provider === "slack" ? await db.select({ payload: chatActions.payload }).from(chatActions).where(and(
+ eq(chatActions.endpointId, link.endpointId), eq(chatActions.principalId, link.principalId), eq(chatActions.kind, "slack_connect"),
+ )).orderBy(desc(chatActions.createdAt)).limit(1).then((rows) => rows[0]) : null;
+ const confirmationRuntime = connectReceipt ? runtimeContexts.get((await runtimeFor(endpointRecordForLink.endpoint)) as object) : null;
+ let confirmationEffectId: string | null = null;
const confirmed = await db.transaction(async (tx) => {
await tx.execute(
sql`select pg_advisory_xact_lock(hashtextextended(${`chat-identity:${link.companyId}:${link.principalId}`}, 0))`,
@@ -27947,7 +28144,7 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) {
},
);
}
- return tx
+ const confirmedLink = await tx
.update(chatIdentityLinks)
.set({
paperclipUserId,
@@ -27966,12 +28163,27 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) {
)
.returning({ endpointId: chatIdentityLinks.endpointId })
.then((rows) => rows[0] ?? null);
+ if (confirmedLink && connectReceipt && confirmationRuntime &&
+ typeof connectReceipt.payload.channelId === "string" && typeof connectReceipt.payload.userId === "string") {
+ const effect = await stageProviderEffect(tx, {
+ endpoint: endpointRecordForLink.endpoint, principalId: link.principalId,
+ providerActionId: `provider_effect:identity_linked:${link.id}:${tokenHash}`,
+ payload: { version: 1, effect: "ephemeral_message", authorizationMode: "safe_notice",
+ threadId: connectReceipt.payload.channelId, userId: connectReceipt.payload.userId,
+ text: "Your Slack account is connected to Paperclip. Future messages use your Paperclip permissions.", settleDelivery: false },
+ runtimeContext: confirmationRuntime,
+ });
+ if (!effect) throw conflict("The Slack connection changed; try confirming again");
+ confirmationEffectId = effect.id;
+ }
+ return confirmedLink;
});
if (!confirmed) {
throw conflict("This identity-link request was already used or expired", {
code: "chat_identity_link_consumed",
});
}
+ if (confirmationEffectId) scheduleProviderEffect(confirmationEffectId);
return { ok: true, endpointId: confirmed.endpointId };
}
@@ -28103,7 +28315,13 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) {
});
}
- async function listActivity(endpointId: string) {
+ async function listActivity(endpointId: string, page?: { limit: number; before?: { createdAt: string; id: string } }) {
+ const limit = page ? page.limit + 1 : 100;
+ // Match the millisecond precision of the public timestamp and use a UUID
+ // tie-breaker so equal timestamps never skip records between pages.
+ const before = (date: AnyPgColumn, id: AnyPgColumn) => page?.before
+ ? sql`(date_trunc('milliseconds', ${date}), ${id}) < (${page.before.createdAt}::timestamptz, ${page.before.id}::uuid)`
+ : undefined;
const recoveryIngress = alias(chatActions, "github_recovery_ingress");
const [
deliveries,
@@ -28118,65 +28336,69 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) {
db
.select()
.from(chatDeliveries)
- .where(eq(chatDeliveries.endpointId, endpointId))
- .orderBy(desc(chatDeliveries.createdAt))
- .limit(100),
+ .where(and(eq(chatDeliveries.endpointId, endpointId), before(chatDeliveries.createdAt, chatDeliveries.id)))
+ .orderBy(desc(sql`date_trunc('milliseconds', ${chatDeliveries.createdAt})`), desc(chatDeliveries.id))
+ .limit(limit),
db
.select()
.from(chatPublications)
- .where(eq(chatPublications.endpointId, endpointId))
- .orderBy(desc(chatPublications.createdAt))
- .limit(100),
+ .where(and(eq(chatPublications.endpointId, endpointId), before(chatPublications.createdAt, chatPublications.id)))
+ .orderBy(desc(sql`date_trunc('milliseconds', ${chatPublications.createdAt})`), desc(chatPublications.id))
+ .limit(limit),
db
.select()
.from(chatActions)
.where(
and(
eq(chatActions.endpointId, endpointId),
+ before(chatActions.createdAt, chatActions.id),
eq(chatActions.kind, "slash_task_start"),
),
)
- .orderBy(desc(chatActions.createdAt))
- .limit(100),
+ .orderBy(desc(sql`date_trunc('milliseconds', ${chatActions.createdAt})`), desc(chatActions.id))
+ .limit(limit),
db
.select()
.from(chatActions)
.where(
and(
eq(chatActions.endpointId, endpointId),
+ before(chatActions.createdAt, chatActions.id),
eq(chatActions.kind, "provider_effect"),
eq(chatActions.status, "delivery_unknown"),
),
)
- .orderBy(desc(chatActions.createdAt))
- .limit(100),
+ .orderBy(desc(sql`date_trunc('milliseconds', ${chatActions.createdAt})`), desc(chatActions.id))
+ .limit(limit),
db
.select()
.from(chatActions)
.where(
and(
eq(chatActions.endpointId, endpointId),
+ before(chatActions.createdAt, chatActions.id),
eq(chatActions.kind, "github_webhook_ingress"),
eq(chatActions.status, "failed"),
sql`coalesce(${chatActions.result}->>'retryable', 'false') = 'false'`,
),
)
- .orderBy(desc(chatActions.createdAt))
- .limit(100),
+ .orderBy(desc(sql`date_trunc('milliseconds', ${chatActions.createdAt})`), desc(chatActions.id))
+ .limit(limit),
db
.select()
.from(chatActions)
.where(
and(
eq(chatActions.endpointId, endpointId),
+ before(chatActions.updatedAt, chatActions.id),
inArray(chatActions.kind, [
"slack_session_sync",
"slack_session_stop",
]),
),
)
- .orderBy(desc(chatActions.updatedAt))
- .limit(100),
+ .orderBy(desc(sql`date_trunc('milliseconds', ${chatActions.updatedAt})`), desc(chatActions.id))
+ .limit(limit),
db
.select({
action: chatActions,
@@ -28195,27 +28417,34 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) {
.where(
and(
eq(chatActions.endpointId, endpointId),
+ before(chatActions.updatedAt, chatActions.id),
eq(chatActions.kind, "github_webhook_recovery"),
),
)
- .orderBy(desc(chatActions.updatedAt))
- .limit(100),
+ .orderBy(desc(sql`date_trunc('milliseconds', ${chatActions.updatedAt})`), desc(chatActions.id))
+ .limit(limit),
db
.select()
.from(chatSdkState)
.where(
and(
eq(chatSdkState.endpointId, endpointId),
+ before(chatSdkState.updatedAt, chatSdkState.id),
eq(chatSdkState.stateKey, GITHUB_RECOVERY_STATE_KEY),
),
)
.limit(1),
]);
- const ambiguousProviderEffectDeliveryIds = new Set(
- providerEffects.flatMap((action) =>
- action.deliveryId ? [action.deliveryId] : [],
- ),
- );
+ // A provider effect can be on another page. Replay safety must still
+ // consider every unresolved effect associated with these deliveries.
+ const ambiguousEffects = deliveries.length ? await db.select({ deliveryId: chatActions.deliveryId })
+ .from(chatActions).where(and(
+ eq(chatActions.endpointId, endpointId),
+ eq(chatActions.kind, "provider_effect"),
+ eq(chatActions.status, "delivery_unknown"),
+ inArray(chatActions.deliveryId, deliveries.map((row) => row.id)),
+ )) : [];
+ const ambiguousProviderEffectDeliveryIds = new Set(ambiguousEffects.map((row) => row.deliveryId));
const transferRows = publications.length
? await db
.select(fileTransferProjectionColumns)
@@ -28509,8 +28738,32 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) {
: [];
}),
]
- .sort((a, b) => b.createdAt.localeCompare(a.createdAt))
- .slice(0, 100);
+ .sort((a, b) => b.createdAt.localeCompare(a.createdAt) || b.id.localeCompare(a.id))
+ .slice(0, limit);
+ }
+
+ async function listActivityPage(endpointId: string, limit = 25, cursor?: string) {
+ if (!Number.isInteger(limit) || limit < 1 || limit > 100) throw badRequest("Activity limit must be between 1 and 100");
+ let before: { createdAt: string; id: string } | undefined;
+ if (cursor !== undefined) {
+ try {
+ if (cursor.length > 256) throw new Error("Invalid cursor");
+ const value = JSON.parse(Buffer.from(cursor, "base64url").toString("utf8"));
+ if (!Array.isArray(value) || value.length !== 2
+ || typeof value[0] !== "string" || new Date(value[0]).toISOString() !== value[0]
+ || typeof value[1] !== "string" || !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(value[1])) throw new Error("Invalid cursor");
+ before = { createdAt: value[0], id: value[1] };
+ } catch { throw badRequest("Invalid activity cursor"); }
+ }
+ const rows = await listActivity(endpointId, { limit, before });
+ const items = rows.slice(0, limit);
+ const last = items.at(-1);
+ return {
+ items,
+ nextCursor: rows.length > limit && last
+ ? Buffer.from(JSON.stringify([last.createdAt, last.id])).toString("base64url")
+ : null,
+ };
}
async function replayDelivery(endpointId: string, deliveryId: string) {
@@ -37646,16 +37899,20 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) {
configure,
inspectPhoton,
test,
+ finishSlackSetup: (endpointId: string, userId: string) => test(endpointId, { optionalSlackTestForUser: userId }),
+ setupTestStatus,
handleWebhook,
listResources,
replaceResources,
listPrincipals,
createLinkIntent,
previewIdentityLink,
+ requestIdentityAccess,
confirmIdentityLink,
revokeLink,
listConversations,
listActivity,
+ listActivityPage,
replayDelivery,
replayPublication,
resolveAction,
diff --git a/tests/e2e/chat-adapters-ui-providers.spec.ts b/tests/e2e/chat-adapters-ui-providers.spec.ts
index b6d5d658f6..67bd60ace7 100644
--- a/tests/e2e/chat-adapters-ui-providers.spec.ts
+++ b/tests/e2e/chat-adapters-ui-providers.spec.ts
@@ -234,82 +234,52 @@ test.describe.serial("native chat adapter UI", () => {
}
if (provider.provider === "slack") {
+ await expect(page.getByRole("heading", { name: "Verify Slack connection" })).toBeVisible();
+ await expect(page.getByText("Slack needs to confirm that it can reach your Paperclip instance.")).toBeVisible();
+ mock.setWebhookVerified();
+ await expect(page.getByRole("heading", { name: "Connect your Slack account" })).toBeVisible();
+ await expect(page.getByText("/maya-public connect", { exact: true })).toBeVisible();
+ await page.getByRole("button", { name: "Link Test operator to my Paperclip account" }).click();
+ await page.getByRole("button", { name: "Continue to message test" }).click();
+ }
+
+ await expect(
+ page.getByRole("heading", { name: `Try Maya in ${provider.name}` }),
+ ).toBeVisible();
+ await expect(
+ page.getByRole("button", { name: "I've sent the test message" }),
+ ).toBeVisible();
+ if (provider.provider !== "slack") {
await expect(
- page.getByRole("heading", { name: "Finish Slack setup" }),
+ page.getByRole("heading", {
+ name: "Link the account you’re testing",
+ }),
).toBeVisible();
await expect(
page.getByText(
- `https://paperclip.example.test/api/chat-webhooks/public-slack/slack`,
- { exact: true },
+ /An observed external account is unlinked, and isolated guest work is off, so it cannot safely start Maya/,
),
).toBeVisible();
await expect(
- page.getByText("/maya-public", { exact: true }),
+ page.getByRole("button", { name: "Review identity access" }),
).toBeVisible();
- await expect(
- page.getByText(
- /Slack's bare \/status command is not a Paperclip control/,
+ await page
+ .getByRole("button", { name: "Review identity access" })
+ .click();
+ await expect(page).toHaveURL(
+ new RegExp(
+ `/${seed.prefix}/apps/chat/endpoint-${provider.provider}/access$`,
),
+ );
+ await expect(
+ page.getByRole("button", { name: "Continue setup" }),
).toBeVisible();
- const saveChangesStep = page
- .getByRole("listitem")
- .filter({ hasText: "Save Changes" });
- await expect(saveChangesStep).toHaveCount(1);
+ await page.getByRole("button", { name: "Continue setup" }).click();
+ expect(new URL(page.url()).searchParams.get("reconnect")).toBeNull();
await expect(
- saveChangesStep.locator("..").getByRole("listitem"),
- ).toHaveCount(1);
- await expect(saveChangesStep).toHaveText(
- "Return to App Manifest in Slack and click Save Changes. The copied manifest already contains the event, interaction, and slash-command URLs. Slack verifies the Events URL when you save; Paperclip records Interactivity and slash command health only after each signed callback is observed.",
- );
- for (const removedManualStep of [
- "Event Subscriptions",
- "Interactivity & Shortcuts",
- "Slash Commands",
- ]) {
- await expect(
- page.getByText(removedManualStep, { exact: true }),
- ).toHaveCount(0);
- }
- await page
- .getByRole("button", { name: "Start Slack message test" })
- .click();
+ page.getByRole("heading", { name: `Try Maya in ${provider.name}` }),
+ ).toBeVisible();
}
-
- await expect(
- page.getByRole("heading", { name: `Try Maya in ${provider.name}` }),
- ).toBeVisible();
- await expect(
- page.getByRole("button", { name: "I've sent the test message" }),
- ).toBeVisible();
- await expect(
- page.getByRole("heading", {
- name: "Link the account you’re testing",
- }),
- ).toBeVisible();
- await expect(
- page.getByText(
- /An observed external account is unlinked, and isolated guest work is off, so it cannot safely start Maya/,
- ),
- ).toBeVisible();
- await expect(
- page.getByRole("button", { name: "Review identity access" }),
- ).toBeVisible();
- await page
- .getByRole("button", { name: "Review identity access" })
- .click();
- await expect(page).toHaveURL(
- new RegExp(
- `/${seed.prefix}/apps/chat/endpoint-${provider.provider}/access$`,
- ),
- );
- await expect(
- page.getByRole("button", { name: "Continue setup" }),
- ).toBeVisible();
- await page.getByRole("button", { name: "Continue setup" }).click();
- expect(new URL(page.url()).searchParams.get("reconnect")).toBeNull();
- await expect(
- page.getByRole("heading", { name: `Try Maya in ${provider.name}` }),
- ).toBeVisible();
await expectSetupRail(page);
await expectProviderTryInstructions(page, provider);
expect(mock.configuredCredentialKeys).toEqual(
@@ -336,26 +306,20 @@ test.describe.serial("native chat adapter UI", () => {
await expect(page.getByText("Change agent", { exact: true })).toHaveCount(
0,
);
- await expect(page.getByRole("tab")).toHaveCount(4);
+ await expect(page.getByRole("navigation", { name: "Chat connection" }).getByRole("link")).toHaveCount(4);
for (const tab of ["Settings", "Access", "Conversations", "Activity"]) {
- await expect(page.getByRole("tab", { name: tab })).toBeVisible();
+ await expect(page.getByRole("navigation", { name: "Chat connection" }).getByRole("link", { name: tab , exact: true })).toBeVisible();
}
await expect(
page.getByRole("heading", { name: "Where this agent can work" }),
).toBeVisible();
if (provider.provider === "slack") {
- await expect(
- page.getByRole("heading", { name: "Slack command" }),
- ).toBeVisible();
- await expect(
- page.getByText("/maya-public", { exact: true }),
- ).toBeVisible();
- await expect(
- page.getByText(
- /Slack's bare \/status command is not a Paperclip control/,
- ),
- ).toBeVisible();
+ await expect(page.getByRole("heading", { name: "Chat in Slack" })).toBeVisible();
+ await expect(page.getByText("@maya-paperclip you there?", { exact: true })).toBeVisible();
+ await expect(page.getByRole("button", { name: "Copy message" })).toBeVisible();
+ await expect(page.getByRole("heading", { name: "Allowed Channels" })).toBeVisible();
}
+
await expect(
page.getByRole("switch", {
name: `Enable ${provider.resourceLabel}`,
@@ -424,7 +388,7 @@ test.describe.serial("native chat adapter UI", () => {
page.getByRole("switch", { name: "Allow unlinked people" }),
).toHaveCount(0);
- await page.getByRole("tab", { name: "Access" }).click();
+ await page.getByRole("navigation", { name: "Chat connection" }).getByRole("link", { name: "Access", exact: true }).click();
await expect(
page.getByRole("heading", { name: "External identity access" }),
).toBeVisible();
@@ -471,7 +435,7 @@ test.describe.serial("native chat adapter UI", () => {
await expect(
page.getByText("Confirmation link copied", { exact: true }),
).toBeVisible();
- await page.getByRole("button", { name: "Revoke" }).click();
+ await page.getByText("Grace Hopper", { exact: true }).locator("../..").getByRole("button", { name: "Revoke" }).click();
await expect
.poll(() => mock.revokedPrincipalId)
.toBe(`principal-${provider.provider}-linked`);
@@ -479,12 +443,12 @@ test.describe.serial("native chat adapter UI", () => {
page.getByText(`grace@${provider.provider}`, { exact: true }),
).toBeVisible();
- await page.getByRole("tab", { name: "Conversations" }).click();
+ await page.getByRole("navigation", { name: "Chat connection" }).getByRole("link", { name: "Conversations", exact: true }).click();
await expect(
page.getByRole("heading", { name: "Conversations" }),
).toBeVisible();
await expect(
- page.getByText(`CHAT-123 · Investigate ${provider.name} delivery`),
+ page.getByText(`Investigate ${provider.name} delivery`, { exact: true }),
).toBeVisible();
await expect(
page.getByText(provider.resourceLabel, { exact: true }),
@@ -503,7 +467,7 @@ test.describe.serial("native chat adapter UI", () => {
timeout: 8_000,
});
- await page.getByRole("tab", { name: "Activity" }).click();
+ await page.getByRole("navigation", { name: "Chat connection" }).getByRole("link", { name: "Activity", exact: true }).click();
await expect(
page.getByRole("heading", { name: "Connection activity" }),
).toBeVisible();
@@ -515,9 +479,8 @@ test.describe.serial("native chat adapter UI", () => {
await expect(
page.getByText(`Published safe output to ${provider.name}`),
).toBeVisible();
- await expect(
- page.getByText("Credential values and request bodies are redacted."),
- ).toBeVisible();
+ await expect(page.getByText("Recent activity", { exact: true })).toBeVisible();
+ await page.getByText("Connection health and controls", { exact: true }).click();
const deliveryTimestamp = page
.getByText(`Inbound ${provider.name} delivery could not be processed`)
.locator("..")
@@ -578,6 +541,7 @@ test.describe.serial("native chat adapter UI", () => {
mock.setStatus("attention");
await page.reload();
+ await page.getByText("Connection health and controls", { exact: true }).click();
await expect(
page.getByRole("button", { name: "Reconnect", exact: true }),
).toBeVisible();
@@ -598,7 +562,7 @@ test.describe.serial("native chat adapter UI", () => {
name:
provider.provider === "github"
? "Reconnect GitHub App"
- : provider.setupHeading,
+ : provider.provider === "slack" ? "Add Slack credentials" : provider.setupHeading,
}),
).toBeVisible();
await expect(
@@ -659,6 +623,7 @@ test.describe.serial("native chat adapter UI", () => {
).toBe(false);
await page.goBack();
+ await page.getByText("Connection health and controls", { exact: true }).click();
await expect(
page.getByRole("heading", { name: "Connection activity" }),
).toBeVisible();
@@ -675,7 +640,7 @@ test.describe.serial("native chat adapter UI", () => {
await expect(
page.getByRole("button", { name: provider.setupButton }),
).toBeDisabled();
- mock.setGitHubWebhookVerified();
+ mock.setWebhookVerified();
await expect(
page.getByRole("button", { name: provider.setupButton }),
).toBeEnabled();
@@ -685,6 +650,7 @@ test.describe.serial("native chat adapter UI", () => {
await page.goto(
`/${seed.prefix}/apps/chat/endpoint-${provider.provider}/activity`,
);
+ await page.getByText("Connection health and controls", { exact: true }).click();
await page.getByRole("button", { name: "Remove connection" }).click();
const confirmation = page.getByRole("alertdialog");
await expect(confirmation).toContainText("Remove this connection?");
@@ -736,7 +702,7 @@ test.describe("iMessage Photon setup and management", () => {
await expect(page.getByText(/enroll your sender in Users/)).toBeVisible();
await expect(page.getByRole("button", {name:/Copy \+1555/})).toHaveCount(0);
await page.getByRole("button", {name:"I've sent the test message"}).click();
- await page.getByRole("tab", {name:"Settings"}).click();
+ await page.getByRole("navigation", { name: "Chat connection" }).getByRole("link", { name: "Settings", exact: true }).click();
await expect(page.getByText(/Shared Photon project · direct messages only/)).toBeVisible();
await expect(page.getByRole("switch", {name:"Enable Family project"})).toBeDisabled();
await expect(page.getByRole("button", {name:"Copy dedicated number"})).toHaveCount(0);
@@ -797,7 +763,7 @@ test.describe("iMessage Photon setup and management", () => {
await page
.getByRole("button", { name: "I've sent the test message" })
.click();
- await page.getByRole("tab", { name: "Settings" }).click();
+ await page.getByRole("navigation", { name: "Chat connection" }).getByRole("link", { name: "Settings", exact: true }).click();
await expect(
page.getByText(/replies are visible to everyone in that group/),
).toBeVisible();
@@ -806,9 +772,9 @@ test.describe("iMessage Photon setup and management", () => {
await group.click();
await expect(group).toBeChecked();
await page.setViewportSize({ width: 390, height: 844 });
- await page
- .getByRole("combobox", { name: "Page section" })
- .selectOption("activity");
+ await page.getByRole("button", { name: "Open sidebar" }).click();
+ await page.getByRole("navigation", { name: "Chat connection" }).getByRole("link", { name: "Activity", exact: true }).click();
+ await page.getByText("Connection health and controls", { exact: true }).click();
await expect(
page.getByRole("button", { name: "Pause", exact: true }),
).toBeVisible();
diff --git a/tests/e2e/chat-adapters-ui.shared.ts b/tests/e2e/chat-adapters-ui.shared.ts
index c222afa128..8ff15104f5 100644
--- a/tests/e2e/chat-adapters-ui.shared.ts
+++ b/tests/e2e/chat-adapters-ui.shared.ts
@@ -52,7 +52,7 @@ export const PROVIDERS: ProviderCase[] = [
secondaryResourceLabel: "#support",
resourceType: "channel",
externalUrl: "https://app.slack.com/client/T-E2E/C-E2E/thread/C-E2E-1",
- setupHeading: /Connect a Slack app/i,
+ setupHeading: /Create a Slack app/i,
setupButton: "Connect Slack app",
chatAndTool: true,
},
@@ -293,6 +293,7 @@ export function endpointFixture(provider: ProviderCase, seed: Seed) {
webhookUrl: `https://paperclip.example.test/api/chat-webhooks/public-${provider.provider}/${provider.provider}`,
messagingEndpoint: `https://paperclip.example.test/api/chat-webhooks/public-${provider.provider}/microsoft-teams`,
command: provider.provider === "slack" ? "/maya-public" : undefined,
+ testStartedAt: null as string | null,
webhookVerifiedAt: null,
webhookSecretConfigured: false,
},
@@ -326,7 +327,7 @@ export type ChatMock = {
conversationState: "active" | "waiting";
removed: boolean;
setStatus: (status: string) => void;
- setGitHubWebhookVerified: () => void;
+ setWebhookVerified: () => void;
};
export async function installChatControlPlaneMock(
@@ -340,6 +341,7 @@ export async function installChatControlPlaneMock(
}: { enableChatConnectors: boolean; resourceCount?: number; photonShared?: boolean },
): Promise<ChatMock> {
const endpoint = endpointFixture(provider, seed);
+ let slackIdentityLinked = false;
const state: ChatMock & {
created: boolean;
failNextGitHubEndpointRead: boolean;
@@ -368,7 +370,7 @@ export async function installChatControlPlaneMock(
setStatus: (status) => {
endpoint.status = status;
},
- setGitHubWebhookVerified: () => {
+ setWebhookVerified: () => {
endpoint.setup.webhookVerifiedAt = new Date().toISOString();
},
};
@@ -558,6 +560,7 @@ export async function installChatControlPlaneMock(
botLabel: provider.botLabel,
setup: {
...endpoint.setup,
+ testStartedAt: body.action === "verify" ? new Date().toISOString() : endpoint.setup.testStartedAt,
step:
provider.provider === "slack" && body.action === "configure"
? "provider_setup"
@@ -573,7 +576,7 @@ export async function installChatControlPlaneMock(
await fulfill(route,{projectId:"project-e2e",projectName:"Photon Test",allocation:photonShared ? "shared" : "dedicated",eligible:true,lines:photonShared ? [] : [{lineId:"line-one",phoneNumber:"+15555550100",eligible:true},{lineId:"line-two",phoneNumber:"+15555550102",eligible:true}]}); return;
}
if (
- pathname === `/api/chat-endpoints/${endpoint.id}/test` &&
+ (pathname === `/api/chat-endpoints/${endpoint.id}/test` || pathname === `/api/chat-endpoints/${endpoint.id}/finish`) &&
method === "POST"
) {
Object.assign(endpoint, {
@@ -585,6 +588,20 @@ export async function installChatControlPlaneMock(
return;
}
+ if (pathname === `/api/chat-endpoints/${endpoint.id}/test-status`) {
+ await fulfill(route, { messageReceivedAt: null });
+ return;
+ }
+ if (pathname === `/api/chat-endpoints/${endpoint.id}/principals/principal-slack-self/link-intent` && method === "POST") {
+ await fulfill(route, { confirmationUrl: `https://paperclip.example.test/${seed.prefix}/chat-identity/confirm?token=e2e-self` });
+ return;
+ }
+ if (pathname === "/api/chat-identity-links/confirm" && method === "POST") {
+ slackIdentityLinked = true;
+ await fulfill(route, { endpointId: endpoint.id, companyId: seed.companyId });
+ return;
+ }
+
if (pathname === `/api/chat-endpoints/${endpoint.id}/resources`) {
if (method === "GET") {
await fulfill(route, { resources });
@@ -617,6 +634,12 @@ export async function installChatControlPlaneMock(
) {
await fulfill(route, {
principals: [
+ ...(provider.provider === "slack" && (slackIdentityLinked || endpoint.setup.step === "test") ? [{
+ id: "link-slack-self", principalId: "principal-slack-self", externalLabel: "Test operator",
+ externalDetail: "operator@slack", lastConnectAt: new Date().toISOString(),
+ paperclipUserId: slackIdentityLinked ? "local-board" : null,
+ status: slackIdentityLinked ? "linked" : "pending",
+ }] : []),
{
id: `link-${provider.provider}`,
principalId: `principal-${provider.provider}`,
@@ -767,6 +790,9 @@ export async function selectMaya(page: Page) {
export async function fillProviderSetup(page: Page, provider: ProviderCase) {
if (provider.provider === "slack") {
+ await page.getByRole("button", { name: "I already created the app" }).click();
+ await expect(page.getByLabel("Bot User OAuth Token")).toHaveAttribute("type", "password");
+ await expect(page.getByLabel("Signing Secret")).toHaveAttribute("type", "password");
await page.getByLabel("Bot User OAuth Token").fill("xoxb-e2e-redacted");
await page.getByLabel("Signing Secret").fill("slack-signing-secret");
} else if (provider.provider === "github") {
@@ -882,10 +908,13 @@ export function expectedCredentialKeys(provider: Provider): string[] {
}
export async function expectSetupRail(page: Page) {
- const rail = page.getByRole("list", { name: "Connection setup progress" });
+ const rail = page.getByRole("navigation", { name: "Connection setup progress" });
await expect(rail).toBeVisible();
- await expect(rail.getByRole("listitem")).toHaveCount(3);
- for (const label of ["Choose agent", "Connect provider", "Try it"]) {
+ const labels = new URL(page.url()).searchParams.get("provider") === "slack"
+ ? ["Choose agent", "Create Slack app", "Add credentials", "Verify Slack connection", "Connect your Slack account", "Try it"]
+ : ["Choose agent", "Connect provider", "Try it"];
+ await expect(rail.getByRole("listitem")).toHaveCount(labels.length);
+ for (const label of labels) {
await expect(rail.getByText(label, { exact: true })).toBeVisible();
}
}
@@ -904,7 +933,7 @@ features:
display_name: "maya"
slash_commands:
- command: "/maya-public"
- description: Start or manage work with "Maya"
+ description: "Start or manage work with Maya"
usage_hint: "status | new | close | <task>"
should_escape: false
url: "${webhookUrl}"
@@ -964,26 +993,15 @@ settings:
export async function expectMinimumProviderSetup(page: Page, provider: ProviderCase) {
const webhookUrl = `https://paperclip.example.test/api/chat-webhooks/public-${provider.provider}/${provider.provider}`;
if (provider.provider === "slack") {
- await expect(page.getByText("From an app manifest")).toBeVisible();
- await expect(page.getByText("OAuth & Permissions")).toBeVisible();
- await expect(page.getByText("Basic Information")).toBeVisible();
- const manifest = await page.getByLabel("Slack app manifest").inputValue();
- expect(manifest).toBe(expectedSlackManifest(webhookUrl));
- await expect(page.getByLabel("Slack app manifest")).toHaveAttribute(
- "readonly",
- "",
- );
- await expect(page.getByLabel("Bot User OAuth Token")).toHaveAttribute(
- "type",
- "password",
- );
- await expect(page.getByLabel("Signing Secret")).toHaveAttribute(
- "type",
- "password",
- );
- await expect(
- page.getByRole("button", { name: "Open Slack app settings" }),
- ).toBeVisible();
+ await expect(page.getByLabel("Slack app name", { exact: true })).toBeEditable();
+ await expect(page.getByLabel("Bot display name", { exact: true })).toBeEditable();
+ await expect(page.getByLabel("Slash command", { exact: true })).toBeEditable();
+ await page.getByRole("button", { name: "View Slack App Manifest" }).click();
+ const manifest = page.getByRole("textbox", { name: "Slack app manifest", exact: true });
+ await expect(manifest).toHaveValue(expectedSlackManifest(webhookUrl));
+ await expect(manifest).toHaveAttribute("readonly", "");
+ await page.keyboard.press("Escape");
+ await expect(page.getByRole("button", { name: "Create Slack app", exact: true })).toBeVisible();
return;
}
@@ -1149,14 +1167,16 @@ export async function expectProviderTryInstructions(
page: Page,
provider: ProviderCase,
) {
+ if (provider.provider === "slack") {
+ for (const text of ["Open a channel and invite @maya-paperclip if needed.", "@maya-paperclip you there?", "Continue the conversation in the thread."]) {
+ await expect(page.getByText(text, { exact: true })).toBeVisible();
+ }
+ await expect(page.getByRole("button", { name: "Copy message" })).toBeVisible();
+ await expect(page.getByRole("link", { name: "Open Slack", exact: true })).toHaveCount(0);
+ return;
+ }
const expected =
- provider.provider === "slack"
- ? [
- "Open a channel and invite the bot if needed.",
- "Mention @maya-paperclip in a new channel message.",
- "Reply once in Maya's thread.",
- ]
- : provider.provider === "github"
+ provider.provider === "github"
? [
"Open an installed issue or pull request.",
"Mention @maya-paperclip in a comment.",
diff --git a/ui/src/App.test.tsx b/ui/src/App.test.tsx
index bfe777b0c2..2cea7cea64 100644
--- a/ui/src/App.test.tsx
+++ b/ui/src/App.test.tsx
@@ -57,7 +57,7 @@ async function waitForText(container: HTMLElement, text: string) {
await vi.waitFor(() => expect(container.textContent).toContain(text));
}
-function renderGate(container: HTMLElement) {
+function renderGate(container: HTMLElement, allowMembershipRequest = false) {
const root = createRoot(container);
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false } },
@@ -66,7 +66,7 @@ function renderGate(container: HTMLElement) {
flushSync(() => {
root.render(
<QueryClientProvider client={queryClient}>
- <CloudAccessGate />
+ <CloudAccessGate allowMembershipRequest={allowMembershipRequest} />
</QueryClientProvider>,
);
});
@@ -123,6 +123,40 @@ describe("CloudAccessGate", () => {
unmountRoot(root);
});
+ it("admits signed-in nonmembers only for the private invitation landing page", async () => {
+ mockAuthApi.getSession.mockResolvedValue({ user: { id: "invitee" } });
+ mockAccessApi.getCurrentBoardAccess.mockResolvedValue({ isInstanceAdmin: false, companyIds: [] });
+ const root = renderGate(container, true);
+ await waitForText(container, "Outlet content");
+ unmountRoot(root);
+ });
+
+ it("still requires sign-in for the invitation landing page", async () => {
+ mockAuthApi.getSession.mockResolvedValue(null);
+ const root = renderGate(container, true);
+ await waitForText(container, "Navigate:/auth?next=");
+ expect(container.textContent).not.toContain("Outlet content");
+ unmountRoot(root);
+ });
+
+ it("still blocks invitation pages while cloud bootstrap is pending", async () => {
+ mockHealthApi.get.mockResolvedValue({ deploymentMode: "authenticated", deploymentExposure: "public", bootstrapStatus: "bootstrap_pending" });
+ mockAuthApi.getSession.mockResolvedValue({ user: { id: "invitee" } });
+ const root = renderGate(container, true);
+ await waitForText(container, "This Paperclip is waiting on its first admin");
+ expect(container.textContent).not.toContain("Outlet content");
+ unmountRoot(root);
+ });
+
+ it("keeps invitation pages closed when cloud access checks fail", async () => {
+ mockAuthApi.getSession.mockResolvedValue({ user: { id: "invitee" } });
+ mockAccessApi.getCurrentBoardAccess.mockRejectedValueOnce(new Error("Access check unavailable"));
+ const root = renderGate(container, true);
+ await waitForText(container, "Access check unavailable");
+ expect(container.textContent).not.toContain("Outlet content");
+ unmountRoot(root);
+ });
+
it("allows authenticated users with company access through to the board", async () => {
mockAuthApi.getSession.mockResolvedValue({
session: { id: "session-1", userId: "user-1" },
diff --git a/ui/src/App.tsx b/ui/src/App.tsx
index c3b957a73c..c1ba93893e 100644
--- a/ui/src/App.tsx
+++ b/ui/src/App.tsx
@@ -749,10 +749,10 @@ export function App() {
<Route path="board-claim/:token" element={<BoardClaimPage />} />
<Route path="cli-auth/:id" element={<CliAuthPage />} />
<Route path="invite/:token" element={<InviteLandingPage />} />
- <Route element={streamlinedUiLoaded ? <CloudAccessGate /> : <PaperclipLoading />}>
- <Route path="chat-identity/confirm" element={
- <ChatConnectorsExperimentalGate><ChatIdentityConfirm /></ChatConnectorsExperimentalGate>
- } />
+ <Route element={streamlinedUiLoaded ? <CloudAccessGate allowMembershipRequest /> : <PaperclipLoading />}>
+ {/* The identity APIs enforce the chat rollout flag. Nonmembers cannot
+ read experimental settings, but a private invitation may request membership. */}
+ <Route path="chat-identity/confirm" element={<ChatIdentityConfirm />} />
</Route>
<Route path="tests/perf/long-thread" element={<IssueChatLongThreadPerf />} />
<Route path="ux-lab/bootstrap-setup" element={<BootstrapSetupUxLab />} />
diff --git a/ui/src/api/chatEndpoints.ts b/ui/src/api/chatEndpoints.ts
index 43d9ab629c..a9bb484608 100644
--- a/ui/src/api/chatEndpoints.ts
+++ b/ui/src/api/chatEndpoints.ts
@@ -1,5 +1,7 @@
import { api } from "./client";
import type {
+ SlackAppConfiguration,
+ UpdateChatEndpointInput,
PhotonProjectInspection,
PhotonChannelConfiguration,
ChatPublicationBatchStatus,
@@ -41,6 +43,8 @@ export interface ChatEndpointResource {
export interface ChatIdentityLink {
id: string;
principalId: string;
+ /** Latest discovery-only connect command received by this endpoint. */
+ lastConnectAt?: string | null;
externalLabel: string;
externalDetail?: string | null;
paperclipUserId?: string | null;
@@ -73,6 +77,8 @@ export interface ExternalChannelBindingSummary {
}
export interface ChatIdentityLinkPreview {
+ selfService?: boolean;
+ canConfirm?: boolean;
endpointId: string;
companyId: string;
companyName: string;
@@ -114,11 +120,14 @@ export interface ChatEndpoint {
activity?: ChatActivityItem[];
setup?: {
step: string;
+ testStartedAt?: string | null;
+ testSkipped?: boolean;
authorizationUrl?: string | null;
providerUrl?: string | null;
webhookUrl?: string | null;
messagingEndpoint?: string | null;
command?: string | null;
+ slackApp?: SlackAppConfiguration;
webhookVerifiedAt?: string | null;
webhookSecretConfigured?: boolean;
callbackSurfaces?: {
@@ -180,12 +189,7 @@ export const chatEndpointsApi = {
) => api.post<ChatEndpoint>(`/companies/${companyId}/chat-endpoints`, input),
update: (
endpointId: string,
- input: Partial<
- Pick<
- ChatEndpoint,
- "allowDirectMessages" | "allowGroupChats" | "allowUnlinkedPeople"
- >
- >,
+ input: UpdateChatEndpointInput,
) => api.patch<ChatEndpoint>(`/chat-endpoints/${endpointId}`, input),
setup: (
endpointId: string,
@@ -204,6 +208,9 @@ export const chatEndpointsApi = {
),
test: (endpointId: string) =>
api.post<ChatEndpoint>(`/chat-endpoints/${endpointId}/test`, {}),
+ finishSlackSetup: (endpointId: string) => api.post<ChatEndpoint>(`/chat-endpoints/${endpointId}/finish`, {}),
+ setupTestStatus: (endpointId: string) => api.get<{ messageReceivedAt: string | null }>(`/chat-endpoints/${endpointId}/test-status`),
+ requestIdentityAccess: (token: string) => api.post<{ status: "member" | "pending_approval" }>("/chat-identity-links/request-access", { token }),
listResources: async (endpointId: string) =>
rows(
await api.get<ListResponse<ChatEndpointResource>>(
@@ -252,6 +259,10 @@ export const chatEndpointsApi = {
`/chat-endpoints/${endpointId}/activity`,
),
),
+ listActivityPage: (endpointId: string, cursor?: string) =>
+ api.get<{ items: ChatActivityItem[]; nextCursor: string | null }>(
+ `/chat-endpoints/${endpointId}/activity?limit=25${cursor ? `&cursor=${encodeURIComponent(cursor)}` : ""}`,
+ ),
getIssueBinding: (issueId: string) =>
api.get<ExternalChannelBindingSummary | null>(
`/issues/${issueId}/chat-binding`,
diff --git a/ui/src/components/AppsSidebar.production.tsx b/ui/src/components/AppsSidebar.production.tsx
index a04d31f3b6..f915a3f3ba 100644
--- a/ui/src/components/AppsSidebar.production.tsx
+++ b/ui/src/components/AppsSidebar.production.tsx
@@ -1,3 +1,6 @@
+import { useLocation } from "@/lib/router";
+import { ChatDetailSidebar } from "./chat/ChatDetailSidebar";
+import { ChatSetupSidebar } from "./chat/ChatSetupNavigation";
import { ChevronLeft, AppWindow, Store, ShieldQuestion } from "lucide-react";
import { Link } from "@/lib/router";
import { useCompany } from "@/context/CompanyContext";
@@ -25,6 +28,7 @@ import { SidebarNavItem } from "./SidebarNavItem.production";
* (PAP-10922).
*/
export function AppsSidebar() {
+ const { pathname } = useLocation();
const { selectedCompany } = useCompany();
const { isMobile, setSidebarOpen } = useSidebar();
@@ -34,6 +38,10 @@ export function AppsSidebar() {
(tab) => !isExperimentalToolTab(tab.key) || smokeLabEnabled,
);
+ if (pathname.endsWith("/apps/chat/connect")) return <ChatSetupSidebar />;
+ const chatDetail = pathname.match(/\/apps\/chat\/([^/]+)(?:\/(?:settings|access|conversations|activity))?\/?$/);
+ if (chatDetail) return <ChatDetailSidebar endpointId={chatDetail[1]} NavItem={SidebarNavItem} />;
+
return (
<aside className="w-full h-full min-h-0 border-r border-border bg-background flex flex-col">
<div className="flex flex-col gap-1 px-3 py-3 shrink-0">
diff --git a/ui/src/components/AppsSidebar.test.tsx b/ui/src/components/AppsSidebar.test.tsx
index 2c29ec371c..454ab45b95 100644
--- a/ui/src/components/AppsSidebar.test.tsx
+++ b/ui/src/components/AppsSidebar.test.tsx
@@ -9,11 +9,13 @@ import { AppsSidebar as ProductionAppsSidebar } from "./AppsSidebar.production";
import { contextualSidebarStyles } from "./contextual-sidebar-styles";
const sidebarNavItemMock = vi.hoisted(() => vi.fn());
+const route = vi.hoisted(() => ({ pathname: "/SLA/apps" }));
const mockToolsApi = vi.hoisted(() => ({
listActionRequests: vi.fn(),
}));
vi.mock("@/lib/router", () => ({
+ useLocation: () => route,
Link: ({
children,
to,
@@ -101,6 +103,7 @@ describe("AppsSidebar", () => {
let container: HTMLDivElement;
beforeEach(() => {
+ route.pathname = "/SLA/apps";
container = document.createElement("div");
document.body.appendChild(container);
mockToolsApi.listActionRequests.mockResolvedValue({ actionRequests: [] });
@@ -112,6 +115,20 @@ describe("AppsSidebar", () => {
vi.clearAllMocks();
});
+ it.each([AppsSidebar, ProductionAppsSidebar])("shows chat navigation in place of browse and review", async (Sidebar) => {
+ route.pathname = "/SLA/apps/chat/endpoint-a/conversations";
+ const root = createRoot(container);
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ await act(async () => root.render(<QueryClientProvider client={queryClient}><Sidebar /></QueryClientProvider>));
+ await flushReact();
+ expect(container.textContent).not.toMatch(/Browse|Review/);
+ for (const tab of ["settings", "access", "conversations", "activity"]) {
+ expect(container.querySelector(`[data-to="/apps/chat/endpoint-a/${tab}"]`)).not.toBeNull();
+ }
+ await act(async () => root.unmount());
+ queryClient.clear();
+ });
+
it("renders the consolidated connector and review doors without a redundant contextual heading", async () => {
const root = createRoot(container);
const queryClient = new QueryClient({
diff --git a/ui/src/components/AppsSidebar.tsx b/ui/src/components/AppsSidebar.tsx
index 906166a086..7b319630ef 100644
--- a/ui/src/components/AppsSidebar.tsx
+++ b/ui/src/components/AppsSidebar.tsx
@@ -1,3 +1,6 @@
+import { useLocation } from "@/lib/router";
+import { ChatDetailSidebar } from "./chat/ChatDetailSidebar";
+import { ChatSetupSidebar } from "./chat/ChatSetupNavigation";
import { Store, ShieldQuestion } from "lucide-react";
import { DEVELOPER_TABS, advancedTabHref, isExperimentalToolTab } from "@/pages/tools/tool-tabs";
import { useSmokeLabEnabled } from "@/hooks/useSmokeLabEnabled";
@@ -13,6 +16,7 @@ import { contextualSidebarStyles } from "./contextual-sidebar-styles";
* developer surfaces remain hidden unless one is explicitly enabled.
*/
export function AppsSidebar() {
+ const { pathname } = useLocation();
const reviewCount = useReviewCount();
const { enabled: smokeLabEnabled } = useSmokeLabEnabled();
const developerTabs = DEVELOPER_TABS.filter((tab) => {
@@ -22,6 +26,10 @@ export function AppsSidebar() {
return !isExperimentalToolTab(tab.key) || smokeLabEnabled;
});
+ if (pathname.endsWith("/apps/chat/connect")) return <ChatSetupSidebar />;
+ const chatDetail = pathname.match(/\/apps\/chat\/([^/]+)(?:\/(?:settings|access|conversations|activity))?\/?$/);
+ if (chatDetail) return <ChatDetailSidebar endpointId={chatDetail[1]} />;
+
return (
<aside className="w-full h-full min-h-0 border-r border-border bg-background flex flex-col">
<nav
diff --git a/ui/src/components/CloudAccessGate.tsx b/ui/src/components/CloudAccessGate.tsx
index 7b47cb854c..1dbe28b0de 100644
--- a/ui/src/components/CloudAccessGate.tsx
+++ b/ui/src/components/CloudAccessGate.tsx
@@ -26,7 +26,7 @@ function NoBoardAccessPage() {
);
}
-export function CloudAccessGate() {
+export function CloudAccessGate({ allowMembershipRequest = false }: { allowMembershipRequest?: boolean } = {}) {
const location = useLocation();
const queryClient = useQueryClient();
const healthQuery = useQuery({
@@ -117,7 +117,10 @@ export function CloudAccessGate() {
return <Navigate to={`/auth?next=${next}`} replace />;
}
+ // Private invitation pages may let signed-in nonmembers request access.
+ // Their token APIs still enforce membership before granting any authority.
if (
+ !allowMembershipRequest &&
isAuthenticatedMode &&
sessionQuery.data &&
!boardAccessQuery.data?.isInstanceAdmin &&
diff --git a/ui/src/components/Layout.production.tsx b/ui/src/components/Layout.production.tsx
index fc5e5f01a6..5b1b646d81 100644
--- a/ui/src/components/Layout.production.tsx
+++ b/ui/src/components/Layout.production.tsx
@@ -1,3 +1,4 @@
+import { ChatSetupSidebarProvider } from "@/context/ChatSetupSidebarContext";
import {
useCallback,
useEffect,
@@ -634,6 +635,7 @@ export function Layout() {
}, [location.key, location.pathname, location.state, navigationType]);
return (
+ <ChatSetupSidebarProvider>
<GeneralSettingsProvider value={{ keyboardShortcutsEnabled }}>
<div
className={cn(
@@ -785,5 +787,6 @@ export function Layout() {
<ToastViewport />
</div>
</GeneralSettingsProvider>
+ </ChatSetupSidebarProvider>
);
}
diff --git a/ui/src/components/Layout.tsx b/ui/src/components/Layout.tsx
index f1c2abc171..b0a3c7b6b6 100644
--- a/ui/src/components/Layout.tsx
+++ b/ui/src/components/Layout.tsx
@@ -1,3 +1,4 @@
+import { ChatSetupSidebarProvider } from "@/context/ChatSetupSidebarContext";
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type CSSProperties, type ReactNode } from "react";
import { useQuery } from "@tanstack/react-query";
import { Outlet, useLocation, useNavigate, useNavigationType, useParams } from "@/lib/router";
@@ -614,6 +615,7 @@ export function Layout({ sidebarSections }: { sidebarSections?: ReactNode }) {
}, [location.key, location.pathname, location.state, navigationType]);
return (
+ <ChatSetupSidebarProvider>
<GeneralSettingsProvider value={{ keyboardShortcutsEnabled }}>
<div
className={cn(
@@ -787,5 +789,6 @@ export function Layout({ sidebarSections }: { sidebarSections?: ReactNode }) {
<AnnouncementWell health={health} />
</div>
</GeneralSettingsProvider>
+ </ChatSetupSidebarProvider>
);
}
diff --git a/ui/src/components/chat/ChatDetailSidebar.test.tsx b/ui/src/components/chat/ChatDetailSidebar.test.tsx
new file mode 100644
index 0000000000..dc2516ede0
--- /dev/null
+++ b/ui/src/components/chat/ChatDetailSidebar.test.tsx
@@ -0,0 +1,34 @@
+// @vitest-environment jsdom
+import type { ReactNode } from "react";
+import { flushSync } from "react-dom";
+import { createRoot } from "react-dom/client";
+import { describe, expect, it, vi } from "vitest";
+import { ChatDetailSidebar } from "./ChatDetailSidebar";
+import { SidebarNavItem, SidebarNavExpandedProvider } from "../SidebarNavItem";
+import { SidebarNavItem as ProductionNavItem, SidebarNavExpandedProvider as ProductionProvider } from "../SidebarNavItem.production";
+import { TooltipProvider } from "../ui/tooltip";
+
+vi.mock("@/context/SidebarContext", () => ({
+ useSidebar: () => ({ collapsed: true, peeking: false, isMobile: false, setSidebarOpen: vi.fn() }),
+}));
+vi.mock("@/lib/router", () => ({
+ NavLink: ({ to, children, className }: { to: string; children: ReactNode; className?: string | ((state: { isActive: boolean }) => string) }) =>
+ <a href={to} className={typeof className === "function" ? className({ isActive: false }) : className}>{children}</a>,
+}));
+
+describe("chat detail sidebar with collapsed global navigation", () => {
+ it.each([
+ ["default", SidebarNavExpandedProvider, SidebarNavItem],
+ ["production", ProductionProvider, ProductionNavItem],
+ ] as const)("keeps labels visible in the %s layout", (_name, Provider, NavItem) => {
+ const container = document.createElement("div");
+ const root = createRoot(container);
+ try {
+ flushSync(() => root.render(<TooltipProvider><Provider><ChatDetailSidebar endpointId="endpoint-a" NavItem={NavItem} /></Provider></TooltipProvider>));
+ for (const label of ["Settings", "Access", "Conversations", "Activity"]) {
+ const span = Array.from(container.querySelectorAll("span")).find((node) => node.textContent === label);
+ expect(span?.classList.contains("truncate")).toBe(true);
+ }
+ } finally { flushSync(() => root.unmount()); }
+ });
+});
diff --git a/ui/src/components/chat/ChatDetailSidebar.tsx b/ui/src/components/chat/ChatDetailSidebar.tsx
new file mode 100644
index 0000000000..91a00369dd
--- /dev/null
+++ b/ui/src/components/chat/ChatDetailSidebar.tsx
@@ -0,0 +1,18 @@
+import { Activity, MessageSquare, Settings, Users } from "lucide-react";
+import { SidebarNavItem } from "../SidebarNavItem";
+import { contextualSidebarStyles } from "../contextual-sidebar-styles";
+
+export function ChatDetailSidebar({ endpointId, NavItem = SidebarNavItem }: { endpointId: string; NavItem?: typeof SidebarNavItem }) {
+ return (
+ <aside className="flex h-full min-h-0 w-full flex-col border-r border-border bg-background">
+ <nav aria-label="Chat connection" data-slot="contextual-sidebar-nav" className={contextualSidebarStyles.nav}>
+ <div data-slot="contextual-sidebar-group" className={contextualSidebarStyles.group}>
+ <NavItem to={`/apps/chat/${endpointId}/settings`} label="Settings" icon={Settings} end />
+ <NavItem to={`/apps/chat/${endpointId}/access`} label="Access" icon={Users} end />
+ <NavItem to={`/apps/chat/${endpointId}/conversations`} label="Conversations" icon={MessageSquare} end />
+ <NavItem to={`/apps/chat/${endpointId}/activity`} label="Activity" icon={Activity} end />
+ </div>
+ </nav>
+ </aside>
+ );
+}
diff --git a/ui/src/components/chat/ChatSetupNavigation.tsx b/ui/src/components/chat/ChatSetupNavigation.tsx
new file mode 100644
index 0000000000..9c19b36ede
--- /dev/null
+++ b/ui/src/components/chat/ChatSetupNavigation.tsx
@@ -0,0 +1,69 @@
+import { createPortal } from "react-dom";
+import { useChatSetupSidebar } from "@/context/ChatSetupSidebarContext";
+import { useSidebar } from "@/context/SidebarContext";
+import { cn } from "@/lib/utils";
+
+export function ChatSetupSidebar() {
+ const sidebar = useChatSetupSidebar();
+ return (
+ <aside className="flex h-full min-h-0 w-full flex-col border-r border-border bg-background">
+ <div ref={sidebar?.setTarget} className="overflow-y-auto px-4 py-6" />
+ </aside>
+ );
+}
+
+export function ChatSetupNavigation({
+ labels = ["Choose agent", "Connect provider", "Try it"],
+ step,
+ availableStep,
+ disabled = false,
+ onSelect,
+}: {
+ labels?: string[];
+ step: number;
+ availableStep: number;
+ disabled?: boolean;
+ onSelect: (step: number) => void;
+}) {
+ const sidebar = useChatSetupSidebar();
+ const { isMobile, setSidebarOpen } = useSidebar();
+ const navigation = (
+ <nav aria-label="Connection setup progress">
+ <ol className="text-sm">
+ {labels.map((label, index) => (
+ <li key={label}>
+ {index > 0 && (
+ <div aria-hidden="true" className="flex w-8 justify-center py-1">
+ <span className="h-4 border-l border-border" />
+ </div>
+ )}
+ <button
+ type="button"
+ aria-current={index === step ? "step" : undefined}
+ disabled={disabled || index > availableStep}
+ onClick={() => {
+ onSelect(index);
+ if (isMobile) setSidebarOpen(false);
+ }}
+ className="flex w-full items-center gap-3 rounded-md text-left outline-none transition-colors hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring disabled:cursor-default disabled:hover:bg-transparent"
+ >
+ <span className={cn(
+ "flex size-8 shrink-0 items-center justify-center rounded-full border font-medium",
+ index === step ? "border-primary bg-primary text-primary-foreground" :
+ index <= availableStep ? "border-foreground text-foreground" : "border-border text-muted-foreground",
+ )}>
+ {index + 1}
+ </span>
+ <span className={index === step ? "font-medium text-foreground" : "text-muted-foreground"}>
+ {label}
+ </span>
+ </button>
+ </li>
+ ))}
+ </ol>
+ </nav>
+ );
+ // Standalone renders (including component previews) retain usable navigation.
+ if (!sidebar) return navigation;
+ return sidebar.target ? createPortal(navigation, sidebar.target) : null;
+}
diff --git a/ui/src/context/ChatSetupSidebarContext.tsx b/ui/src/context/ChatSetupSidebarContext.tsx
new file mode 100644
index 0000000000..3aaab7c787
--- /dev/null
+++ b/ui/src/context/ChatSetupSidebarContext.tsx
@@ -0,0 +1,17 @@
+import { createContext, useContext, useMemo, useState, type ReactNode } from "react";
+
+const ChatSetupSidebarContext = createContext<{
+ target: HTMLDivElement | null;
+ setTarget: (target: HTMLDivElement | null) => void;
+} | null>(null);
+
+/** Keeps setup navigation owned by the form while rendering it in the shell. */
+export function ChatSetupSidebarProvider({ children }: { children: ReactNode }) {
+ const [target, setTarget] = useState<HTMLDivElement | null>(null);
+ const value = useMemo(() => ({ target, setTarget }), [target]);
+ return <ChatSetupSidebarContext.Provider value={value}>{children}</ChatSetupSidebarContext.Provider>;
+}
+
+export function useChatSetupSidebar() {
+ return useContext(ChatSetupSidebarContext);
+}
diff --git a/ui/src/index.css b/ui/src/index.css
index f7b2e97140..545c0c0ba5 100644
--- a/ui/src/index.css
+++ b/ui/src/index.css
@@ -3042,3 +3042,8 @@ span.paperclip-mention-chip[data-mention-kind="external-object"] {
@media (prefers-reduced-motion: reduce) {
.announcement-well { animation: none; }
}
+
+/* Native disclosure marker is replaced by the connection-health chevron. */
+.chat-connection-health-summary::-webkit-details-marker {
+ display: none;
+}
diff --git a/ui/src/pages/apps/AppLogo.tsx b/ui/src/pages/apps/AppLogo.tsx
index 02738b0944..3794613f91 100644
--- a/ui/src/pages/apps/AppLogo.tsx
+++ b/ui/src/pages/apps/AppLogo.tsx
@@ -26,6 +26,7 @@ interface AppLogoProps {
allowRemoteFallback?: boolean;
darkLogoUrl?: string | null;
size?: number;
+ compact?: boolean;
className?: string;
}
@@ -41,6 +42,7 @@ export function AppLogo({
darkLogoUrl,
allowRemoteFallback = true,
size = 36,
+ compact = false,
className,
}: AppLogoProps) {
const [failedLogoUrls, setFailedLogoUrls] = useState<ReadonlySet<string>>(() => new Set());
@@ -111,7 +113,7 @@ export function AppLogo({
alt=""
width={size}
height={size}
- className="h-full w-full object-contain p-1.5 dark:hidden"
+ className={cn("h-full w-full object-contain dark:hidden", compact ? "p-0.5" : "p-1.5")}
onError={() => markLogoFailed(lightLogoUrlForRender)}
/>
) : (
@@ -131,7 +133,7 @@ export function AppLogo({
alt=""
width={size}
height={size}
- className="hidden h-full w-full object-contain p-1.5 dark:block"
+ className={cn("hidden h-full w-full object-contain dark:block", compact ? "p-0.5" : "p-1.5")}
onError={() => markLogoFailed(darkLogoUrlForRender)}
/>
) : (
@@ -152,7 +154,7 @@ export function AppLogo({
alt=""
width={size}
height={size}
- className="h-full w-full object-contain p-1.5"
+ className={cn("h-full w-full object-contain", compact ? "p-0.5" : "p-1.5")}
onError={() => markLogoFailed(fallbackLogoUrl)}
/>
)}
diff --git a/ui/src/pages/apps/chat/ChatEndpoint.clipboard.test.tsx b/ui/src/pages/apps/chat/ChatEndpoint.clipboard.test.tsx
index 32fc24f845..03b0700049 100644
--- a/ui/src/pages/apps/chat/ChatEndpoint.clipboard.test.tsx
+++ b/ui/src/pages/apps/chat/ChatEndpoint.clipboard.test.tsx
@@ -5,20 +5,36 @@ import { createRoot, type Root } from "react-dom/client";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { ChatEndpoint, ChatProvider } from "@/api/chatEndpoints";
+import { queryKeys } from "@/lib/queryKeys";
+import { TooltipProvider } from "@/components/ui/tooltip";
+import { ChatSetupSidebarProvider } from "@/context/ChatSetupSidebarContext";
+import { ChatSetupSidebar } from "@/components/chat/ChatSetupNavigation";
import { ChatEndpointSetup } from "./ChatEndpointSetup";
import { ChatEndpointDetail } from "./ChatEndpointDetail";
const mocks = vi.hoisted(() => ({
get: vi.fn(),
+ tab: "access",
+ listActivityPage: vi.fn(),
+ create: vi.fn(),
+ update: vi.fn(),
+ setup: vi.fn(),
+ setupTestStatus: vi.fn(),
+ finishSlackSetup: vi.fn(),
generateSetupSecret: vi.fn(),
listPrincipals: vi.fn(),
createLinkIntent: vi.fn(),
+ confirmIdentityLink: vi.fn(),
pushToast: vi.fn(),
setBreadcrumbs: vi.fn(),
search: "",
+ setParams: vi.fn(),
}));
vi.mock("@/api/chatEndpoints", () => ({ chatEndpointsApi: mocks }));
+vi.mock("@/api/auth", () => ({ authApi: { getSession: async () => ({ user: { id: "owner-user", name: "Owner" } }) } }));
+vi.mock("@/api/health", () => ({ healthApi: { get: async () => ({ deploymentMode: "authenticated" }) } }));
vi.mock("@/api/agents", () => ({ agentsApi: { list: async () => [] } }));
+vi.mock("@/api/instanceSettings", () => ({ instanceSettingsApi: { getExperimental: async () => ({ enableIsolatedWorkspaces: true }) } }));
vi.mock("@/context/CompanyContext", () => ({
useCompany: () => ({ selectedCompanyId: "company-a" }),
}));
@@ -33,8 +49,8 @@ vi.mock("@/context/SidebarContext", () => ({
}));
vi.mock("@/lib/router", () => ({
useNavigate: () => vi.fn(),
- useParams: () => ({ endpointId: "endpoint-a", tab: "access" }),
- useSearchParams: () => [new URLSearchParams(mocks.search)],
+ useParams: () => ({ endpointId: "endpoint-a", tab: mocks.tab }),
+ useSearchParams: () => [new URLSearchParams(mocks.search), mocks.setParams],
Link: ({ children }: { children: React.ReactNode }) => (
<span>{children}</span>
),
@@ -51,6 +67,8 @@ describe("chat setup and identity-link clipboard actions", () => {
const secret = "synthetic-one-time-webhook-secret";
beforeEach(() => {
+ mocks.tab = "access";
+ mocks.listActivityPage.mockReset();
container = document.createElement("div");
document.body.append(container);
root = createRoot(container);
@@ -67,6 +85,8 @@ describe("chat setup and identity-link clipboard actions", () => {
configurable: true,
value: execCommand,
});
+ mocks.setupTestStatus.mockResolvedValue({ messageReceivedAt: null });
+ mocks.finishSlackSetup.mockResolvedValue({ id: "endpoint-a", status: "active" });
mocks.generateSetupSecret.mockResolvedValue({ webhookSecret: secret });
mocks.listPrincipals.mockResolvedValue([
{
@@ -89,6 +109,7 @@ describe("chat setup and identity-link clipboard actions", () => {
vi.restoreAllMocks();
vi.unstubAllGlobals();
vi.clearAllMocks();
+ vi.useRealTimers();
});
async function settle() {
for (let i = 0; i < 5; i += 1)
@@ -96,14 +117,14 @@ describe("chat setup and identity-link clipboard actions", () => {
flushSync(() => {});
}
async function click(text: string) {
- const button = [...container.querySelectorAll("button")].find(
+ const button = [...document.querySelectorAll("button")].find(
(node) => node.textContent?.trim() === text,
);
expect(button, text).toBeDefined();
flushSync(() => button!.click());
await settle();
}
- async function render(provider: ChatProvider, detail = false) {
+ async function render(provider: ChatProvider, detail = false, publicHttps = true) {
const endpoint: ChatEndpoint = {
id: "endpoint-a",
companyId: "company-a",
@@ -114,7 +135,7 @@ describe("chat setup and identity-link clipboard actions", () => {
allowUnlinkedPeople: false,
setup: {
step: "provider_setup",
- webhookUrl: "https://example.test/api/chat-webhooks/test",
+ webhookUrl: publicHttps ? "https://example.test/api/chat-webhooks/test" : null,
webhookSecretConfigured: false,
},
};
@@ -123,13 +144,43 @@ describe("chat setup and identity-link clipboard actions", () => {
flushSync(() =>
root.render(
<QueryClientProvider client={client}>
- {detail ? <ChatEndpointDetail /> : <ChatEndpointSetup />}
+ {detail ? <ChatEndpointDetail /> : (
+ <TooltipProvider>
+ <ChatSetupSidebarProvider>
+ <ChatSetupSidebar />
+ <main><ChatEndpointSetup /></main>
+ </ChatSetupSidebarProvider>
+ </TooltipProvider>
+ )}
</QueryClientProvider>,
),
);
await settle();
+ return endpoint;
}
+ it("pages older activity and lets users return after a page fails", async () => {
+ mocks.tab = "activity";
+ const item = (id: string) => ({ id, kind: "delivery", status: "processed", summary: id, createdAt: "2026-01-01T00:00:00Z" });
+ mocks.listActivityPage.mockImplementation(async (_id, cursor) => cursor
+ ? { items: [item("Older message")], nextCursor: null }
+ : { items: [item("Newest message")], nextCursor: "older-cursor" });
+ await render("slack", true);
+ expect(container.textContent).toContain("Newest message");
+ await click("Next");
+ expect(mocks.listActivityPage).toHaveBeenLastCalledWith("endpoint-a", "older-cursor");
+ expect(container.textContent).toContain("Older message");
+ expect(container.textContent).toContain("Page 2");
+ await click("Previous");
+ expect(container.textContent).toContain("Newest message");
+ client.removeQueries({ queryKey: [...queryKeys.chatEndpoints.activity("endpoint-a"), "older-cursor"] });
+ mocks.listActivityPage.mockRejectedValue(new Error("Offline"));
+ await click("Next");
+ expect(container.textContent).toContain("Connection activity could not be loaded");
+ await click("Previous");
+ expect(container.textContent).toContain("Page 1");
+ });
+
it.each(["slack", "microsoft-teams"] as const)(
"copies the %s manifest via the insecure-context fallback",
async (provider) => {
@@ -149,18 +200,360 @@ describe("chat setup and identity-link clipboard actions", () => {
input!.dispatchEvent(new Event("input", { bubbles: true }));
});
}
- const expected = container.querySelector("textarea")!.value;
+ if (provider === "slack") await click("View Slack App Manifest");
+ const expected = document.querySelector("textarea")!.value;
await click(
provider === "slack" ? "Copy manifest" : "Copy manifest settings",
);
expect(copied).toEqual([expected]);
expect(writeText).not.toHaveBeenCalled();
- expect(container.textContent).toContain(
+ expect(document.body.textContent).toContain(
provider === "slack" ? "Manifest copied" : "Manifest settings copied",
);
},
);
+ it("keeps the Slack manifest in a modal and generates the creation link from saved edits", async () => {
+ const endpoint = await render("slack");
+ expect(document.querySelector("[role=dialog]")).toBeNull();
+ expect(container.querySelector("textarea")).toBeNull();
+ const edited = { appName: 'Research & "Ops"', botName: "research-ops", command: "/research" };
+ mocks.update.mockImplementation(async (_id, input) => ({
+ ...endpoint,
+ setup: { ...endpoint.setup, slackApp: input.slackApp, command: input.slackApp.command },
+ }));
+ for (const [label, value] of [
+ ["Slack app name", edited.appName],
+ ["Bot display name", edited.botName],
+ ["Slash command", edited.command],
+ ]) {
+ const fieldLabel = [...container.querySelectorAll("label")].find((node) => node.textContent === label)!;
+ const input = document.getElementById(fieldLabel.htmlFor) as HTMLInputElement;
+ flushSync(() => {
+ Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call(input, value);
+ input.dispatchEvent(new Event("input", { bubbles: true }));
+ });
+ flushSync(() => input.dispatchEvent(new FocusEvent("focusout", { bubbles: true })));
+ await settle();
+ }
+ expect(mocks.update).toHaveBeenLastCalledWith("endpoint-a", { slackApp: edited });
+ await click("View Slack App Manifest");
+ expect(document.querySelector("[role=dialog]")).not.toBeNull();
+ expect(document.querySelector("textarea")!.readOnly).toBe(true);
+ const manifest = document.querySelector("textarea")!.value;
+ expect(manifest).toContain(`name: ${JSON.stringify(edited.appName)}`);
+ expect(manifest).toContain(`display_name: "research-ops"`);
+ expect(manifest).toContain(`command: "/research"`);
+ await click("Copy manifest");
+ expect(copied).toEqual([manifest]);
+ await click("Close");
+ expect(document.querySelector("[role=dialog]")).toBeNull();
+ const open = vi.spyOn(window, "open").mockReturnValue(null);
+ vi.useFakeTimers();
+ const createButton = [...container.querySelectorAll("button")].find((button) => button.textContent?.trim() === "Create Slack app")!;
+ flushSync(() => createButton.click());
+ const url = new URL(open.mock.calls[0][0] as string);
+ expect(url.origin + url.pathname).toBe("https://api.slack.com/apps");
+ expect(url.searchParams.get("new_app")).toBe("1");
+ expect(url.searchParams.get("manifest_yaml")).toBe(manifest);
+ expect(open.mock.calls[0].slice(1)).toEqual(["_blank", "noopener,noreferrer"]);
+ expect(container.querySelector("h1")?.textContent).toBe("Create a Slack app");
+ expect(createButton.disabled).toBe(true);
+ flushSync(() => createButton.click());
+ expect(open).toHaveBeenCalledTimes(1);
+ flushSync(() => vi.advanceTimersByTime(999));
+ expect(container.querySelector("h1")?.textContent).toBe("Create a Slack app");
+ flushSync(() => vi.advanceTimersByTime(1));
+ vi.useRealTimers();
+ expect(container.querySelector("h1")?.textContent).toBe("Add Slack credentials");
+ expect(document.querySelector("textarea")).toBeNull();
+ const token = container.querySelector<HTMLInputElement>("#slack-bot-token")!;
+ expect(token.closest("[hidden]")).toBeNull();
+ flushSync(() => {
+ Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call(token, "synthetic-token");
+ token.dispatchEvent(new Event("input", { bubbles: true }));
+ });
+ expect(mocks.setParams.mock.calls.at(-1)?.[0].get("stage")).toBe("credentials");
+ await click("2Create Slack app");
+ expect(container.querySelector("h1")?.textContent).toBe("Create a Slack app");
+ expect(token.closest("[hidden]")).not.toBeNull();
+ await click("View Slack App Manifest");
+ expect(document.querySelector("textarea")!.value).toBe(manifest);
+ await click("Close");
+ await click("3Add credentials");
+ expect(token.closest("[hidden]")).toBeNull();
+ expect(token.value).toBe("synthetic-token");
+ const finalStep = container.querySelectorAll("aside button")[4] as HTMLButtonElement;
+ expect(finalStep.disabled).toBe(true);
+
+ });
+
+
+ it.each(["xapp-", "xoxb-", "xoxp-"])("warns about a %s token in the Slack signing secret field and clears after correction", async (prefix) => {
+ await render("slack");
+ await click("I already created the app");
+ const inputFor = (name: string) => document.getElementById([...container.querySelectorAll("label")]
+ .find((label) => label.textContent === name)!.htmlFor) as HTMLInputElement;
+ const setValue = (input: HTMLInputElement, value: string) => flushSync(() => {
+ Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call(input, value);
+ input.dispatchEvent(new Event("input", { bubbles: true }));
+ });
+ const signingSecret = inputFor("Signing Secret");
+ const connect = [...container.querySelectorAll("button")].find((button) => button.textContent === "Connect Slack app")!;
+ setValue(inputFor("Bot User OAuth Token"), "xoxb-synthetic-token");
+ setValue(signingSecret, ` ${prefix}synthetic-private-token `);
+ expect(signingSecret.getAttribute("aria-invalid")).toBe("true");
+ const warning = document.getElementById("slack-signing-secret-warning")!;
+ expect(signingSecret.getAttribute("aria-describedby")?.split(" ")).toContain(warning.id);
+ expect(warning.textContent).toContain("Signing Secret, NOT an app or bot token");
+ expect(warning.textContent).not.toContain("synthetic-private-token");
+ expect(connect.disabled).toBe(true);
+ setValue(signingSecret, "synthetic-signing-secret");
+ expect(document.getElementById("slack-signing-secret-warning")).toBeNull();
+ expect(signingSecret.getAttribute("aria-invalid")).toBeNull();
+ expect(connect.disabled).toBe(false);
+ const botToken = inputFor("Bot User OAuth Token");
+ for (const value of ["xapp-synthetic-token", "xoxp-synthetic-token", "not-a-bot-token"]) {
+ setValue(botToken, value);
+ expect(botToken.getAttribute("aria-invalid")).toBe("true");
+ expect(document.getElementById("slack-bot-token-warning")!.textContent).toContain("must start with xoxb-");
+ expect(connect.disabled).toBe(true);
+ }
+ setValue(botToken, " xoxb-synthetic-token ");
+ expect(document.getElementById("slack-bot-token-warning")).toBeNull();
+ expect(connect.disabled).toBe(false);
+ setValue(signingSecret, "");
+ expect(connect.disabled).toBe(true);
+ expect(container.querySelector("img")).toBeNull();
+ });
+
+ it("separates saved credentials, finishing Slack setup, and the message test", async () => {
+ const endpoint = await render("slack");
+ await click("I already created the app");
+ const configured: ChatEndpoint = {
+ ...endpoint,
+ status: "verifying",
+ providerAccountId: "workspace-a",
+ botExternalId: "bot-a",
+ setup: { ...endpoint.setup!, command: "/maya-test" },
+ };
+ mocks.get.mockResolvedValue(configured);
+ mocks.setup.mockResolvedValueOnce(configured);
+ for (const [id, value] of [["slack-bot-token", "xoxb-synthetic-token"], ["slack-signing-secret", "synthetic-secret"]]) {
+ const input = document.getElementById(id)!;
+ flushSync(() => {
+ Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call(input, value);
+ input.dispatchEvent(new Event("input", { bubbles: true }));
+ });
+ }
+ await click("Connect Slack app");
+ expect(container.querySelector("h1")?.textContent).toBe("Verify Slack connection");
+ expect(container.querySelector('aside button[aria-current="step"]')?.textContent).toBe("4Verify Slack connection");
+ await click("3Add credentials");
+ expect(container.querySelector("h1")?.textContent).toBe("Add Slack credentials");
+ expect(container.querySelector<HTMLInputElement>("#slack-bot-token")!.value).toBe("");
+ await click("Continue");
+ expect(container.querySelector("h1")?.textContent).toBe("Verify Slack connection");
+ expect(mocks.setup).toHaveBeenCalledTimes(1);
+ expect([...container.querySelectorAll("button")].find((button) => button.textContent === "Continue")!.disabled).toBe(true);
+ expect(container.querySelector("details")?.open).toBe(false);
+ const verified = { ...configured, setup: { ...configured.setup, webhookVerifiedAt: new Date().toISOString() } };
+ mocks.get.mockResolvedValue(verified);
+ mocks.setup.mockResolvedValueOnce({ ...verified, setup: { ...verified.setup, step: "test" } });
+ await client.invalidateQueries({ queryKey: ["chat-endpoint-slack-webhook-verification", endpoint.id] });
+ await settle();
+ expect(mocks.setup).toHaveBeenLastCalledWith(endpoint.id, { action: "verify", credentials: undefined });
+ expect(container.querySelector('aside button[aria-current="step"]')?.textContent).toBe("5Connect your Slack account");
+ expect(container.textContent).toContain("/maya-test connect");
+ await click("4Verify Slack connection");
+ expect(container.querySelector("h1")?.textContent).toBe("Verify Slack connection");
+ expect(container.textContent).toContain("Slack verified your connection.");
+ await click("Continue");
+ expect(container.querySelector('aside button[aria-current="step"]')?.textContent).toBe("5Connect your Slack account");
+ expect(mocks.setup).toHaveBeenCalledTimes(2);
+ await click("3Add credentials");
+ expect(container.querySelector("h1")?.textContent).toBe("Add Slack credentials");
+ });
+
+ it("skips verification when Slack has already verified the URL", async () => {
+ const endpoint = await render("slack");
+ const verified: ChatEndpoint = {
+ ...endpoint, status: "verifying", providerAccountId: "workspace-a",
+ setup: { ...endpoint.setup!, webhookVerifiedAt: new Date().toISOString() },
+ };
+ mocks.setup.mockResolvedValueOnce({ ...verified, setup: { ...verified.setup, step: "test" } });
+ flushSync(() => client.setQueryData(["chat-endpoint-setup-resume", endpoint.id], verified));
+ await settle();
+ expect(mocks.setup).toHaveBeenCalledTimes(1);
+ expect(mocks.setup).toHaveBeenCalledWith(endpoint.id, { action: "verify", credentials: undefined });
+ expect(container.querySelector('aside button[aria-current="step"]')?.textContent).toBe("5Connect your Slack account");
+ });
+
+ it("picks up verification completed in another tab", async () => {
+ const endpoint = await render("slack");
+ const verified: ChatEndpoint = {
+ ...endpoint, status: "verifying", providerAccountId: "workspace-a",
+ setup: { ...endpoint.setup!, webhookVerifiedAt: new Date().toISOString() },
+ };
+ mocks.setup.mockRejectedValueOnce(new Error("Provider verification is not available at this setup step"));
+ mocks.get.mockResolvedValue({ ...verified, setup: { ...verified.setup, step: "test" } });
+ flushSync(() => client.setQueryData(["chat-endpoint-setup-resume", endpoint.id], verified));
+ await settle();
+ expect(mocks.setup).toHaveBeenCalledTimes(1);
+ expect(container.querySelector('aside button[aria-current="step"]')?.textContent).toBe("5Connect your Slack account");
+ expect(container.textContent).not.toContain("Connection failed");
+ });
+
+ it("allows retrying a failed automatic transition without looping", async () => {
+ const endpoint = await render("slack");
+ const verified: ChatEndpoint = {
+ ...endpoint, status: "verifying", providerAccountId: "workspace-a",
+ setup: { ...endpoint.setup!, webhookVerifiedAt: new Date().toISOString() },
+ };
+ mocks.setup.mockRejectedValueOnce(new Error("Connection interrupted"));
+ flushSync(() => client.setQueryData(["chat-endpoint-setup-resume", endpoint.id], verified));
+ await settle();
+ expect(mocks.setup).toHaveBeenCalledTimes(1);
+ expect(container.textContent).toContain("Connection interrupted");
+ mocks.setup.mockResolvedValueOnce({ ...verified, setup: { ...verified.setup, step: "test" } });
+ await click("Continue");
+ expect(mocks.setup).toHaveBeenCalledTimes(2);
+ expect(container.querySelector('aside button[aria-current="step"]')?.textContent).toBe("5Connect your Slack account");
+ });
+
+ async function renderSlackIdentityStep() {
+ const endpoint = await render("slack");
+ flushSync(() => client.setQueryData(["chat-endpoint-setup-resume", endpoint.id], {
+ ...endpoint, status: "verifying", providerAccountId: "workspace-a",
+ setup: { ...endpoint.setup, step: "test", command: "/maya-test", testStartedAt: "2026-09-18T20:00:00Z" },
+ }));
+ await settle();
+ return endpoint;
+ }
+
+ it("waits for a fresh connect command and links the selected identity inside the wizard", async () => {
+ mocks.listPrincipals.mockResolvedValue([
+ { id: "old", principalId: "old", externalLabel: "Old workspace member", status: "pending", lastConnectAt: "2026-09-17T20:00:00Z" },
+ { id: "unrelated", principalId: "unrelated", externalLabel: "Other workspace member", status: "pending" },
+ ]);
+ await renderSlackIdentityStep();
+ expect(container.textContent).toContain("/maya-test connect");
+ expect(container.textContent).toContain("Waiting for your connect command");
+ expect(container.textContent).not.toContain("Other workspace member");
+ expect(container.textContent).not.toContain("Old workspace member");
+ expect(mocks.createLinkIntent).not.toHaveBeenCalled();
+ await click("Copy command");
+ expect(copied).toContain("/maya-test connect");
+ const identity = { id: "link-a", principalId: "principal-a", externalLabel: "My Slack identity", externalDetail: "@my-slack", status: "pending", lastConnectAt: "2026-09-18T20:01:00Z" };
+ mocks.listPrincipals.mockResolvedValue([identity]);
+ client.setQueryData(queryKeys.chatEndpoints.principals("endpoint-a"), [identity]);
+ await settle();
+ expect(container.textContent).toContain("My Slack identity");
+ expect(container.textContent).toContain("Owner");
+ expect(mocks.confirmIdentityLink).not.toHaveBeenCalled();
+ mocks.confirmIdentityLink.mockImplementationOnce(async () => {
+ mocks.listPrincipals.mockResolvedValue([{ ...identity, status: "linked", paperclipUserId: "owner-user" }]);
+ return { ok: true };
+ });
+ await click("This is my Slack account");
+ expect(mocks.createLinkIntent).toHaveBeenCalledWith("endpoint-a", "principal-a");
+ expect(mocks.confirmIdentityLink).toHaveBeenCalledWith("synthetic-private-confirmation-token");
+ expect(container.textContent).toContain("Linked to you");
+ expect(container.querySelector('aside button[aria-current="step"]')?.textContent).toBe("5Connect your Slack account");
+ await click("Continue to message test");
+ expect(container.querySelector('aside button[aria-current="step"]')?.textContent).toBe("6Try it");
+ expect(container.textContent).toContain("@Maya you there?");
+ await click("Copy message");
+ expect(copied).toContain("@Maya you there?");
+ expect(container.textContent).not.toContain("Review identity access");
+ expect(container.textContent).not.toContain("Complete this real conversation");
+ expect(container.textContent).toContain("Continue the conversation in the thread.");
+ expect([...container.querySelectorAll("button")].find((button) => button.textContent === "I've sent the test message")!.disabled).toBe(false);
+ mocks.finishSlackSetup.mockImplementationOnce(async () => ({
+ ...client.getQueryData<ChatEndpoint>(["chat-endpoint-setup-resume", "endpoint-a"]),
+ status: "active", setup: { step: "complete", command: "/maya-test" },
+ }));
+ await click("I've sent the test message");
+ expect(mocks.finishSlackSetup).toHaveBeenCalledWith("endpoint-a");
+ client.setQueryData(["chat-endpoint-setup-test-status", "endpoint-a"], { messageReceivedAt: "2026-09-18T20:02:00Z" });
+ await settle();
+ expect(container.textContent).toContain("Received your Slack message.");
+ await click("5Connect your Slack account");
+ expect([...container.querySelectorAll("h1")].find((heading) => !heading.closest("[hidden]"))?.textContent).toBe("Connect your Slack account");
+ expect(container.textContent).toContain("Linked to you");
+ await click("6Try it");
+ expect([...container.querySelectorAll("h1")].find((heading) => !heading.closest("[hidden]"))?.textContent).toBe("Try Maya in Slack");
+ });
+
+ it("keeps failed identity linking in the wizard and allows retry", async () => {
+ mocks.listPrincipals.mockResolvedValue([{ id: "link-a", principalId: "principal-a", externalLabel: "My Slack identity", status: "pending", lastConnectAt: "2026-09-18T20:01:00Z" }]);
+ mocks.confirmIdentityLink.mockRejectedValueOnce(new Error("Expired"));
+ await renderSlackIdentityStep();
+ await click("This is my Slack account");
+ expect(container.textContent).toContain("Couldn't link");
+ expect(container.textContent).not.toContain("Continue to message test");
+ expect([...container.querySelectorAll("button")].find((button) => button.textContent === "This is my Slack account")!.disabled).toBe(false);
+ });
+
+ it("does not offer to claim a Slack identity linked to someone else", async () => {
+ mocks.listPrincipals.mockResolvedValue([{ id: "link-a", principalId: "principal-a", externalLabel: "Someone else", status: "linked", paperclipUserId: "another-user", paperclipUserLabel: "Another Person", lastConnectAt: "2026-09-18T20:01:00Z" }]);
+ await renderSlackIdentityStep();
+ expect(container.textContent).toContain("Linked to Another Person");
+ expect(container.textContent).not.toContain("This is my Slack account");
+ expect(container.textContent).not.toContain("Continue to message test");
+ expect(mocks.createLinkIntent).not.toHaveBeenCalled();
+ });
+
+ it("links the missing HTTPS warning to the setup guide", async () => {
+ await render("slack", false, false);
+ const warning = container.querySelector('[role="alert"]')!;
+ expect(warning.textContent).toContain("Public HTTPS URL required");
+ const link = warning.querySelector("a")!;
+ expect(link.textContent).toBe("Learn how to set up HTTPS");
+ expect(link.href).toBe("https://docs.paperclip.ing/reference/deploy/https/");
+ });
+
+ it("cancels the delayed Slack advance when returning to the agent step", async () => {
+ await render("slack");
+ vi.spyOn(window, "open").mockReturnValue(null);
+ vi.useFakeTimers();
+ const buttons = [...container.querySelectorAll("button")];
+ flushSync(() => buttons.find((button) => button.textContent?.trim() === "Create Slack app")!.click());
+ flushSync(() => buttons.find((button) => button.textContent?.trim() === "1Choose agent")!.click());
+ flushSync(() => vi.advanceTimersByTime(1000));
+ expect(container.querySelector('input[aria-label="Assigned agent"]')).not.toBeNull();
+ expect(mocks.setParams).not.toHaveBeenCalled();
+ vi.useRealTimers();
+ await click("2Create Slack app");
+ await click("I already created the app");
+ expect(container.querySelector("h1")?.textContent).toBe("Add Slack credentials");
+ });
+
+ it.each(["slack", "github", "discord", "telegram", "microsoft-teams"] as const)(
+ "lets %s setup revisit the agent without duplicating the connection or losing provider fields",
+ async (provider) => {
+ await render(provider);
+ const nav = container.querySelector('aside nav[aria-label="Connection setup progress"]')!;
+ expect(nav).not.toBeNull();
+ expect(container.querySelector("main nav")).toBeNull();
+ const steps = [...nav.querySelectorAll("button")];
+ expect(steps[1].getAttribute("aria-current")).toBe("step");
+ expect(steps[2].disabled).toBe(true);
+ const fields = [...container.querySelectorAll("main input")];
+ await click("1Choose agent");
+ expect(container.querySelector('input[aria-label="Assigned agent"]')?.getAttribute("readonly")).not.toBeNull();
+ expect(steps[0].getAttribute("aria-current")).toBe("step");
+ expect(steps[1].disabled).toBe(false);
+ await click("Continue");
+ expect(steps[1].getAttribute("aria-current")).toBe("step");
+ expect([...container.querySelectorAll("main input")]).toEqual(fields);
+ expect(mocks.create).not.toHaveBeenCalled();
+ await click("1Choose agent");
+ await click(provider === "slack" ? "2Create Slack app" : "2Connect provider");
+ expect(steps[1].getAttribute("aria-current")).toBe("step");
+ },
+ );
+
it("copies the one-time webhook secret through the same fallback", async () => {
await render("github");
await click("Generate webhook secret");
diff --git a/ui/src/pages/apps/chat/ChatEndpointDetail.tsx b/ui/src/pages/apps/chat/ChatEndpointDetail.tsx
index 86b3cc7059..c5d2ee946d 100644
--- a/ui/src/pages/apps/chat/ChatEndpointDetail.tsx
+++ b/ui/src/pages/apps/chat/ChatEndpointDetail.tsx
@@ -3,6 +3,11 @@ import { useEffect, useMemo, useState } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import {
AlertTriangle,
+ ArrowDownLeft,
+ ArrowUpRight,
+ ChevronDown,
+ Check,
+ Activity as ActivityIcon,
Copy,
ExternalLink,
Loader2,
@@ -31,9 +36,8 @@ import {
AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import { ToggleSwitch } from "@/components/ui/toggle-switch";
-import { PageTabBar } from "@/components/PageTabBar";
+import { AppLogo } from "../AppLogo";
import { StatusBadge } from "@/components/StatusBadge";
-import { Tabs } from "@/components/ui/tabs";
import { useBreadcrumbs } from "@/context/BreadcrumbContext";
import { useToast } from "@/context/ToastContext";
import { formatDateTime } from "@/lib/utils";
@@ -306,22 +310,9 @@ export function ChatEndpointDetail() {
Continue setup
</Button>
) : null}
- <StatusBadge status={endpoint.status} />
+ {endpoint.status !== "active" && <StatusBadge status={endpoint.status} />}
</div>
</header>
- <Tabs
- value={activeTab}
- onValueChange={(next) => navigate(`/apps/chat/${endpoint.id}/${next}`)}
- >
- <PageTabBar
- items={tabItems}
- value={activeTab}
- onValueChange={(next) =>
- navigate(`/apps/chat/${endpoint.id}/${next}`)
- }
- align="start"
- />
- </Tabs>
{activeTab === "settings" && (
<Settings endpointId={endpoint.id} endpoint={endpoint} />
)}
@@ -329,6 +320,7 @@ export function ChatEndpointDetail() {
<Access
endpointId={endpoint.id}
allowUnlinked={endpoint.allowUnlinkedPeople}
+ endpoint={endpoint}
/>
)}
{activeTab === "conversations" && (
@@ -350,6 +342,8 @@ function Settings({
}) {
const queryClient = useQueryClient();
const { pushToast } = useToast();
+ const [messageCopied, setMessageCopied] = useState(false);
+ const mentionMessage = `@${(endpoint.botUsername ?? endpoint.botLabel ?? endpoint.assignedAgentName).replace(/^@/, "")} you there?`;
const resourcesQuery = useQuery({
queryKey: queryKeys.chatEndpoints.resources(endpointId),
queryFn: () => chatEndpointsApi.listResources(endpointId),
@@ -393,19 +387,15 @@ function Settings({
return (
<section className="max-w-3xl space-y-7">
{endpoint.provider === "imessage-photon" && <p className="text-sm text-muted-foreground">{endpoint.photonAllocation === "shared" ? "Shared Photon project · direct messages only. Enroll senders in Photon and link their Messages identities in Access. Groups cannot be enabled." : "Enable each group individually. Agent replies are visible to everyone in that group; only authorized senders can start work."}</p>}
- {endpoint.provider === "slack" && endpoint.setup?.command && (
- <div className="space-y-2">
- <h2 className="text-lg font-semibold">Slack command</h2>
- <div className="rounded-lg border border-border p-3 text-sm">
- <code>{endpoint.setup.command}</code>
- <p className="mt-2 text-muted-foreground">
- Start work with{" "}
- <code>{endpoint.setup.command} investigate this</code>. In a
- direct message, use <code>{endpoint.setup.command} status</code>,{" "}
- <code>{endpoint.setup.command} new</code>, or{" "}
- <code>{endpoint.setup.command} close</code>. Slack&apos;s bare{" "}
- <code>/status</code> command is not a Paperclip control.
- </p>
+ {endpoint.provider === "slack" && (
+ <div className="space-y-2 text-sm">
+ <h2 className="text-lg font-semibold">Chat in Slack</h2>
+ <p>Invite the bot to a channel, then mention it to start a conversation.</p>
+ <div className="flex items-center justify-between gap-3 rounded-lg border border-border p-3">
+ <code>{mentionMessage}</code>
+ <Button size="icon" variant="ghost" aria-label={messageCopied ? "Message copied" : "Copy message"} onClick={() => {
+ void copyTextToClipboard(mentionMessage).then(() => setMessageCopied(true), () => pushToast({ title: "Couldn’t copy the message", body: "Select and copy it manually.", tone: "error" }));
+ }}>{messageCopied ? <Check className="size-4" /> : <Copy className="size-4" />}</Button>
</div>
</div>
)}
@@ -428,13 +418,9 @@ function Settings({
)}
<div>
<h2 className="text-lg font-semibold">Where this agent can work</h2>
- <p className="mt-1 text-sm text-muted-foreground">
- Provider membership makes a destination available. Paperclip responds
- only where you enable it.
- </p>
</div>
<div className="space-y-2">
- <h3 className="text-sm font-semibold">Destinations</h3>
+ <h3 className="text-sm font-semibold">{endpoint.provider === "slack" ? "Allowed Channels" : "Destinations"}</h3>
{resourcesQuery.isLoading ? (
<p className="text-sm text-muted-foreground">Loading destinations…</p>
) : destinationResources.length === 0 ? (
@@ -538,13 +524,17 @@ function SettingToggle({
function Access({
endpointId,
allowUnlinked,
+ endpoint,
}: {
endpointId: string;
allowUnlinked: boolean;
+ endpoint: ChatEndpoint;
}) {
const queryClient = useQueryClient();
const { pushToast } = useToast();
const [confirmationUrl, setConfirmationUrl] = useState<string | null>(null);
+ const [joinCommandCopied, setJoinCommandCopied] = useState(false);
+ const joinCommand = `${endpoint.setup?.slackApp?.command ?? endpoint.setup?.command ?? "/paperclip"} connect`;
const linksQuery = useQuery({
queryKey: queryKeys.chatEndpoints.principals(endpointId),
queryFn: () => chatEndpointsApi.listPrincipals(endpointId),
@@ -557,6 +547,7 @@ function Access({
queryKeys.chatEndpoints.detail(endpointId),
next,
),
+ onError: (error) => pushToast({ title: "Couldn’t update access", body: error instanceof Error ? error.message : "Try again.", tone: "error" }),
});
const createIntent = useMutation({
mutationFn: (principalId: string) =>
@@ -591,11 +582,26 @@ function Access({
<section className="max-w-3xl space-y-7">
<div>
<h2 className="text-lg font-semibold">External identity access</h2>
- <p className="mt-1 text-sm text-muted-foreground">
- Linked identities act as their current Paperclip user. Unlinked
- people, when allowed, receive a fixed restricted profile.
- </p>
</div>
+ {endpoint.provider === "slack" && (
+ <div className="space-y-3">
+ <h3 className="text-sm font-semibold">Invite others to connect their Slack accounts</h3>
+ <ol className="list-decimal space-y-3 pl-5 text-sm">
+ <li>
+ Ask them to send this command in your Slack workspace:
+ <div className="mt-2 flex items-center justify-between gap-3 rounded-lg border border-border p-3">
+ <code>{joinCommand}</code>
+ <Button size="sm" variant="ghost" onClick={() => {
+ void copyTextToClipboard(joinCommand).then(() => setJoinCommandCopied(true), () => pushToast({ title: "Couldn't copy the command", body: "Select and copy it manually.", tone: "error" }));
+ }}><Copy className="size-4" />{joinCommandCopied ? "Copied" : "Copy command"}</Button>
+ </div>
+ </li>
+ <li>Open the private link from the bot, sign into Paperclip, and confirm their Slack account. The link expires in 15 minutes and works once.</li>
+ <li>If they aren’t a member of this organization, choose <strong>Request access</strong>. An admin must approve their request before they can link their account.</li>
+ </ol>
+ <p className="text-sm text-muted-foreground">Each person links their own account and uses their own Paperclip permissions. They don’t need to create another Slack app or share credentials.</p>
+ </div>
+ )}
<SettingToggle
label="Allow unlinked people"
detail="They are restricted guests. Their tasks run only with an isolated workspace and sandbox environment; otherwise Paperclip safely refuses the request. They cannot approve, hire, spend, manage access, or reassign agents."
@@ -707,41 +713,24 @@ function Conversations({
start one.
</p>
) : (
- <div className="divide-y divide-border border-y border-border">
+ <ul aria-label="Conversations" className="divide-y divide-border overflow-x-auto border-y border-border">
{rows.map((row) => (
- <div key={row.id} className="grid gap-3 py-4 md:grid-cols-3">
- <div className="min-w-0">
- <p className="truncate text-sm font-medium">
- {row.externalLabel}
- </p>
- <p className="text-xs text-muted-foreground">
- {providerNames[provider]}
- </p>
+ <li key={row.id} className="flex min-w-xl items-center gap-3 px-2 py-3 text-sm transition-colors hover:bg-accent/50">
+ <AppLogo name={providerNames[provider]} brandKey={provider} compact className="size-5! rounded-sm bg-transparent" />
+ <div className="flex min-w-0 max-w-56 items-center gap-2">
+ <span className="truncate font-medium" title={row.externalLabel}>{row.externalLabel}</span>
+ {row.externalUrl && <a href={row.externalUrl} target="_blank" rel="noreferrer" className="inline-flex shrink-0 items-center gap-1 text-xs text-muted-foreground hover:text-foreground hover:underline">Open {providerNames[provider]}<ExternalLink className="size-3" /></a>}
</div>
- <div className="min-w-0">
- <p className="truncate text-sm font-medium">
- {row.issueIdentifier ? `${row.issueIdentifier} · ` : ""}
- {row.issueTitle ?? "Waiting for task"}
- </p>
- <StatusBadge status={row.state} />
+ <span aria-hidden="true" className="text-muted-foreground">·</span>
+ <div className="flex min-w-0 flex-1 items-center gap-2">
+ <span className="truncate" title={row.issueTitle ?? undefined}>{row.issueTitle ?? "Waiting for task"}</span>
+ {row.issueId && <Link to={`/issues/${row.issueId}`} className="inline-flex shrink-0 items-center gap-1 text-xs text-muted-foreground hover:text-foreground hover:underline">Open task<ExternalLink className="size-3" /></Link>}
</div>
- <div className="flex flex-wrap items-center gap-2 md:justify-end">
- {row.externalUrl && (
- <Button asChild size="sm" variant="outline">
- <a href={row.externalUrl} target="_blank" rel="noreferrer">
- Open {providerNames[provider]} <ExternalLink />
- </a>
- </Button>
- )}
- {row.issueId && (
- <Button asChild size="sm" variant="outline">
- <Link to={`/issues/${row.issueId}`}>Open task</Link>
- </Button>
- )}
- </div>
- </div>
+ <span className="hidden shrink-0 text-xs text-muted-foreground xl:inline">{row.issueIdentifier}</span>
+ {row.state !== "active" && <StatusBadge status={row.state} />}
+ </li>
))}
- </div>
+ </ul>
)}
</section>
);
@@ -761,10 +750,14 @@ function Activity({
const [resolutionItem, setResolutionItem] = useState<ChatActivityItem | null>(
null,
);
+ const [cursors, setCursors] = useState<Array<string | undefined>>([undefined]);
+ const cursor = cursors[cursors.length - 1];
+ useEffect(() => setCursors([undefined]), [endpointId]);
const query = useQuery({
- queryKey: queryKeys.chatEndpoints.activity(endpointId),
- queryFn: () => chatEndpointsApi.listActivity(endpointId),
+ queryKey: [...queryKeys.chatEndpoints.activity(endpointId), cursor ?? null],
+ queryFn: () => chatEndpointsApi.listActivityPage(endpointId, cursor),
...liveChatQueryOptions,
+ refetchInterval: cursor ? false : liveChatQueryOptions.refetchInterval,
});
const replay = useMutation({
mutationFn: (item: ChatActivityItem) =>
@@ -873,7 +866,7 @@ function Activity({
tone: "error",
}),
});
- const rows = query.data ?? [];
+ const rows = query.data?.items ?? [];
const { status } = endpoint;
const health = connectionHealthPresentation(endpoint);
const lifecycleAction = lifecycle.variables;
@@ -887,7 +880,7 @@ function Activity({
return (
<section className="space-y-5">
<h2 className="text-lg font-semibold">Connection activity</h2>
- {(health.message || health.error) && (
+ {((status !== "active" && health.message) || health.error) && (
<div
className={`flex items-start gap-2 rounded-lg border p-3 text-sm ${status === "attention" || status === "revoked" ? "border-destructive/40 bg-destructive/5 text-destructive" : "border-border bg-muted/30 text-foreground"}`}
>
@@ -911,21 +904,30 @@ function Activity({
</div>
</div>
)}
+ <details className="group rounded-lg border border-border">
+ <summary className="flex cursor-pointer list-none items-center justify-between gap-3 p-4 text-sm font-medium chat-connection-health-summary">
+ <span>Connection health and controls</span>
+ <span className="flex items-center gap-2">
+ {endpoint.setup?.callbacksNeedUpdate && <span className="text-xs text-(--status-task-blocked)">Callback URLs need attention</span>}
+ <ChevronDown className="size-4 text-muted-foreground transition-transform group-open:rotate-180" />
+ </span>
+ </summary>
+ <div className="space-y-5 border-t border-border p-4">
{endpoint.provider === "slack" && callbackSurfaceRows.length > 0 && (
<div
- className={`rounded-lg border p-3 text-sm ${endpoint.setup?.callbacksNeedUpdate ? "border-destructive/40 bg-destructive/5" : "border-border bg-muted/30"}`}
+ className="space-y-3 text-sm"
>
<p className="font-medium">Slack callback health</p>
- <p className="mt-1 text-xs text-muted-foreground">
+ <p className="text-xs text-muted-foreground">
{endpoint.setup?.callbacksNeedUpdate
? "Slack callback URLs need an update. Save the current App Manifest, then exercise Events, Interactivity, and the registered command again."
: "Paperclip records each callback surface independently after Slack successfully calls it."}
</p>
- <div className="mt-3 grid gap-2 sm:grid-cols-3">
+ <div className="divide-y divide-border border-y border-border">
{callbackSurfaceRows.map(([label, surface]) => (
- <div key={label} className="rounded-md border border-border p-2">
+ <div key={label} className="flex flex-wrap items-center justify-between gap-3 py-2">
<p className="text-xs font-medium">{label}</p>
- <p className="mt-1 text-xs text-muted-foreground">
+ <p className="text-xs text-muted-foreground">
{surface.status === "current"
? "Current"
: surface.status === "stale"
@@ -933,7 +935,7 @@ function Activity({
: "Not observed"}
</p>
{surface.observedAt && (
- <p className="mt-1 text-xs text-muted-foreground">
+ <p className="text-xs text-muted-foreground">
Last observed{" "}
<time
dateTime={surface.observedAt}
@@ -952,7 +954,7 @@ function Activity({
</div>
)}
{status !== "archived" && (
- <div className="space-y-2 border-y border-border py-3">
+ <div className="space-y-3 pt-2">
<div className="flex flex-wrap items-center gap-2">
{status === "active" && (
<Button
@@ -1022,9 +1024,11 @@ function Activity({
)}
</div>
)}
+ </div>
+ </details>
<div className="space-y-2">
<h3 className="text-sm font-semibold">
- Delivery and publication history
+ Recent activity
</h3>
<div className="divide-y divide-border border-y border-border">
{query.isLoading && (
@@ -1052,23 +1056,20 @@ function Activity({
rows.map((item) => (
<div
key={item.id}
- className="flex flex-wrap items-start gap-3 py-3"
+ className="flex items-start gap-3 px-2 py-3 transition-colors hover:bg-accent/50"
>
+ <span className="mt-0.5 text-muted-foreground" aria-hidden="true">
+ {item.kind === "delivery" ? <ArrowDownLeft className="size-4" /> : item.kind === "publication" ? <ArrowUpRight className="size-4" /> : <ActivityIcon className="size-4" />}
+ </span>
<div className="min-w-0 flex-1">
- <div className="flex flex-wrap items-center gap-2">
- <span className="text-xs font-medium text-muted-foreground">
- {activityKindLabels[item.kind]}
- </span>
+ <div className="flex flex-wrap items-center gap-x-3 gap-y-1">
+ <p className="min-w-0 flex-1 text-sm font-medium">{item.summary}</p>
<StatusBadge status={item.status} />
- <time
- dateTime={item.createdAt}
- title={item.createdAt}
- className="font-mono text-xs text-muted-foreground"
- >
+ <time dateTime={item.createdAt} title={item.createdAt} className="shrink-0 text-xs tabular-nums text-muted-foreground">
{formatDateTime(item.createdAt, { includeSeconds: true })}
</time>
</div>
- <p className="mt-2 text-sm font-medium">{item.summary}</p>
+ <p className="mt-1 text-xs text-muted-foreground">{activityKindLabels[item.kind]}</p>
{item.fileTransfer && (
<p className="mt-1 text-xs text-muted-foreground">
{item.fileTransfer.filename} —{" "}
@@ -1118,6 +1119,13 @@ function Activity({
)}
</div>
</div>
+ <nav aria-label="Activity pagination" className="flex items-center justify-between gap-3">
+ <span className="text-xs text-muted-foreground">Page {cursors.length}</span>
+ <div className="flex items-center gap-2">
+ <Button size="sm" variant="outline" disabled={cursors.length === 1 || query.isFetching} onClick={() => setCursors((pages) => pages.slice(0, -1))}>Previous</Button>
+ <Button size="sm" variant="outline" disabled={!query.data?.nextCursor || query.isFetching || query.isError} onClick={() => { if (query.data?.nextCursor) setCursors((pages) => [...pages, query.data.nextCursor!]); }}>Next</Button>
+ </div>
+ </nav>
<AlertDialog
open={resolutionItem !== null}
onOpenChange={(open) => !open && setResolutionItem(null)}
diff --git a/ui/src/pages/apps/chat/ChatEndpointSetup.tsx b/ui/src/pages/apps/chat/ChatEndpointSetup.tsx
index ea836b89fd..5f8ac79afa 100644
--- a/ui/src/pages/apps/chat/ChatEndpointSetup.tsx
+++ b/ui/src/pages/apps/chat/ChatEndpointSetup.tsx
@@ -1,3 +1,5 @@
+import { ChatSetupNavigation } from "@/components/chat/ChatSetupNavigation";
+import { SlackIdentityStep } from "./SlackIdentityStep";
import { PhotonConnectStep } from "./PhotonConnectStep";
import { EmailEndpointSetup } from "./EmailEndpointSetup";
import {
@@ -10,10 +12,12 @@ import {
type SetStateAction,
} from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
-import { Check, ExternalLink, Eye, EyeOff, Loader2 } from "lucide-react";
+import { AlertTriangle, CheckCircle2, Copy, CircleHelp, ExternalLink, Eye, EyeOff, Loader2 } from "lucide-react";
import { AgentSelect } from "@/components/AgentMultiSelect";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
+import { Dialog, DialogTrigger, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from "@/components/ui/dialog";
+import { Tooltip, TooltipTrigger, TooltipContent } from "@/components/ui/tooltip";
import { Textarea } from "@/components/ui/textarea";
import { useBreadcrumbs } from "@/context/BreadcrumbContext";
import { useCompany } from "@/context/CompanyContext";
@@ -30,7 +34,7 @@ import { useNavigate, useSearchParams } from "@/lib/router";
import { queryKeys } from "@/lib/queryKeys";
import { copyTextToClipboard } from "@/lib/clipboard";
import { useCopyAction } from "@/lib/use-copy-action";
-import { isAgentStatusInvokable } from "@paperclipai/shared";
+import { isAgentStatusInvokable, slackAppConfigurationSchema, type SlackAppConfiguration } from "@paperclipai/shared";
import { sanitizedSetupErrorMessage } from "./chat-setup-error";
import {
createGitHubPrivateKeyReadGuard,
@@ -101,31 +105,6 @@ export function isChatEndpointRepairing(
);
}
-function SetupRail({ step }: { step: number }) {
- return (
- <ol className="space-y-2 text-sm" aria-label="Connection setup progress">
- {["Choose agent", "Connect provider", "Try it"].map((label, index) => (
- <li key={label} className="flex items-center gap-2">
- <span
- className={`flex h-6 w-6 items-center justify-center rounded-full border ${index < step ? "border-primary bg-primary text-primary-foreground" : index === step ? "border-foreground text-foreground" : "border-border text-muted-foreground"}`}
- >
- {index < step ? <Check className="h-3.5 w-3.5" /> : index + 1}
- </span>
- <span
- className={
- index === step
- ? "font-medium text-foreground"
- : "text-muted-foreground"
- }
- >
- {label}
- </span>
- </li>
- ))}
- </ol>
- );
-}
-
export function ChatEndpointSetup() {
const [params] = useSearchParams();
return params.get("provider") === "agentmail" ? <EmailEndpointSetup /> : <ChatSdkEndpointSetup />;
@@ -148,6 +127,9 @@ function ChatSdkEndpointSetup() {
params.get("purpose") === "chat" ? "chat" : "choice",
);
const [agentId, setAgentId] = useState(preselectedAgent);
+ const [slackCredentialsReady, setSlackCredentialsReady] = useState(params.get("stage") === "credentials");
+ const [viewedStep, setViewedStep] = useState<number | null>(null);
+ const [slackIdentityReady, setSlackIdentityReady] = useState(false);
const [endpoint, setEndpoint] = useState<ChatEndpoint | null>(null);
const [credentials, setCredentials] = useState<Record<string, string>>({});
const [generatedWebhookSecret, setGeneratedWebhookSecret] = useState("");
@@ -237,6 +219,7 @@ function ChatSdkEndpointSetup() {
assignedAgentId: agentId,
}),
onSuccess: (next) => {
+ setViewedStep(null);
syncEndpointSnapshot(next);
if (next.provider === "imessage-photon") {
const resumed = new URLSearchParams(params);
@@ -252,22 +235,37 @@ function ChatSdkEndpointSetup() {
}),
});
const setupAction = useMutation({
- mutationFn: ({
+ mutationFn: async ({
action,
values,
}: {
action: ChatEndpointSetupAction;
values?: Record<string, string>;
- }) => chatEndpointsApi.setup(endpoint!.id, provider === "imessage-photon" ? {
+ }) => {
+ const endpointId = endpoint!.id;
+ try {
+ return await chatEndpointsApi.setup(endpointId, provider === "imessage-photon" ? {
action,
...(values?.projectSecret ? { credentials: { projectSecret: values.projectSecret } } : {}),
...(values?.projectId && values.allocation === "shared" ? { photon: { allocation: "shared" as const, projectId: values.projectId } } : values?.projectId && values?.lineId ? { photon: { allocation: "dedicated" as const, projectId: values.projectId, lineId: values.lineId } } : {}),
- } : { action, credentials: values }),
+ } : { action, credentials: values });
+ } catch (error) {
+ // Another open tab may have completed verification, or the successful
+ // response may have been lost. Read the canonical state before retrying.
+ if (action === "verify") {
+ const current = await chatEndpointsApi.get(endpointId).catch(() => null);
+ if (current?.setup?.step === "test" || current?.setup?.step === "complete") return current;
+ }
+ throw error;
+ }
+ },
onMutate: () => setSetupError(null),
onSuccess: (next) => {
setSetupError(null);
+ setViewedStep(null);
syncEndpointSnapshot(next);
setCredentials({});
+ if (next.setup?.step !== "test" && next.setup?.step !== "complete") setSlackIdentityReady(false);
},
onError: (error, variables) =>
setSetupError(sanitizedSetupErrorMessage(error, variables.values)),
@@ -337,7 +335,7 @@ function ChatSdkEndpointSetup() {
}),
});
const testConnection = useMutation({
- mutationFn: () => chatEndpointsApi.test(endpoint!.id),
+ mutationFn: () => provider === "slack" ? chatEndpointsApi.finishSlackSetup(endpoint!.id) : chatEndpointsApi.test(endpoint!.id),
onSuccess: (next) => {
syncEndpointSnapshot(next);
if (next.status === "active") navigate(`/apps/chat/${next.id}/settings`);
@@ -353,6 +351,45 @@ function ChatSdkEndpointSetup() {
}),
});
+ const repairing = isChatEndpointRepairing(
+ endpoint,
+ resumeEndpointId,
+ reconnectRequested,
+ );
+ const isSlack = provider === "slack";
+ const tryStep = isSlack ? 5 : 2;
+ const availableStep = endpoint
+ ? !repairing &&
+ (endpoint.setup?.step === "test" || endpoint.setup?.step === "complete")
+ ? isSlack && !slackIdentityReady && endpoint.setup?.step !== "complete" ? 4 : tryStep
+ : isSlack && endpoint.providerAccountId && !repairing ? 3
+ : isSlack && (slackCredentialsReady || repairing) ? 2 : 1
+ : 0;
+ const step = Math.min(viewedStep ?? availableStep, availableStep);
+ const slackVerificationQuery = useQuery({
+ queryKey: ["chat-endpoint-slack-webhook-verification", endpoint?.id],
+ queryFn: () => chatEndpointsApi.get(endpoint!.id),
+ enabled: Boolean(isSlack && step === 3 && endpoint?.setup?.step === "provider_setup" &&
+ !endpoint.setup.webhookVerifiedAt && !setupAction.isPending),
+ refetchInterval: 1_500,
+ });
+ useEffect(() => {
+ const next = slackVerificationQuery.data;
+ if (!next || !endpoint || next.id !== endpoint.id || setupAction.isPending ||
+ endpoint.setup?.step !== "provider_setup" || endpoint.setup.webhookVerifiedAt ||
+ !next.setup?.webhookVerifiedAt) return;
+ setEndpoint(next);
+ }, [slackVerificationQuery.data, endpoint, setupAction.isPending]);
+ const autoVerificationAttempt = useRef<string | null>(null);
+ useEffect(() => {
+ if (!isSlack || step !== 3 || endpoint?.setup?.step !== "provider_setup" ||
+ !endpoint.setup.webhookVerifiedAt || setupAction.isPending) return;
+ const attempt = `${endpoint.id}:${endpoint.setup.webhookVerifiedAt}`;
+ if (autoVerificationAttempt.current === attempt) return;
+ autoVerificationAttempt.current = attempt;
+ setupAction.mutate({ action: "verify" });
+ }, [isSlack, step, endpoint, setupAction]);
+
if (!provider)
return (
<p className="text-sm text-destructive">
@@ -369,6 +406,7 @@ function ChatSdkEndpointSetup() {
if (purpose === "choice") {
return (
<div className="max-w-2xl space-y-6">
+ <ChatSetupNavigation labels={provider === "slack" ? ["Choose agent", "Create Slack app", "Add credentials", "Verify Slack connection", "Connect your Slack account", "Try it"] : undefined} step={0} availableStep={0} onSelect={() => setPurpose("chat")} />
<div>
<h1 className="text-xl font-bold">Choose how to connect</h1>
<p className="mt-1 text-sm text-muted-foreground">
@@ -407,23 +445,18 @@ function ChatSdkEndpointSetup() {
);
}
- const repairing = isChatEndpointRepairing(
- endpoint,
- resumeEndpointId,
- reconnectRequested,
- );
- const step = endpoint
- ? !repairing &&
- (endpoint.setup?.step === "test" || endpoint.setup?.step === "complete")
- ? 2
- : 1
- : 0;
const selectedAgent = activeAgents.find((agent) => agent.id === agentId);
return (
- <div className="grid max-w-4xl gap-8 md:grid-cols-(--gtc-11)">
- <SetupRail step={step} />
- <main className="min-w-0 space-y-6">
- {!endpoint ? (
+ <div className="max-w-2xl space-y-6">
+ <ChatSetupNavigation
+ labels={isSlack ? ["Choose agent", "Create Slack app", "Add credentials", "Verify Slack connection", "Connect your Slack account", "Try it"] : undefined}
+ step={step}
+ availableStep={availableStep}
+ disabled={createEndpoint.isPending || setupAction.isPending || generateSetupSecret.isPending || testConnection.isPending}
+ onSelect={setViewedStep}
+ />
+ <div className="min-w-0 space-y-6">
+ {step === 0 ? (
<>
<div>
<h1 className="text-xl font-bold">
@@ -434,17 +467,22 @@ function ChatSdkEndpointSetup() {
channel to represent a different agent.
</p>
</div>
- <AgentSelect
+ {endpoint ? (
+ <Input aria-label="Assigned agent" value={endpoint.assignedAgentName ?? selectedAgent?.name ?? agentId} readOnly />
+ ) : <AgentSelect
agents={activeAgents}
value={agentId}
onChange={setAgentId}
placeholder="Choose an active agent"
emptyMessage="No active agents are available."
- />
- <div className="flex justify-end">
+ />}
+ <div className="flex items-center justify-between gap-3">
+ <Button variant="ghost" className="text-muted-foreground" onClick={() => navigate("/apps")}>
+ Save &amp; exit
+ </Button>
<Button
disabled={!agentId || createEndpoint.isPending}
- onClick={() => createEndpoint.mutate()}
+ onClick={() => endpoint ? setViewedStep(1) : createEndpoint.mutate()}
>
{createEndpoint.isPending && (
<Loader2 className="h-4 w-4 animate-spin" />
@@ -453,8 +491,9 @@ function ChatSdkEndpointSetup() {
</Button>
</div>
</>
- ) : step === 1 ? (
- <>
+ ) : null}
+ {endpoint && (
+ <div hidden={step !== 1 && !(isSlack && (step === 2 || step === 3))} className="space-y-6">
{setupError ? (
<div
role="alert"
@@ -467,8 +506,21 @@ function ChatSdkEndpointSetup() {
<ProviderConnectStep
key={`${provider}:${endpoint.id}`}
provider={provider}
+ slackStage={step === 1 ? "app" : step === 3 ? "finish" : "credentials"}
+ onSlackCredentialsContinue={() => setViewedStep(3)}
+ onSlackVerificationContinue={() => setViewedStep(4)}
+ slackVerificationError={slackVerificationQuery.isError}
+ onSlackAppCreated={() => {
+ setSlackCredentialsReady(true);
+ setViewedStep(2);
+ const resumed = new URLSearchParams(params);
+ resumed.set("resume", endpoint.id);
+ resumed.set("stage", "credentials");
+ setParams(resumed, { replace: true });
+ }}
agentName={selectedAgent?.name ?? endpoint.assignedAgentName}
endpoint={endpoint}
+ onEndpointSaved={syncEndpointSnapshot}
credentials={credentials}
setCredentials={setCredentials}
repairing={repairing}
@@ -480,8 +532,21 @@ function ChatSdkEndpointSetup() {
setupAction.mutate({ action, values })
}
/>
- </>
- ) : (
+ </div>
+ )}
+ {endpoint && isSlack && step === 4 && (
+ <SlackIdentityStep
+ endpointId={endpoint.id}
+ command={endpoint.setup?.slackApp?.command ?? endpoint.setup?.command ?? "/paperclip"}
+ testStartedAt={endpoint.setup?.testStartedAt}
+ onSaveExit={() => navigate("/apps")}
+ onConnected={() => {
+ setSlackIdentityReady(true);
+ setViewedStep(5);
+ }}
+ />
+ )}
+ {endpoint && step === tryStep && (
<TryStep
endpointId={endpoint.id}
provider={provider}
@@ -503,38 +568,51 @@ function ChatSdkEndpointSetup() {
pending={testConnection.isPending}
onOpenAccess={() => navigate(`/apps/chat/${endpoint.id}/access`)}
onTest={() => testConnection.mutate()}
+ onSaveExit={() => navigate("/apps")}
/>
)}
- <div className="flex justify-start">
- <Button variant="ghost" onClick={() => navigate("/apps")}>
+ {step !== 0 && !(isSlack && (step === 1 || step === 2 || step === 3 || step === 4 || step === 5)) && <div className="flex justify-start">
+ <Button className="text-muted-foreground" variant="ghost" onClick={() => navigate("/apps")}>
Save &amp; exit
</Button>
- </div>
- </main>
+ </div>}
+ </div>
</div>
);
}
function ProviderConnectStep({
provider,
+ slackStage,
+ onSlackCredentialsContinue,
+ onSlackVerificationContinue,
+ slackVerificationError,
+ onSlackAppCreated,
agentName,
endpoint,
credentials,
setCredentials,
repairing,
pending,
+ onEndpointSaved,
generatedWebhookSecret,
generatingSetupSecret,
onGenerateSetupSecret,
onAction,
}: {
provider: ChatProvider;
+ slackStage: "app" | "credentials" | "finish";
+ onSlackCredentialsContinue: () => void;
+ onSlackVerificationContinue: () => void;
+ slackVerificationError: boolean;
+ onSlackAppCreated: () => void;
agentName: string;
endpoint: ChatEndpoint;
credentials: Record<string, string>;
setCredentials: Dispatch<SetStateAction<Record<string, string>>>;
repairing: boolean;
pending: boolean;
+ onEndpointSaved: (endpoint: ChatEndpoint) => void;
generatedWebhookSecret: string;
generatingSetupSecret: boolean;
onGenerateSetupSecret: () => void;
@@ -544,6 +622,15 @@ function ProviderConnectStep({
) => void;
}) {
const { pushToast } = useToast();
+ const navigate = useNavigate();
+ const slackBotToken = (credentials.botToken ?? "").trim();
+ const slackBotTokenInvalid = provider === "slack" && slackBotToken.length > 0 &&
+ !slackBotToken.startsWith("xoxb-");
+ const slackSigningSecretHasTokenPrefix = provider === "slack" &&
+ /^x[a-z0-9]*-/i.test((credentials.signingSecret ?? "").trim());
+ const slackCredentialsSaved = provider === "slack" && Boolean(endpoint.providerAccountId);
+ const continueWithSavedSlackCredentials = slackCredentialsSaved && !repairing &&
+ !slackBotToken && !credentials.signingSecret?.trim();
const reportCopyFailure = () =>
pushToast({
title: "Couldn't copy to clipboard",
@@ -585,6 +672,17 @@ function ProviderConnectStep({
// value the reader never copied. The status resets itself, and a refused
// clipboard reads as a failure instead of a success.
const webhookSecretCopy = useCopyAction();
+ const [openingSlackApp, setOpeningSlackApp] = useState(false);
+ const slackAdvanceTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
+ useEffect(() => {
+ setOpeningSlackApp(false);
+ return () => {
+ if (slackAdvanceTimer.current !== null) {
+ clearTimeout(slackAdvanceTimer.current);
+ slackAdvanceTimer.current = null;
+ }
+ };
+ }, [slackStage]);
const [privateKeyVisible, setPrivateKeyVisible] = useState(false);
const [privateKeyFileError, setPrivateKeyFileError] = useState<string | null>(
null,
@@ -633,7 +731,7 @@ function ProviderConnectStep({
setPrivateKeyFileLoading(false);
setCredentials((current) => ({ ...current, privateKey }));
};
- const slackCommand =
+ const defaultSlackCommand =
endpoint.setup?.command ??
`/${
agentName
@@ -642,8 +740,30 @@ function ProviderConnectStep({
.replace(/^-+|-+$/g, "")
.slice(0, 24) || "paperclip"
}`;
- const slackBotName = slackBotNameForAgent(agentName);
- const slackAppName = `${slackBotName.slice(0, 25)}-paperclip`;
+ const defaultSlackBotName = slackBotNameForAgent(agentName);
+ const [slackApp, setSlackApp] = useState<SlackAppConfiguration>(() =>
+ endpoint.setup?.slackApp ?? {
+ appName: `${defaultSlackBotName.slice(0, 25)}-paperclip`,
+ botName: defaultSlackBotName,
+ command: defaultSlackCommand,
+ },
+ );
+ const slackDetailsEditable = endpoint.status === "draft" && !endpoint.botExternalId;
+ const slackValidation = slackAppConfigurationSchema.safeParse(slackApp);
+ const saveSlackApp = useMutation({
+ scope: { id: `slack-app-details:${endpoint.id}` },
+ mutationFn: (details: SlackAppConfiguration) =>
+ chatEndpointsApi.update(endpoint.id, { slackApp: details }),
+ onSuccess: onEndpointSaved,
+ });
+ const persistSlackApp = () => {
+ if (!slackDetailsEditable || !slackValidation.success) return;
+ if (JSON.stringify(slackValidation.data) === JSON.stringify(endpoint.setup?.slackApp)) return;
+ saveSlackApp.mutate(slackValidation.data);
+ };
+ const slackAppName = slackApp.appName.trim();
+ const slackBotName = slackApp.botName.trim();
+ const slackCommand = slackApp.command.trim();
const slackWebhookUrl =
endpoint.setup?.webhookUrl ?? "<paperclip-webhook-url>";
const slackManifest = `display_information:
@@ -659,7 +779,7 @@ features:
display_name: ${JSON.stringify(slackBotName)}
slash_commands:
- command: ${JSON.stringify(slackCommand)}
- description: Start or manage work with ${JSON.stringify(agentName)}
+ description: ${JSON.stringify(`Start or manage work with ${agentName}`)}
usage_hint: ${JSON.stringify("status | new | close | <task>")}
should_escape: false
url: ${JSON.stringify(slackWebhookUrl)}
@@ -714,6 +834,9 @@ settings:
interactivity:
is_enabled: true
request_url: ${JSON.stringify(slackWebhookUrl)}`;
+ // Slack's documented creation link accepts a URL-encoded YAML manifest.
+ const slackCreateUrl = `https://api.slack.com/apps?new_app=1&manifest_yaml=${encodeURIComponent(slackManifest)}`;
+ useEffect(() => setManifestCopied(false), [slackManifest]);
const teamsClientId =
credentials.clientId?.trim() || "<application-client-id>";
const teamsManifestSettings = JSON.stringify(
@@ -1361,137 +1484,270 @@ settings:
</Button>
</div>
);
- if (endpoint.providerAccountId && !repairing)
+ if (slackStage === "finish")
return (
<div className="space-y-5">
<div>
- <h1 className="text-xl font-bold">Finish Slack setup</h1>
+ <h1 className="text-xl font-bold">Verify Slack connection</h1>
<p className="mt-1 text-sm text-muted-foreground">
- Point the Slack app at Paperclip now that its signing secret is
- connected.
- </p>
- </div>
- {endpointValue("Paperclip webhook URL", endpoint.setup?.webhookUrl)}
- {endpointValue("Slack command", slackCommand)}
- <div className="rounded-lg border border-border p-3 text-sm">
- <p className="font-medium">Use the registered command</p>
- <p className="mt-1 text-muted-foreground">
- Start work with <code>{slackCommand} investigate this</code>. In a
- direct message, use <code>{slackCommand} status</code>,{" "}
- <code>{slackCommand} new</code>, or{" "}
- <code>{slackCommand} close</code>. Slack&apos;s bare{" "}
- <code>/status</code> command is not a Paperclip control.
+ Slack needs to confirm that it can reach your Paperclip instance.
</p>
</div>
<ol className="list-decimal space-y-2 pl-5 text-sm">
- <li>
- Return to <strong>App Manifest</strong> in Slack and click{" "}
- <strong>Save Changes</strong>. The copied manifest already contains
- the event, interaction, and slash-command URLs. Slack verifies the
- Events URL when you save; Paperclip records Interactivity and slash
- command health only after each signed callback is observed.
- </li>
+ <li><a className="underline underline-offset-4" href="https://api.slack.com/apps" target="_blank" rel="noopener noreferrer">Open Slack app Settings <ExternalLink className="inline size-3" /></a> and choose <strong>{slackApp.appName}</strong>.</li>
+ <li>Choose <strong>Event Subscriptions</strong>.</li>
+ <li>Beside the prefilled <strong>Request URL</strong>, click <strong>Retry</strong> if it isn&apos;t verified. Save changes if Slack asks.</li>
</ol>
- <div className="flex flex-wrap gap-2">
- <Button
- variant="outline"
- onClick={() => openProviderSetup("https://api.slack.com/apps")}
- >
- Open Slack app settings <ExternalLink />
- </Button>
- <Button disabled={pending} onClick={() => onAction("verify")}>
- {pending && <Loader2 className="h-4 w-4 animate-spin" />}
- Start Slack message test
+ {endpoint.setup?.webhookVerifiedAt ? (
+ <p role="status" className="flex items-center gap-2 text-sm">
+ <CheckCircle2 className="size-4 text-(--status-task-done)" />
+ Slack verified your connection.{pending ? " Opening the message test…" : ""}
+ </p>
+ ) : slackVerificationError ? (
+ <p role="alert" className="text-sm text-destructive">Couldn&apos;t check verification. We&apos;ll keep trying; check your connection if this continues.</p>
+ ) : (
+ <p role="status" className="flex items-center gap-2 text-sm text-muted-foreground">
+ <Loader2 className="size-4 animate-spin" /> Waiting for Slack to verify. We&apos;ll continue automatically.
+ </p>
+ )}
+ <details className="text-sm">
+ <summary className="cursor-pointer text-muted-foreground">Troubleshooting</summary>
+ <div className="mt-3 space-y-3">
+ <p className="text-muted-foreground">If the Request URL is missing or different, paste this URL into Event Subscriptions. If verification fails, check that your public HTTPS server is reachable and your Signing Secret is correct.</p>
+ {endpointValue("Paperclip webhook URL", endpoint.setup?.webhookUrl)}
+ </div>
+ </details>
+ <div className="flex items-center justify-between gap-3">
+ <Button variant="ghost" className="text-muted-foreground" onClick={() => navigate("/apps")}>Save &amp; exit</Button>
+ <Button disabled={pending || !endpoint.setup?.webhookVerifiedAt} onClick={() =>
+ endpoint.setup?.step === "provider_setup" ? onAction("verify") : onSlackVerificationContinue()
+ }>
+ {pending && <Loader2 className="size-4 animate-spin" />}
+ Continue
</Button>
</div>
</div>
);
+
return (
<div className="space-y-5">
+ {!endpoint.setup?.webhookUrl && (
+ <div role="alert" className="flex items-start gap-3 rounded-lg border border-destructive/30 bg-destructive/10 p-4">
+ <AlertTriangle className="size-5 shrink-0 text-destructive" />
+ <div className="space-y-1">
+ <p className="text-sm font-semibold">Public HTTPS URL required</p>
+ <p className="text-sm">
+ Slack needs a public HTTPS URL to send messages to Paperclip.
+ Configure one for this instance before creating or connecting your Slack app.
+ </p>
+ <a
+ href="https://docs.paperclip.ing/reference/deploy/https/"
+ target="_blank"
+ rel="noopener noreferrer"
+ className="text-sm underline underline-offset-4"
+ >
+ Learn how to set up HTTPS
+ </a>
+ </div>
+ </div>
+ )}
<div>
- <h1 className="text-xl font-bold">Connect a Slack app</h1>
- <p className="mt-1 text-sm text-muted-foreground">
- {repairing
- ? "Reconnect verifies or replaces credentials for this same Slack app. It does not reinstall the app or change its workspace or channel membership. Leave credentials blank to reuse the saved values."
- : "Bring your own Slack app. The manifest requests the scopes Paperclip needs; credentials remain write-only."}
- </p>
+ <h1 className="text-xl font-bold">{slackStage === "app" ? "Create a Slack app" : "Add Slack credentials"}</h1>
+ {repairing && (
+ <p className="mt-1 text-sm text-muted-foreground">
+ Reconnect verifies or replaces credentials for this same Slack app. It does not reinstall the app or change its workspace or channel membership. Leave credentials blank to reuse the saved values.
+ </p>
+ )}
</div>
- <ol className="list-decimal space-y-2 pl-5 text-sm">
- <li>
- Copy the manifest, then create a Slack app{" "}
- <strong>From an app manifest</strong> in the target workspace.
- </li>
- <li>
- Open <strong>OAuth &amp; Permissions</strong>, install the app to the
- workspace, and copy its Bot User OAuth Token.
- </li>
- <li>
- Open <strong>Basic Information</strong> and copy its Signing Secret.
- </li>
- </ol>
- <div className="space-y-2 rounded-lg border border-border p-3 text-sm">
- <div className="flex items-center justify-between gap-4">
- <span className="text-muted-foreground">Slack app name</span>
- <code>{slackAppName}</code>
- </div>
- <div className="flex items-center justify-between gap-4">
- <span className="text-muted-foreground">Bot display name</span>
- <code>{slackBotName}</code>
+ <div hidden={slackStage !== "app"} className="space-y-5">
+ <div className="space-y-3 text-sm">
+ {([
+ ["appName", "Slack app name", 35, "The name of your app in Slack’s app directory and settings."],
+ ["botName", "Bot display name", 80, "The name people see when your bot sends a message. Use lowercase letters, numbers, periods, hyphens, or underscores."],
+ ["command", "Slash command", 32, "The command people type in Slack to talk to this agent. Start with /, followed by lowercase letters, numbers, hyphens, or underscores."],
+ ] as const).map(([key, label, maxLength, help]) => (
+ <div key={key} className="grid items-center gap-2 sm:grid-cols-2">
+ <div className="flex items-center gap-1.5">
+ <label htmlFor={`slack-${key}`}>{label}</label>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <button
+ type="button"
+ aria-label={`Help with ${label.toLowerCase()}`}
+ className="rounded-sm text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
+ >
+ <CircleHelp className="size-3.5" aria-hidden="true" />
+ </button>
+ </TooltipTrigger>
+ <TooltipContent className="max-w-xs">{help}</TooltipContent>
+ </Tooltip>
+ </div>
+ <Input
+ id={`slack-${key}`}
+ className="bg-background text-foreground dark:bg-background"
+ value={slackApp[key]}
+ maxLength={maxLength}
+ readOnly={!slackDetailsEditable}
+ aria-invalid={!slackValidation.success && slackValidation.error.issues.some((issue) => issue.path[0] === key)}
+ onChange={(event) => setSlackApp({ ...slackApp, [key]: event.target.value })}
+ onBlur={persistSlackApp}
+ />
+ </div>
+ ))}
+ {!slackValidation.success && (
+ <p role="alert" className="text-sm text-destructive">{slackValidation.error.issues[0].message}</p>
+ )}
+ {saveSlackApp.isError && (
+ <div role="alert" className="space-y-2 text-sm text-destructive">
+ <p>Couldn&apos;t save the Slack app details. Try again before connecting.</p>
+ <Button variant="outline" size="sm" onClick={persistSlackApp}>Retry saving</Button>
+ </div>
+ )}
+ <div className="flex justify-end">
+ <Dialog>
+ <DialogTrigger asChild>
+ <Button variant="link" className="h-auto p-0 text-xs text-muted-foreground underline underline-offset-4">
+ View Slack App Manifest
+ </Button>
+ </DialogTrigger>
+ <DialogContent className="sm:max-w-2xl">
+ <DialogHeader>
+ <DialogTitle>Slack app manifest</DialogTitle>
+ <DialogDescription>
+ Generated from your app name, bot name, and slash command. Edit those fields to update the manifest.
+ </DialogDescription>
+ </DialogHeader>
+ <Textarea
+ aria-label="Slack app manifest"
+ className="h-80 font-mono text-xs"
+ readOnly
+ value={slackManifest}
+ />
+ <DialogFooter>
+ <Button
+ variant="outline"
+ disabled={!slackValidation.success}
+ onClick={() => {
+ void copyTextToClipboard(slackManifest).then(
+ () => setManifestCopied(true),
+ reportCopyFailure,
+ );
+ }}
+ >
+ {manifestCopied ? "Manifest copied" : "Copy manifest"}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ </div>
</div>
- <div className="flex items-center justify-between gap-4">
- <span className="text-muted-foreground">Slash command</span>
- <code>{slackCommand}</code>
+ <div className="flex flex-wrap items-center justify-between gap-3 pt-3">
+ <Button variant="ghost" className="text-muted-foreground" onClick={() => navigate("/apps")}>
+ Save &amp; exit
+ </Button>
+ <div className="ml-auto flex flex-wrap items-center justify-end gap-2">
+ <Button variant="outline" disabled={openingSlackApp || !endpoint.setup?.webhookUrl || !slackValidation.success || saveSlackApp.isPending || saveSlackApp.isError} onClick={onSlackAppCreated}>
+ I already created the app
+ </Button>
+ {!repairing && (
+ <Button
+ disabled={openingSlackApp || !endpoint.setup?.webhookUrl || !slackValidation.success || saveSlackApp.isPending || saveSlackApp.isError}
+ onClick={() => {
+ window.open(slackCreateUrl, "_blank", "noopener,noreferrer");
+ setOpeningSlackApp(true);
+ // Let Slack open before changing the step behind its new tab.
+ slackAdvanceTimer.current = setTimeout(() => {
+ slackAdvanceTimer.current = null;
+ setOpeningSlackApp(false);
+ onSlackAppCreated();
+ }, 1000);
+ }}
+ >
+ Create Slack app <ExternalLink />
+ </Button>
+ )}
+ </div>
</div>
</div>
- <label className="grid gap-2 text-sm font-medium">
- Slack app manifest
- <Textarea
- className="min-h-56 font-mono text-xs"
- readOnly
- value={slackManifest}
- />
- </label>
- <div className="flex flex-wrap gap-2">
- <Button
- variant="outline"
- onClick={() => {
- void copyTextToClipboard(slackManifest).then(
- () => setManifestCopied(true),
- reportCopyFailure,
- );
- }}
- >
- {manifestCopied ? "Manifest copied" : "Copy manifest"}
- </Button>
- <Button
- variant="outline"
- onClick={() => openProviderSetup("https://api.slack.com/apps")}
- >
- Open Slack app settings <ExternalLink />
- </Button>
- </div>
- {field("botToken", "Bot User OAuth Token")}
- {field("signingSecret", "Signing Secret")}
- {!endpoint.setup?.webhookUrl && (
- <p className="text-sm text-destructive">
- Configure a public HTTPS URL for this Paperclip instance before
- connecting Slack.
+ <div hidden={slackStage !== "credentials"} className="space-y-5">
+ <p className="text-sm">
+ Now you need to find two secrets. They are in two different screens on Slack.
</p>
- )}
- <Button
- disabled={
- (!repairing &&
- (!credentials.botToken || !credentials.signingSecret)) ||
- !endpoint.setup?.webhookUrl ||
- pending
- }
- onClick={() =>
- onAction(repairing ? "reconnect" : "configure", credentials)
- }
- >
- {pending && <Loader2 className="h-4 w-4 animate-spin" />}
- {repairing ? "Reconnect Slack app" : "Connect Slack app"}
- </Button>
+ {slackCredentialsSaved && !repairing && (
+ <p className="text-sm text-muted-foreground">Your credentials are saved. Leave the fields blank to keep them, or enter replacements.</p>
+ )}
+ <section className="space-y-3">
+ <h2 className="text-sm font-semibold"><label htmlFor="slack-bot-token">Bot User OAuth Token</label></h2>
+ <ul id="slack-bot-token-help" className="list-disc space-y-1 pl-5 text-sm">
+ <li>
+ <a href="https://api.slack.com/apps" target="_blank" rel="noopener noreferrer" className="underline underline-offset-4">
+ Open Slack app Settings <ExternalLink className="inline size-3" />
+ </a> and choose <strong>{slackApp.appName}</strong>.
+ </li>
+ <li>Choose <strong>OAuth &amp; Permissions</strong></li>
+ <li>Copy and paste your <strong>Bot OAuth Token</strong></li>
+ </ul>
+ <Input
+ id="slack-bot-token"
+ type="password"
+ placeholder={slackCredentialsSaved ? "Saved — leave blank to keep" : undefined}
+ value={credentials.botToken ?? ""}
+ aria-invalid={slackBotTokenInvalid || undefined}
+ aria-describedby={`slack-bot-token-help${slackBotTokenInvalid ? " slack-bot-token-warning" : ""}`}
+ onChange={(event) => setCredentials({ ...credentials, botToken: event.target.value })}
+ />
+ {slackBotTokenInvalid && (
+ <p id="slack-bot-token-warning" role="alert" className="text-sm text-destructive">
+ Your Bot User OAuth Token must start with <code>xoxb-</code>. Copy it from <strong>OAuth &amp; Permissions</strong>.
+ </p>
+ )}
+ </section>
+ <section className="space-y-3">
+ <h2 className="text-sm font-semibold"><label htmlFor="slack-signing-secret">Signing Secret</label></h2>
+ <ul id="slack-signing-secret-help" className="list-disc space-y-1 pl-5 text-sm">
+ <li>
+ <a href="https://api.slack.com/apps" target="_blank" rel="noopener noreferrer" className="underline underline-offset-4">
+ Open Slack app Settings <ExternalLink className="inline size-3" />
+ </a> and choose <strong>{slackApp.appName}</strong>.
+ </li>
+ <li>Choose <strong>Basic Information</strong></li>
+ <li>Copy and paste your <strong>Signing Secret</strong></li>
+ </ul>
+ <Input
+ id="slack-signing-secret"
+ type="password"
+ placeholder={slackCredentialsSaved ? "Saved — leave blank to keep" : undefined}
+ value={credentials.signingSecret ?? ""}
+ aria-invalid={slackSigningSecretHasTokenPrefix || undefined}
+ aria-describedby={`slack-signing-secret-help${slackSigningSecretHasTokenPrefix ? " slack-signing-secret-warning" : ""}`}
+ onChange={(event) => setCredentials({ ...credentials, signingSecret: event.target.value })}
+ />
+ {slackSigningSecretHasTokenPrefix && (
+ <p id="slack-signing-secret-warning" role="alert" className="text-sm text-destructive">
+ Use the <strong>Signing Secret</strong>, NOT an app or bot token. The Signing Secret has no token prefix.
+ </p>
+ )}
+ </section>
+ <div className="flex flex-wrap items-center justify-between gap-3">
+ <Button variant="ghost" className="text-muted-foreground" onClick={() => navigate("/apps")}>
+ Save &amp; exit
+ </Button>
+ <Button
+ className="ml-auto"
+ disabled={
+ (!repairing && !slackCredentialsSaved && (!slackBotToken || !credentials.signingSecret?.trim())) ||
+ !endpoint.setup?.webhookUrl || !slackValidation.success ||
+ saveSlackApp.isPending || saveSlackApp.isError || pending || slackSigningSecretHasTokenPrefix || slackBotTokenInvalid
+ }
+ onClick={() => continueWithSavedSlackCredentials
+ ? onSlackCredentialsContinue()
+ : onAction(repairing || slackCredentialsSaved ? "reconnect" : "configure", credentials)}
+ >
+ {pending && <Loader2 className="h-4 w-4 animate-spin" />}
+ {continueWithSavedSlackCredentials ? "Continue" : repairing || slackCredentialsSaved ? "Reconnect Slack app" : "Connect Slack app"}
+ </Button>
+ </div>
+ </div>
</div>
);
}
@@ -1508,6 +1764,7 @@ function TryStep({
pending,
onOpenAccess,
onTest,
+ onSaveExit,
}: {
endpointId: string;
provider: ChatProvider;
@@ -1520,7 +1777,15 @@ function TryStep({
pending: boolean;
onOpenAccess: () => void;
onTest: () => void;
+ onSaveExit: () => void;
}) {
+ const messageStatus = useQuery({
+ queryKey: ["chat-endpoint-setup-test-status", endpointId],
+ queryFn: () => chatEndpointsApi.setupTestStatus(endpointId),
+ enabled: provider === "slack", refetchInterval: 1_500,
+ });
+ const [commandCopied, setCommandCopied] = useState(false);
+ const [commandCopyError, setCommandCopyError] = useState(false);
const principalsQuery = useQuery({
queryKey: queryKeys.chatEndpoints.principals(endpointId),
queryFn: () => chatEndpointsApi.listPrincipals(endpointId),
@@ -1540,7 +1805,7 @@ function TryStep({
: provider === "microsoft-teams"
? "start a new channel post and mention the agent again"
: "send a new root mention to the agent";
- const identityGuidance = provider === "imessage-photon" && principalsQuery.isSuccess && (identities.length === 0 || unlinkedIdentities.length > 0)
+ const identityGuidance = provider === "slack" ? null : provider === "imessage-photon" && principalsQuery.isSuccess && (identities.length === 0 || unlinkedIdentities.length > 0)
? { tone: "info" as const, title: "Link your Messages identity", body: "Send one message to discover your phone number or Apple account address, then link that exact identity in Access. Send a fresh request after linking; earlier messages do not start work." }
: principalsQuery.isError
? {
@@ -1589,6 +1854,7 @@ function TryStep({
const botMention = normalizedBotUsername
? `@${normalizedBotUsername}`
: (botLabel ?? agentName);
+ const slackTestMessage = `${botMention.startsWith("@") ? botMention : `@${botMention}`} you there?`;
const instructions =
provider === "imessage-photon" ? [
photonAllocation === "shared" ? "In your Photon project, enroll your sender in Users and find its assigned number in Get started. Send a fresh message to that number from Apple Messages." : `Open Apple Messages and send a fresh message to ${botUsername ?? botLabel ?? "the dedicated number"}.`,
@@ -1620,7 +1886,7 @@ function TryStep({
"Reply once beneath the post.",
]
: [
- "Open a channel and invite the bot if needed.",
+ `Open a channel and invite ${botMention} if needed.`,
`Mention ${botMention} in a new channel message.`,
`Reply once in ${agentName}'s thread.`,
];
@@ -1630,9 +1896,9 @@ function TryStep({
<h1 className="text-xl font-bold">
Try {agentName} in {providerNames[provider]}
</h1>
- <p className="mt-1 text-sm text-muted-foreground">
+ {provider !== "slack" && <p className="mt-1 text-sm text-muted-foreground">
Complete this real conversation to finish setup.
- </p>
+ </p>}
</div>
{(!principalsQuery.isSuccess || guestIsolationState === "loading") &&
!principalsQuery.isError ? (
@@ -1662,10 +1928,35 @@ function TryStep({
</div>
) : null}
{provider === "imessage-photon" && botUsername && <div className="space-y-2"><Button variant="outline" onClick={() => { void copyTextToClipboard(botUsername).then(() => { setNumberCopied(true); setCopyError(null); }, () => setCopyError("Could not copy the number. Select it in the instructions below.")); }}>{numberCopied ? "Number copied" : `Copy ${botUsername}`}</Button>{copyError && <p role="alert" className="text-sm text-destructive">{copyError}</p>}</div>}
+ {provider === "slack" ? (
+ <>
+ <ol className="list-decimal space-y-4 pl-5 text-sm">
+ <li>Open a channel and invite {botMention} if needed.</li>
+ <li>
+ <div className="flex flex-wrap items-center justify-between gap-3 rounded-lg border border-border p-3">
+ <code>{slackTestMessage}</code>
+ <Button size="sm" variant="ghost" onClick={() => {
+ void copyTextToClipboard(slackTestMessage).then(() => { setCommandCopied(true); setCommandCopyError(false); }, () => setCommandCopyError(true));
+ }}><Copy className="size-4" />{commandCopied ? "Copied" : "Copy message"}</Button>
+ </div>
+ <p className="mt-2 text-muted-foreground">Select the bot from Slack’s @mention suggestions.</p>
+ </li>
+ <li>Continue the conversation in the thread.</li>
+ </ol>
+ {commandCopyError && <p role="alert" className="text-sm text-destructive">Couldn&apos;t copy. Select and copy the command above.</p>}
+ {messageStatus.data?.messageReceivedAt ? <p role="status" className="flex items-center gap-2 text-sm"><CheckCircle2 className="size-4 text-(--status-task-done)" />Received your Slack message.</p>
+ : <p role={messageStatus.isError ? "alert" : "status"} className="text-sm text-muted-foreground">{messageStatus.isError ? "Couldn’t check for your message. You can still finish setup." : "We’ll check for your message automatically. This test is optional."}</p>}
+ <div className="flex items-center justify-between gap-3">
+ <Button variant="ghost" className="text-muted-foreground" onClick={onSaveExit}>Save &amp; exit</Button>
+ <div className="flex flex-wrap items-center justify-end gap-2">
+ <Button variant="ghost" disabled={pending} onClick={onTest}>Skip test and finish</Button>
+ <Button disabled={pending} onClick={onTest}>{pending && <Loader2 className="size-4 animate-spin" />}I&apos;ve sent the test message</Button>
+ </div>
+ </div>
+ </>
+ ) : <>
<ol className="list-decimal space-y-2 pl-5 text-sm">
- {instructions.map((item) => (
- <li key={item}>{item}</li>
- ))}
+ {instructions.map((item) => <li key={item}>{item}</li>)}
</ol>
<div className="flex flex-wrap gap-2">
{providerUrl && (
@@ -1680,6 +1971,7 @@ function TryStep({
I've sent the test message
</Button>
</div>
+ </>}
</div>
);
}
diff --git a/ui/src/pages/apps/chat/ChatIdentityConfirm.test.tsx b/ui/src/pages/apps/chat/ChatIdentityConfirm.test.tsx
new file mode 100644
index 0000000000..16cf724f24
--- /dev/null
+++ b/ui/src/pages/apps/chat/ChatIdentityConfirm.test.tsx
@@ -0,0 +1,72 @@
+// @vitest-environment jsdom
+import { flushSync } from "react-dom";
+import { createRoot, type Root } from "react-dom/client";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { ChatIdentityConfirm } from "./ChatIdentityConfirm";
+
+const mocks = vi.hoisted(() => ({
+ getSession: vi.fn(), previewIdentityLink: vi.fn(), confirmIdentityLink: vi.fn(),
+ requestIdentityAccess: vi.fn(), navigate: vi.fn(),
+}));
+vi.mock("@/api/chatEndpoints", () => ({ chatEndpointsApi: mocks }));
+vi.mock("@/api/auth", () => ({ authApi: { getSession: mocks.getSession } }));
+vi.mock("@/api/health", () => ({ healthApi: { get: async () => ({ deploymentMode: "authenticated" }) } }));
+vi.mock("@/lib/router", () => ({
+ useSearchParams: () => [new URLSearchParams({ token: "synthetic-token-that-is-at-least-32-characters" })],
+ Navigate: (props: { to: string }) => { mocks.navigate(props.to); return null; },
+}));
+
+describe("self-service Slack identity confirmation", () => {
+ let container: HTMLDivElement;
+ let root: Root;
+ let client: QueryClient;
+ const identity = { provider: "slack", externalLabel: "Dotta", companyName: "Acme", botLabel: "CEO", selfService: true, canConfirm: true };
+ beforeEach(() => {
+ vi.resetAllMocks();
+ mocks.getSession.mockResolvedValue({ user: { id: "user-a", name: "Dotta" } });
+ mocks.previewIdentityLink.mockResolvedValue(identity);
+ mocks.confirmIdentityLink.mockResolvedValue({ ok: true });
+ mocks.requestIdentityAccess.mockResolvedValue({ status: "pending_approval" });
+ container = document.createElement("div"); document.body.append(container);
+ root = createRoot(container);
+ client = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } });
+ });
+ afterEach(() => { flushSync(() => root.unmount()); client.clear(); container.remove(); });
+ const render = () => flushSync(() => root.render(<QueryClientProvider client={client}><ChatIdentityConfirm /></QueryClientProvider>));
+ const button = (text: string) => Array.from(container.querySelectorAll("button")).find((node) => node.textContent === text)!;
+
+ it("sends signed-out users to sign in with the confirmation route preserved", async () => {
+ mocks.getSession.mockResolvedValue(null); render();
+ await vi.waitFor(() => expect(mocks.navigate).toHaveBeenCalledWith(expect.stringContaining("/auth?next=%2Fchat-identity%2Fconfirm%3Ftoken%3D")));
+ expect(mocks.previewIdentityLink).not.toHaveBeenCalled();
+ });
+ it("requires an explicit identity confirmation from members", async () => {
+ render(); await vi.waitFor(() => expect(button("Confirm identity")).toBeTruthy());
+ expect(mocks.confirmIdentityLink).not.toHaveBeenCalled();
+ button("Confirm identity").click();
+ await vi.waitFor(() => expect(container.textContent).toContain("Identity linked"));
+ expect(container.textContent).toContain("current Paperclip permissions");
+ expect(container.querySelector('a')?.textContent).toBe("Return to Slack");
+ });
+ it("keeps other providers out of the Slack return flow", async () => {
+ mocks.previewIdentityLink.mockResolvedValue({ ...identity, provider: "github", selfService: false });
+ render(); await vi.waitFor(() => expect(button("Confirm identity")).toBeTruthy());
+ button("Confirm identity").click();
+ await vi.waitFor(() => expect(container.textContent).toContain("Identity linked"));
+ expect(container.querySelector('a[href="https://app.slack.com/"]')).toBeNull();
+ });
+ it("lets nonmembers request access without confirming the identity", async () => {
+ mocks.previewIdentityLink.mockResolvedValue({ ...identity, canConfirm: false });
+ render(); await vi.waitFor(() => expect(button("Request access")).toBeTruthy());
+ expect(button("Confirm identity")).toBeUndefined(); button("Request access").click();
+ await vi.waitFor(() => expect(container.textContent).toContain("Access requested"));
+ expect(mocks.confirmIdentityLink).not.toHaveBeenCalled();
+ expect(mocks.requestIdentityAccess).toHaveBeenCalledTimes(1);
+ });
+ it("does not allow requests using an expired or consumed link", async () => {
+ mocks.previewIdentityLink.mockRejectedValue(new Error("Expired")); render();
+ await vi.waitFor(() => expect(container.textContent).toContain("This identity link is unavailable"));
+ expect(container.querySelector("button")).toBeNull();
+ });
+});
diff --git a/ui/src/pages/apps/chat/ChatIdentityConfirm.tsx b/ui/src/pages/apps/chat/ChatIdentityConfirm.tsx
index f0f0d0a751..562d5d2d3f 100644
--- a/ui/src/pages/apps/chat/ChatIdentityConfirm.tsx
+++ b/ui/src/pages/apps/chat/ChatIdentityConfirm.tsx
@@ -2,10 +2,11 @@ import { useState } from "react";
import { useMutation, useQuery } from "@tanstack/react-query";
import { CheckCircle2, Loader2 } from "lucide-react";
import { chatEndpointsApi, type ChatProvider } from "@/api/chatEndpoints";
+import { healthApi } from "@/api/health";
import { authApi } from "@/api/auth";
import { Button } from "@/components/ui/button";
import { queryKeys } from "@/lib/queryKeys";
-import { Link, useSearchParams } from "@/lib/router";
+import { Navigate, useSearchParams } from "@/lib/router";
const providerNames: Record<ChatProvider, string> = {
slack: "Slack",
@@ -21,6 +22,8 @@ export function ChatIdentityConfirm() {
const [params] = useSearchParams();
const token = params.get("token") ?? "";
const [confirmed, setConfirmed] = useState(false);
+ const health = useQuery({ queryKey: queryKeys.health, queryFn: healthApi.get, retry: false });
+ const local = health.data?.deploymentMode === "local_trusted";
const session = useQuery({
queryKey: queryKeys.auth.session,
queryFn: () => authApi.getSession(),
@@ -29,7 +32,8 @@ export function ChatIdentityConfirm() {
const preview = useQuery({
queryKey: ["chat-identity-link-preview", token],
queryFn: () => chatEndpointsApi.previewIdentityLink(token),
- enabled: token.length >= 32,
+ enabled: token.length >= 32 && (local || Boolean(session.data)),
+ refetchInterval: confirmed ? false : 3_000,
retry: false,
});
const confirm = useMutation({
@@ -37,7 +41,14 @@ export function ChatIdentityConfirm() {
onSuccess: () => setConfirmed(true),
});
- if (token.length < 32 || preview.isError) {
+ const requestAccess = useMutation({
+ mutationFn: () => chatEndpointsApi.requestIdentityAccess(token),
+ });
+ if (health.isError || (!local && session.isError)) return <main className="mx-auto max-w-lg px-6 py-12 text-sm text-destructive">Couldn&apos;t load your account. Refresh to try again.</main>;
+ if (health.isSuccess && !local && session.isSuccess && !session.data) {
+ return <Navigate to={`/auth?next=${encodeURIComponent(`/chat-identity/confirm?token=${token}`)}`} replace />;
+ }
+ if (token.length < 32 || (!confirmed && preview.isError)) {
return (
<main className="mx-auto max-w-lg space-y-4 px-6 py-12">
<h1 className="text-xl font-bold">This identity link is unavailable</h1>
@@ -48,7 +59,7 @@ export function ChatIdentityConfirm() {
</main>
);
}
- if (preview.isLoading || session.isLoading || !preview.data) {
+ if (health.isPending || preview.isLoading || (!local && session.isLoading) || !preview.data) {
return (
<main className="flex items-center justify-center gap-2 px-6 py-12 text-sm text-muted-foreground">
<Loader2 className="h-4 w-4 animate-spin" />
@@ -57,7 +68,7 @@ export function ChatIdentityConfirm() {
);
}
const identity = preview.data;
- const paperclipAccount =
+ const paperclipAccount = local ? "Local Board" :
session.data?.user.name?.trim() ||
session.data?.user.email?.trim() ||
session.data?.user.id ||
@@ -73,13 +84,7 @@ export function ChatIdentityConfirm() {
Paperclip permissions in {identity.companyName}.
</p>
</div>
- <Button asChild>
- <Link
- to={`/${identity.companyPrefix}/apps/chat/${identity.endpointId}/access`}
- >
- Return to connection
- </Link>
- </Button>
+ {identity.provider === "slack" && <Button asChild><a href="https://app.slack.com/" target="_blank" rel="noopener noreferrer">Return to Slack</a></Button>}
</main>
);
}
@@ -124,10 +129,17 @@ export function ChatIdentityConfirm() {
This link could not be confirmed. It may have expired or been revoked.
</p>
)}
- <Button disabled={confirm.isPending} onClick={() => confirm.mutate()}>
+ {identity.canConfirm === false ? (
+ <div className="space-y-3">
+ <p className="text-sm">You need membership in {identity.companyName} before linking this account.</p>
+ {requestAccess.isSuccess ? <p role="status" className="text-sm">Access requested. An admin can approve it in Paperclip. After approval, return here to confirm; if this link expires, send the connect command in Slack again.</p>
+ : <Button disabled={requestAccess.isPending || !identity.selfService} onClick={() => requestAccess.mutate()}>Request access</Button>}
+ {requestAccess.isError && <p role="alert" className="text-sm text-destructive">Couldn&apos;t request access. The link may have expired. Send the connect command again and retry.</p>}
+ </div>
+ ) : <Button disabled={confirm.isPending} onClick={() => confirm.mutate()}>
{confirm.isPending && <Loader2 className="h-4 w-4 animate-spin" />}
Confirm identity
- </Button>
+ </Button>}
</main>
);
}
diff --git a/ui/src/pages/apps/chat/EmailEndpointSetup.tsx b/ui/src/pages/apps/chat/EmailEndpointSetup.tsx
index 432cc64d09..527d140313 100644
--- a/ui/src/pages/apps/chat/EmailEndpointSetup.tsx
+++ b/ui/src/pages/apps/chat/EmailEndpointSetup.tsx
@@ -1,3 +1,4 @@
+import { ChatSetupNavigation } from "@/components/chat/ChatSetupNavigation";
import { useEffect, useState } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import {
@@ -235,31 +236,13 @@ export function EmailEndpointSetup() {
{step === 6 ? "Close" : "Cancel"}
</Button>
</header>
- {step !== 6 && (
- <nav aria-label="Setup progress">
- <ol className="flex gap-4">
- {labels.map((label, i) => (
- <li
- className="flex flex-1 items-center gap-2 text-sm"
- key={label}
- >
- <span
- className={
- i <= current
- ? "flex size-7 shrink-0 items-center justify-center rounded-full bg-foreground text-background"
- : "flex size-7 shrink-0 items-center justify-center rounded-full border border-border text-muted-foreground"
- }
- >
- {i < current ? <Check className="size-4" /> : i + 1}
- </span>
- <span aria-current={i === current ? "step" : undefined}>
- {label}
- </span>
- </li>
- ))}
- </ol>
- </nav>
- )}
+ <ChatSetupNavigation
+ labels={labels}
+ step={current}
+ availableStep={current}
+ disabled={connect.isPending || setup.isPending || step === 2 || step === 6}
+ onSelect={(index) => setStep(step < 3 ? index : index + 3)}
+ />
{step === 0 && (
<AccessStep
companyId={companyId}
diff --git a/ui/src/pages/apps/chat/SlackIdentityStep.tsx b/ui/src/pages/apps/chat/SlackIdentityStep.tsx
new file mode 100644
index 0000000000..716e8c27e7
--- /dev/null
+++ b/ui/src/pages/apps/chat/SlackIdentityStep.tsx
@@ -0,0 +1,98 @@
+import { useState } from "react";
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import { CheckCircle2, Copy, ExternalLink, Loader2 } from "lucide-react";
+import { authApi } from "@/api/auth";
+import { healthApi } from "@/api/health";
+import { chatEndpointsApi } from "@/api/chatEndpoints";
+import { Button } from "@/components/ui/button";
+import { copyTextToClipboard } from "@/lib/clipboard";
+import { queryKeys } from "@/lib/queryKeys";
+
+export function SlackIdentityStep({ endpointId, command, testStartedAt, onConnected, onSaveExit }: {
+ endpointId: string;
+ command: string;
+ testStartedAt?: string | null;
+ onConnected: () => void;
+ onSaveExit: () => void;
+}) {
+ const client = useQueryClient();
+ const [copied, setCopied] = useState(false);
+ const [copyError, setCopyError] = useState(false);
+ const session = useQuery({ queryKey: queryKeys.auth.session, queryFn: authApi.getSession, retry: false });
+ const health = useQuery({ queryKey: queryKeys.health, queryFn: healthApi.get });
+ const identities = useQuery({
+ queryKey: queryKeys.chatEndpoints.principals(endpointId),
+ queryFn: () => chatEndpointsApi.listPrincipals(endpointId),
+ refetchInterval: 1_500,
+ });
+ const local = health.data?.deploymentMode === "local_trusted";
+ const userId = local ? "local-board" : session.data?.user.id;
+ const userLabel = local ? "Local Board" : session.data?.user.name || session.data?.user.email;
+ const candidates = (identities.data ?? []).filter((identity) => identity.lastConnectAt &&
+ (!testStartedAt || Date.parse(identity.lastConnectAt) >= Date.parse(testStartedAt)));
+ const linkedToMe = candidates.some((identity) => identity.status === "linked" && identity.paperclipUserId === userId);
+ const connectCommand = `${command} connect`;
+ const link = useMutation({
+ mutationFn: async (principalId: string) => {
+ const { confirmationUrl } = await chatEndpointsApi.createLinkIntent(endpointId, principalId);
+ const token = new URL(confirmationUrl, window.location.origin).searchParams.get("token");
+ if (!token) throw new Error("Could not create the account confirmation. Try again.");
+ await chatEndpointsApi.confirmIdentityLink(token);
+ },
+ onSuccess: () => client.invalidateQueries({ queryKey: queryKeys.chatEndpoints.principals(endpointId) }),
+ });
+
+ return (
+ <div className="space-y-5">
+ <div>
+ <h1 className="text-xl font-bold">Connect your Slack account</h1>
+ <p className="mt-1 text-sm text-muted-foreground">
+ Send this command in Slack so we can identify your account. It won&apos;t start agent work.
+ </p>
+ </div>
+ <div className="flex flex-wrap items-center justify-between gap-3 rounded-lg border border-border p-3">
+ <code className="text-sm">{connectCommand}</code>
+ <Button variant="ghost" size="sm" onClick={() => {
+ void copyTextToClipboard(connectCommand).then(() => { setCopied(true); setCopyError(false); }, () => setCopyError(true));
+ }}><Copy className="size-4" />{copied ? "Copied" : "Copy command"}</Button>
+ </div>
+ {copyError && <p role="alert" className="text-sm text-destructive">Couldn&apos;t copy the command. Select and copy it above.</p>}
+ <p className="text-sm">
+ <a href="https://app.slack.com/" target="_blank" rel="noopener noreferrer" className="underline underline-offset-4">Open Slack <ExternalLink className="inline size-3" /></a>, send the command in your workspace, then return here.
+ </p>
+ {identities.isError ? (
+ <p role="alert" className="text-sm text-destructive">Couldn&apos;t check for your Slack account. We&apos;ll keep trying.</p>
+ ) : candidates.length === 0 ? (
+ <p role="status" className="flex items-center gap-2 text-sm text-muted-foreground"><Loader2 className="size-4 animate-spin" />Waiting for your connect command…</p>
+ ) : (
+ <div className={`space-y-3 rounded-lg border p-4 ${linkedToMe
+ ? "border-(--status-task-done)/30 bg-(--status-task-done)/10"
+ : "border-(--status-task-todo)/30 bg-(--status-task-todo)/10"}`}>
+ <p className="text-sm">Choose your Slack account below to link it to <strong>{userLabel ?? "your Paperclip account"}</strong>. Only confirm an account that belongs to you. Future messages will use your Paperclip permissions.</p>
+ {candidates.map((identity) => {
+ const mine = identity.status === "linked" && identity.paperclipUserId === userId;
+ return (
+ <div key={identity.principalId} className="flex flex-wrap items-center justify-between gap-3 rounded-lg border border-border p-3">
+ <div className="min-w-0">
+ <p className="text-sm font-medium">{identity.externalLabel}</p>
+ <p className="text-xs text-muted-foreground">{identity.externalDetail}</p>
+ </div>
+ {mine ? <p role="status" className="flex items-center gap-2 text-sm"><CheckCircle2 className="size-4 text-(--status-task-done)" />Linked to you</p>
+ : identity.status === "linked" ? <p className="text-sm text-muted-foreground">Linked to {identity.paperclipUserLabel ?? "another Paperclip account"}</p>
+ : <Button variant="outline" disabled={!userId || link.isPending} onClick={() => link.mutate(identity.principalId)} aria-label={`Link ${identity.externalLabel} to my Paperclip account`}>
+ {link.isPending && link.variables === identity.principalId && <Loader2 className="size-4 animate-spin" />}This is my Slack account
+ </Button>}
+ </div>
+ );
+ })}
+ </div>
+ )}
+ {!userId && !session.isPending && !health.isPending && <p role="alert" className="text-sm text-destructive">Sign in to Paperclip to link your Slack account. Refresh this page after signing in.</p>}
+ {link.isError && <p role="alert" className="text-sm text-destructive">Couldn&apos;t link your account. Check that you are a member of this company and try again.</p>}
+ <div className="flex items-center justify-between gap-3">
+ <Button variant="ghost" className="text-muted-foreground" onClick={onSaveExit}>Save &amp; exit</Button>
+ {linkedToMe && <Button onClick={onConnected}>Continue to message test</Button>}
+ </div>
+ </div>
+ );
+}
diff --git a/ui/src/pages/apps/chat/chat-ui-contract.test.ts b/ui/src/pages/apps/chat/chat-ui-contract.test.ts
index e87f8b9f50..2a3e4e8264 100644
--- a/ui/src/pages/apps/chat/chat-ui-contract.test.ts
+++ b/ui/src/pages/apps/chat/chat-ui-contract.test.ts
@@ -154,7 +154,6 @@ describe("chat connector UI contract", () => {
const setup = source("./ChatEndpointSetup.tsx");
for (const credential of [
"botToken",
- "signingSecret",
"appId",
"applicationId",
"guildId",
@@ -165,7 +164,8 @@ describe("chat connector UI contract", () => {
expect(setup).toContain(`\"${credential}\"`);
}
expect(setup).toContain("credentials.privateKey");
- expect(setup).toContain("Bring your own Slack app");
+ expect(setup).toContain("credentials.signingSecret");
+ expect(setup).toContain("Create Slack app");
expect(setup).toContain("Create or connect a GitHub App");
expect(setup).toContain("create a single-tenant app registration");
expect(setup).toContain("Create a bot with BotFather");
@@ -246,7 +246,7 @@ describe("chat connector UI contract", () => {
expect(setup).toContain("Only on this account");
expect(setup).toContain('type="password"');
expect(setup).not.toContain("WebkitTextSecurity");
- expect(setup).toContain("Start Slack message test");
+ expect(setup).toContain("Verify Slack connection");
expect(setup).toContain("member_joined_channel");
expect(setup).toContain("member_left_channel");
expect(setup).toContain("channel_left");
@@ -255,8 +255,6 @@ describe("chat connector UI contract", () => {
expect(setup).toContain("group_unarchive");
expect(setup).toContain("group_rename");
expect(setup).toContain("app_uninstalled");
- expect(setup).toContain("Paperclip records Interactivity");
- expect(setup).toContain("command health only after each signed callback");
expect(setup).toContain("slackBotNameForAgent");
expect(setup).not.toContain("- im:write");
expect(setup).toContain("- reactions:write");