mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-02 02:30:43 +01:00
feat(chat): simplify Slack onboarding and account linking (#13638)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Chat connections let people start and continue that work from Slack. > - Setup mixed app creation, credentials, URL verification, account linking, and testing on the same screens. > - People also needed a safe way to link their own Slack identity after the first operator finished setup. > - This pull request gives each step a clear place and keeps membership approval separate from identity linking. > - It also makes connection details easier to use and fixes misleading callback health behind HTTPS proxies. ## Linked Issues or Issue Description **Subsystem affected** Cross-cutting: chat routes and services, shared contracts, and the Apps board UI. **Problem or motivation** Slack onboarding made users find settings without enough guidance. A second user needed operator help to link their account. Activity stopped at 100 records, and TLS termination could mark working callbacks as stale. **Proposed solution** Use six setup steps with editable app names, a generated manifest, credential guidance, URL verification, account linking, and an optional message test. Send each Slack user a private, expiring confirmation link. Require company membership or an approved access request before linking. Add cursor pagination and tolerate the internal HTTP hop in callback diagnostics. **Roadmap alignment** This improves the existing connected-app surface and supports CEO Chat without changing the task-and-comments model. The maintainer requested and reviewed the flow during a live Slack test drive. **Additional context** Related work: #7, #3349, #13000, and #13620. Those cover broader chat capabilities, older webhook paths, or plugins. This PR improves the existing native connector's setup and account-linking flow. HTTPS documentation was published separately in paperclipai/paperclip-docs#128. ## What Changed - Split Slack onboarding into six clickable sidebar steps. Keep secondary and primary actions on one row. - Generate the Slack creation link and read-only manifest from editable app, bot, and command names. Add credential prefix validation and direct instructions. - Add live account-link status and an optional mention-based message test. - Add private, single-use Slack account invitations and membership access requests. Retain cloud authentication/bootstrap checks and enforce the chat rollout flag in all identity APIs. Default new Slack connections to linked users only. - Put Settings, Access, Conversations, and Activity in the sidebar. Simplify conversation rows and remove active header badges. - Add 25-item activity pages, stable timestamp/ID cursors, and replay safety across pages. Preserve the legacy array API for clients without pagination parameters. - Fix false callback warnings when HTTPS terminates at a proxy. Keep host, port, and path drift detection. - Document the setup flow, pagination, callback diagnostics, and shared wizard footer rule. ## Verification - Passed: `pnpm -r typecheck`, `pnpm build`, and `pnpm check:token-gates`. - Passed: focused Slack callback and pagination integration tests; UI clipboard, wizard, pagination, and activity tests; OpenAPI route tests. The final access-gate fix also passes 27 focused tests covering cloud authentication/bootstrap, nonmember invitations, token validity, and the server-enforced rollout flag. - Passed: all 1,002 chat integration tests, 6,356 UI tests, and all 11 provider browser scenarios (including mobile light/dark navigation). After rebase, the identity route, sidebar, and 25 clipboard tests pass. - The full local `pnpm test:run` was attempted. The first run found 14 Slack fixtures that needed explicit guest access; those are fixed and the complete chat suite passes. Unrelated embedded PostgreSQL startup/resource failures and timeouts prevented a clean full local run. All CI checks pass on `2d858b036`, including the full chat, server, workspace, build, typecheck, and browser suites. - Live test drive: Slack app creation, credential setup, URL verification, private account confirmation, mention messages, and thread replies. Verified the callback warning clears for the existing proxied connection. - Review: create a Slack connection, follow the six steps, link a second user's account, and browse older activity with Next and Previous. ## Risks - Identity invitations carry a temporary capability. Tokens are hashed, expire after 15 minutes, work once, and require explicit confirmation by a company member. Access requests do not grant membership. - New Slack connections reject unlinked people by default. Existing connection settings remain intact. - Activity is a live ledger. Updated action rows can move forward in time. Older pages do not poll. - Proxy tolerance affects health display only. Slack signature checks and proxy authentication settings remain unchanged. - No database migration or package-lock changes. ## Model Used OpenAI Codex, based on GPT-6, with reasoning, repository tools, code execution, and browser verification. The runtime does not expose an exact model build 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 - [x] I have run tests locally and they pass (targeted suites; full local-run limitations documented above) - [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 - [x] 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>
This commit is contained in:
1 parent
4b8dc416da
commit
924f07be8c
36 files changed
+2364
-688
No files matched your search
+36
-2
@@ -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" },
|
||||
|
||||
+4
-4
@@ -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 />} />
|
||||
|
||||
@@ -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`,
|
||||
|
||||
@@ -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">
|
||||
|
||||
@@ -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({
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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 &&
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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()); }
|
||||
});
|
||||
});
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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)}
|
||||
/>
|
||||
)}
|
||||
|
||||
@@ -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");
|
||||
|
||||
@@ -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'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)}
|
||||
|
||||
@@ -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 & 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 & 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'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'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't check verification. We'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'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 & 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">
|
||||
<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>
|
||||
</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 & 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>
|
||||
<div className="flex items-center justify-between gap-4">
|
||||
<span className="text-muted-foreground">Slash command</span>
|
||||
<code>{slackCommand}</code>
|
||||
</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.
|
||||
</p>
|
||||
<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>
|
||||
)}
|
||||
<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>
|
||||
<div>
|
||||
<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>
|
||||
<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'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 flex-wrap items-center justify-between gap-3 pt-3">
|
||||
<Button variant="ghost" className="text-muted-foreground" onClick={() => navigate("/apps")}>
|
||||
Save & 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>
|
||||
<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>
|
||||
{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 & 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 & 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 & 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'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 & 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'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>
|
||||
);
|
||||
}
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
@@ -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'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'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>
|
||||
);
|
||||
}
|
||||
@@ -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}
|
||||
|
||||
@@ -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'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'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't check for your Slack account. We'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'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 & exit</Button>
|
||||
{linkedToMe && <Button onClick={onConnected}>Continue to message test</Button>}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -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");
|
||||
|
||||
Reference in new issue
Block a user