mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-29 23:56:43 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Slack connects a person to an agent through an installed app and a verified identity. > - Independent installations must remain usable without Paperclip Cloud or manager credentials. > - Approved Cloud deployments can use Slack manager grants to create and install each agent's app. > - Both paths should share credential storage, identity checks, recovery, and the existing runtime. > - This pull request adds gated managed setup and keeps independent app setup under Advanced. > - It also makes ongoing connection settings and personal test messages easier to use. ## Linked Issues or Issue Description **Subsystem affected** Slack setup, connection settings, tenant credential storage, and the Cloud connector handoff. **Problem or motivation** Approved deployments need an installation flow without pasted configuration tokens. Open-source users must retain their independent Slack app flow. A connection manager also needs a simple way to check a bot from Settings. **Proposed solution** Use the managed path when the instance is configured to support it. Choose agent and Connect are the two visible stops. Continue starts authorization or installation. Use your own app remains under Advanced before creation. Save personal manager grants by company, Paperclip user, Slack user, workspace, and manager app. Reuse only verified identities for test messages. Unknown identities must complete a private Slack connection challenge before linking and receiving the test DM. **Alternatives considered** A shared bot would change each agent's Slack identity. Requiring Slack CLI or a hosted service for self-hosted users would remove independent installation. **Roadmap alignment** This maintainer-requested change improves Connected Apps and experimental Agent Chat. It adds provisioning and management controls to the existing Slack runtime. **Additional context** The companion Cloud broker profile is a separate deployment prerequisite. Managed setup remains gated. Existing-app adoption is deferred. ## What Changed - Extract Slack registration, provider requests, completion, customer-owned setup, managed setup, and personal manager grants into focused services. Preserve the compatibility facade and independent removal cleanup. - Add company-scoped manager grants and a registration reference through an additive, idempotent migration after current master. Keep runtime credentials separate from app-registration secrets. - Add authenticated manager authorization, sealed handoff, serialized refresh and revocation, app creation, managed installation, and installer-bound OAuth fallback. - Preserve creation intent, block automatic uncertain recreation, save credentials before downstream checks, and validate app, workspace, bot, scopes, and installer identity. - Add the two-stop production wizard and ordered stories. Keep the own-app, manual, existing-app, and legacy-draft paths. - Simplify Settings. Open Slack configuration targets the saved app. The test-message action has its own row. Remove the old manual-avatar section, channel-message section, and broken permissions link. - Add paginated account discovery and a private connection challenge for unknown accounts. Expired invitations stop waiting and offer a new private invitation. Save send receipts before provider dispatch and preserve confirmed delivery when activity logging fails. - Reinstall the saved managed app on explicit reconnect, replace revoked credentials, and resume completion. Persist reconnect intent and duplicate-request receipts without creating another app. - Update provider browser tests, recovery tests, secret redaction, setup documentation, and the agent prompt. Preserve current master's durable verification scheduling. ## Verification - Full workspace typecheck and repository build passed on `56d389d47a`. The subsequent reconnect retry fix in `288364eada` also passed UI typecheck and UI build. - 114 focused Slack registration cases and 13 production managed-wizard cases passed, including fresh-token reconnect, retry after installation failure, and duplicate reconnect requests. - All nine affected Slack browser cases passed against the production UI and a disposable fixture server. They cover managed setup, automatic setup, own-app selection, refresh, recovery, mobile behavior, and connection settings. - Eight focused real-database test-message cases passed. They cover a private ownership challenge, saved grant reuse, account pagination, revoked and conflicting links, workspace mismatch, disabled DMs, revoked membership, audit failure, ambiguous dispatch, and secret canaries. - UI token gates and the production Storybook build passed. - Greptile reviewed exact head `288364eada5d9c114fad991ff634612639d06672` at 5/5 with no actionable findings or unresolved review threads. - The full repository test suite and current-head CI are running. Their final results will replace this line before merge. - Earlier live feature previews created two bots in the authorized Paperclip Slack workspace and reused one personal manager grant. Local managed Continue created and installed a bot without a configuration token or a separate Add to Slack action. Avatars, welcome DMs, signed callbacks, and direct replies were observed. A Settings test DM also arrived in the signed-in user's Slack account. - Earlier staging thread qualification required manual publication recovery for one bot. Current-head live qualification remains required before enabling the production default. Fixture results do not establish Slack approval behavior in other workspaces. ## Risks - Personal manager tokens can create apps. They stay in scoped vault entries. The manager client secret stays at the broker. Company, actor/session, origin, and app identity checks apply throughout setup. - The additive migration must also work on qualification instances that applied earlier branch migrations. Table, column, index, and constraint creation is idempotent. - Creation and message timeouts can leave uncertain outcomes. Saved request IDs prevent automatic duplicate dispatch. - Unknown Slack identities must receive and complete their private challenge while signed in. Account selection alone does not grant Paperclip permissions. Existing revoked or conflicting links are not overwritten. - A development-only manager transport uses an explicitly configured private credential file for local qualification. Production ignores this transport; no manager credentials are bundled with open source. - Managed rollout requires Slack approval, the companion broker deployment, configured secrets, and final live qualification. Removing a connection does not delete its Slack app. ## Model Used OpenAI Codex, GPT-6 family, with reasoning, code execution, and browser tools. The session does not expose the exact serving model ID or context-window size. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [ ] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing>
148 lines
9.7 KiB
TypeScript
148 lines
9.7 KiB
TypeScript
import { z } from "zod";
|
|
import { SLACK_BOT_TOOL_SCOPES } from "./slack-tools.js";
|
|
import type { SlackAppConfiguration } from "./types/chat-channels.js";
|
|
|
|
export const SLACK_CHAT_BOT_SCOPES = [
|
|
"app_mentions:read", "assistant:write", "channels:history", "channels:read",
|
|
"chat:write", "commands", "files:read", "files:write", "groups:history",
|
|
"groups:read", "im:history", "im:read", "mpim:history", "mpim:read",
|
|
"reactions:read", "reactions:write", "users:read",
|
|
] as const;
|
|
|
|
export function defaultSlackAppConfiguration(agentName: string): SlackAppConfiguration {
|
|
const botName = agentName.normalize("NFKD").toLowerCase()
|
|
.replace(/[^a-z0-9._-]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 24) || "paperclip-agent";
|
|
return { appName: `${botName}-paperclip`, botName, command: `/${botName.replace(/[._]+/g, "-")}` };
|
|
}
|
|
|
|
export function buildSlackAppManifest(input: {
|
|
app: SlackAppConfiguration;
|
|
agentName: string;
|
|
webhookUrl: string;
|
|
redirectUri?: string;
|
|
}) {
|
|
return {
|
|
display_information: { name: input.app.appName, description: `Talk to ${input.agentName} and manage work in Paperclip.`.slice(0, 140) },
|
|
features: {
|
|
app_home: { home_tab_enabled: false, messages_tab_enabled: true, messages_tab_read_only_enabled: false },
|
|
agent_view: { agent_description: "Work with a Paperclip agent in a task-backed conversation." },
|
|
bot_user: { display_name: input.app.botName },
|
|
slash_commands: [{ command: input.app.command, description: `Start or manage work with ${input.agentName}`,
|
|
usage_hint: "status | new | close | <task>", should_escape: false, url: input.webhookUrl }],
|
|
},
|
|
oauth_config: {
|
|
scopes: { bot: [...SLACK_CHAT_BOT_SCOPES, ...SLACK_BOT_TOOL_SCOPES] },
|
|
...(input.redirectUri ? { redirect_urls: [input.redirectUri] } : {}),
|
|
},
|
|
settings: {
|
|
org_deploy_enabled: false, socket_mode_enabled: false, token_rotation_enabled: false,
|
|
event_subscriptions: {
|
|
request_url: input.webhookUrl,
|
|
bot_events: ["agent_session_stopped", "app_mention", "message.channels", "message.groups", "message.im", "message.mpim",
|
|
"member_joined_channel", "member_left_channel", "channel_left", "group_left", "reaction_added", "reaction_removed",
|
|
"channel_archive", "group_archive", "channel_unarchive", "group_unarchive", "channel_deleted", "channel_rename",
|
|
"group_rename", "app_uninstalled", "tokens_revoked"],
|
|
},
|
|
interactivity: { is_enabled: true, request_url: input.webhookUrl },
|
|
},
|
|
};
|
|
}
|
|
|
|
export const slackRegistrationSchema = z.object({
|
|
requestId: z.string().uuid(),
|
|
credentials: z.object({ configurationToken: z.string().trim().min(1).max(4096) }).strict(),
|
|
confirmedNoAppCreated: z.boolean().optional(),
|
|
}).strict();
|
|
export type SlackRegistrationInput = z.infer<typeof slackRegistrationSchema>;
|
|
export const slackRegistrationStatusSchema = z.enum(["creating", "uncertain", "failed", "install", "credentials_saved", "configured", "removed"]);
|
|
export type SlackRegistrationStatus = z.infer<typeof slackRegistrationStatusSchema>;
|
|
export const slackRegistrationStateSchema = z.object({
|
|
status: slackRegistrationStatusSchema,
|
|
appId: z.string().nullable().optional(),
|
|
managementUrl: z.string().url().nullable().optional(),
|
|
managerGrantId: z.string().uuid().nullable().optional(),
|
|
errorCode: z.string().nullable().optional(),
|
|
}).strict();
|
|
export type SlackRegistrationState = z.infer<typeof slackRegistrationStateSchema>;
|
|
export const slackAvatarStateSchema = z.discriminatedUnion("status", [
|
|
z.object({ status: z.literal("pending") }).strict(),
|
|
z.object({ status: z.literal("uploaded"), uploadedAt: z.string().datetime() }).strict(),
|
|
z.object({ status: z.literal("failed"), errorCode: z.literal("slack_avatar_upload_failed") }).strict(),
|
|
]);
|
|
export type SlackAvatarState = z.infer<typeof slackAvatarStateSchema>;
|
|
export const slackAccountStateSchema = z.object({
|
|
externalUserId: z.string().regex(/^[UW][A-Z0-9]+$/),
|
|
paperclipUserId: z.string().min(1),
|
|
status: z.enum(["pending", "linked"]),
|
|
welcomeStatus: z.enum(["pending", "sending", "sent", "failed", "uncertain"]),
|
|
verificationStatus: z.enum(["pending", "sending", "sent", "failed", "uncertain"]).optional(),
|
|
dmChannelId: z.string().regex(/^D[A-Z0-9]+$/).optional(),
|
|
}).strict();
|
|
export type SlackAccountState = z.infer<typeof slackAccountStateSchema>;
|
|
export const slackInstallAuthorizationSchema = z.object({ authorizationUrl: z.string().url(), expiresAt: z.string().datetime() });
|
|
export const slackManagerAuthorizationSchema = slackInstallAuthorizationSchema.extend({ handoff: z.object({ kind: z.literal("paperclip_cloud"), session: z.string().min(16).max(512) }).optional() });
|
|
export type SlackManagerAuthorization = z.infer<typeof slackManagerAuthorizationSchema>;
|
|
export type SlackInstallAuthorization = z.infer<typeof slackInstallAuthorizationSchema>;
|
|
export const slackSetupActionSchema = z.object({}).strict();
|
|
|
|
export const slackTestMessageSchema = z.object({
|
|
requestId: z.string().uuid(),
|
|
slackUserId: z.string().regex(/^[UW][A-Z0-9]+$/).optional(),
|
|
accountCursor: z.string().min(1).max(512).optional(),
|
|
}).strict();
|
|
export type SlackTestMessageInput = z.infer<typeof slackTestMessageSchema>;
|
|
export const slackTestMessageResultSchema = z.discriminatedUnion("status", [
|
|
z.object({ status: z.literal("sent"), slackUrl: z.string().url() }).strict(),
|
|
z.object({ status: z.literal("connection_required"), accounts: z.array(z.object({
|
|
id: z.string(), name: z.string(),
|
|
}).strict()), nextCursor: z.string().nullable() }).strict(),
|
|
z.object({ status: z.literal("connection_pending"), principalId: z.string().uuid(), expiresAt: z.string().datetime() }).strict(),
|
|
]);
|
|
export type SlackTestMessageResult = z.infer<typeof slackTestMessageResultSchema>;
|
|
|
|
export function slackRegistrationErrorMessage(code: string): string {
|
|
const messages: Record<string, string> = {
|
|
slack_managed_unavailable: "Managed Slack setup is unavailable. Try again later or use your own app before creation starts.",
|
|
slack_manager_reauthorize: "Reconnect your Slack workspace to continue setting up this agent.",
|
|
slack_approval_pending: "Slack is waiting for your workspace administrator to approve this app.",
|
|
slack_approval_required: "Your Slack workspace requires approval. Continue in Slack to request it.",
|
|
slack_approval_denied: "Your Slack administrator declined this installation. Contact them to continue.",
|
|
slack_configuration_token_invalid: "Slack rejected the app configuration access token. Generate a new access token and try again.",
|
|
slack_manifest_invalid: "Slack rejected this app configuration. Check the app details or use manual setup.",
|
|
slack_manifest_update_pending: "Your Slack app is saved, but its event settings still need to be applied. Enter an app configuration access token to retry configuring the same app.",
|
|
slack_setup_rate_limited: "Slack is limiting setup requests. Wait a minute and try again.",
|
|
slack_setup_permission_denied: "Slack requires permission to create or install this app. Ask your workspace administrator.",
|
|
slack_creation_uncertain: "Slack may have created the app. Check your Slack app settings before trying again, or connect the existing app manually.",
|
|
slack_install_declined: "Installation was not approved. You can install the same app when you are ready.",
|
|
slack_install_expired: "Slack authorization expired. Install the same app again to continue.",
|
|
slack_install_failed: "Slack installation could not be completed. Authorize the same app again.",
|
|
slack_install_identity_mismatch: "Slack returned a different app, workspace, or bot. Install the app created for this connection.",
|
|
slack_install_scopes_missing: "Slack did not grant all required bot permissions. Install the app again and approve its requested permissions.",
|
|
slack_bot_already_connected: "This Slack bot is already connected to Paperclip. Resume its existing connection or use a different app.",
|
|
slack_install_token_invalid: "Slack rejected the saved bot credentials. Continue in Slack to authorize this app again.",
|
|
slack_configuration_incomplete: "The app is installed, but Paperclip could not finish connecting it. Retry connecting the saved installation.",
|
|
slack_install_account_missing: "Slack did not identify your account. Authorize the same app again to connect your Slack account.",
|
|
slack_install_account_conflict: "This Slack account already has an existing link. Manage account links in connection settings, or authorize with your own Slack account.",
|
|
};
|
|
return messages[code] ?? "Slack setup could not be completed. Resume setup and try again.";
|
|
}
|
|
|
|
/** Persisted legacy values keep their original meaning. Missing means manual. */
|
|
export type SlackSetupMethod = "managed" | "automatic" | "manual" | "existing";
|
|
export function isProvisionedSlackSetup(method: string | undefined): boolean {
|
|
return method === "automatic" || method === "managed";
|
|
}
|
|
export const SLACK_MANAGER_SCOPES = ["app_configurations:read", "app_configurations:write", "managed_apps:install"] as const;
|
|
export const slackSetupOptionsSchema = z.object({
|
|
managedAvailable: z.boolean(),
|
|
defaultMethod: z.enum(["managed", "automatic"]),
|
|
workspaces: z.array(z.object({ grantId: z.string().uuid(), workspaceId: z.string(), workspaceName: z.string(), userId: z.string() })),
|
|
});
|
|
export type SlackSetupOptions = z.infer<typeof slackSetupOptionsSchema>;
|
|
export const slackManagedProvisionSchema = z.object({
|
|
requestId: z.string().uuid(), grantId: z.string().uuid(), confirmedNoAppCreated: z.boolean().optional(), reconnect: z.boolean().optional(),
|
|
}).strict();
|
|
export type SlackManagedProvisionInput = z.infer<typeof slackManagedProvisionSchema>;
|
|
export const slackManagedResultSchema = z.object({ authorization: slackInstallAuthorizationSchema.optional() });
|
|
export type SlackManagedResult = z.infer<typeof slackManagedResultSchema>;
|