fix(ui): show Slack workspace reconnect on saved setup errors (#18837)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Slack setup connects a saved agent draft to a workspace.
> - Workspace authorization can fail before the agent's Slack app
exists.
> - The error requested reconnection while its primary action said
Continue.
> - Older grants could also make retry provision instead of reopening
authorization.
> - This change names the recovery action and keeps it on the
authorization path.
> - People can reconnect from the same setup page and resume the saved
agent.

## Linked Issues or Issue Description

Refs: #18722.

**What happened?** A managed Slack draft showed “Reconnect your Slack
workspace to continue setting up this agent.” Its primary action was
Continue. The reconnect label depended on a registration that might not
exist, and a saved error or failed explicit authorization could be
ignored when an older grant remained available.

**Expected behavior:** Offer one enabled Reconnect Slack workspace
action that opens ordinary Slack authorization and resumes the saved
setup.

**Steps to reproduce:** Resume a managed Slack draft before app creation
with a saved manager reauthorization error, or fail an explicit
workspace authorization request. Inspect the recovery action with zero,
one or multiple older workspace grants.

## What Changed

- Show Reconnect Slack workspace for saved and local authorization
failures before app creation and for existing-app recovery.
- Honor the saved manager error and retain explicit authorization
intent, so retry authorizes rather than provisioning with an older
grant.
- Hide irrelevant workspace controls during recovery and allow
authorization before choosing an old grant. Use one recovery action.
- Cover zero, one and two older grants in component regressions. Update
the existing browser test to use the explicit action; add
production-wizard desktop/mobile recovery previews and provider
guidance.

The Slack provider UI owns this change. It uses the existing
authorization endpoint and shared footer; API contracts and provider
permissions are unchanged. Maps are unchanged.

## Verification

- Final head: `02234bd1afc61d404841a9fc2b7e457b0dc021bf`. Full CI
[41715544834](https://github.com/paperclipai/paperclip/actions/runs/41715544834)
passed on attempt 2, including all browser, server/chat, Runner,
typecheck, build, policy and canary checks. Greptile and Ponytail both
give this exact head 5/5; all review threads are resolved.
- All 20 managed setup tests and 276 related chat UI tests across 19
files passed. All 9 Slack provider browser cases passed on the final
source in 1.3 minutes using Node 24.22.2 and unchanged Playwright
configuration. Provider responses are mocked in those cases.
- Full repository typecheck and build passed earlier; final UI
typecheck/build, token gates and Storybook catalog checks passed after
the source refinement. All 30 map/catalog Node checks passed.
Catalog/map checks are structural. The full local server Vitest suite
was not repeated for this UI-only change; full CI covered it.
- Production-wizard browser previews covered saved recovery on desktop
and at 320 × 568, older grants, and failed explicit authorization. On
the final source, the visible retry with older grants returned to an
error-free workspace chooser, where Continue requires a choice.
Selecting a workspace and continuing was also exercised through the
message step during the preceding refinement. All provider actions in
these previews are simulated.
- The existing recovery path was independently exercised live in staging
through ordinary controls: Continue → Slack Allow → Success → Open Slack
→ real agent DM reply → Done → full reload. The new action label still
needs deployed acceptance. No live grant was revoked or duplicate bot
created to force the error.

Failures retained through acceptance:

- New regressions failed on the earlier sources for missing recovery
labels, ignored saved errors with active grants, a duplicate action,
disabled multi-workspace recovery, and lost explicit authorization
intent. The final tests require enabled recovery, authorization
navigation and no provisioning on that action.
- The first preview assertion raced workspace-options loading; it now
waits for the same enabled condition. A later multi-workspace return
assertion incorrectly expected the message step; it now checks the
required workspace choice and disabled Continue before selection. The
fixture's authorization flag is reset by a normal full reload. An
unsupported Testing Library `exact` option was caught by typecheck and
replaced with an anchored name regex. Failure screenshots remain
preserved.
- Earlier CI
[41707550300](https://github.com/paperclipai/paperclip/actions/runs/41707550300)
found the existing browser test still clicking Continue and an npm
canary-version collision. The locator was updated without removing
authorization-count/redirect assertions; subsequent packaging checks
passed. CI
[41709833527](https://github.com/paperclipai/paperclip/actions/runs/41709833527)
had runner shutdown/lost-communication interruptions; those earlier
successes were not used to qualify the final head.
- Final-head attempt 1 had a native Runner shutdown while unpacking its
cache, plus a distinct Cursor Cloud Stop assertion failure in the
package lane (4890 passed, 10 skipped). The Cursor Cloud case passed
unchanged in isolation, with its source subtree matching the CI merge
tree; the CI cause is not established. Both full Runner lanes then
passed on retry of the same reviewed commit, with successful checks
retained.
- One local browser invocation timed out during server startup on Node
26 before assertions. The first Node 24 wrapper invocation failed a
nested-npx package selector before assertions. Direct Playwright
execution with that wrapper variable cleared and unchanged timeouts
passed the final 9-case suite.
- Greptile flagged a routine regression paragraph outside feature-map
scope; it was removed. Ponytail then found the active-grant mismatch; it
was reproduced and fixed at the authorization decision. Both reviewers
now report 5/5.

## Risks

Saved reauthorization errors and retries of explicit authorization
requests now reopen existing Slack consent even when older grants
remain. Provider availability or browser consent can still prevent
reconnection. This change does not establish why the original workspace
grant became unusable; simulated previews are not live Slack proof.

## Model Used

OpenAI Codex, GPT-6 family, with reasoning, repository editing, browser
use and command execution. The runtime does not expose a more precise
model ID or context-window size.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [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:
DottaandPaperclip authored and GitHub committed 2026-11-03 15:16:53 -06:00
1 parent f7fae6b738
commit ff80845756
6 files changed
+91 -8

No files matched your search

+3
View File
@@ -78,6 +78,9 @@ Provider-side app removal remains explicit through the saved Slack management UR
permissions therefore pass through installation again before activation.
- Expired or revoked manager grants require reconnection. Losing managed
availability pauses setup; it never changes the saved ownership method.
A saved draft that needs workspace reauthorization shows **Reconnect Slack
workspace** on Connect, even before its app has been created. This button
opens Slack authorization and returns to the same saved agent setup.
- Slack rate limits are grouped by manager/workspace/method. Provider `Retry-After`
is persisted across matching grants in the company, survives restarts, and blocks
early retries. Other tenant instances must observe Slack's limits independently;
+1 -1
View File
@@ -208,7 +208,7 @@ test.describe.serial("native chat adapter UI", () => {
await page.route("https://slack.test/manager-consent", route => route.fulfill({ contentType: "text/html", body: "Slack authorization fixture" }));
await page.goto(`/${seed.prefix}/apps/chat/connect?provider=slack&purpose=chat&resume=endpoint-slack`);
await expect(page.getByRole("alert")).toBeVisible();
await page.getByRole("button", { name: "Continue", exact: true }).click();
await page.getByRole("button", { name: "Reconnect Slack workspace", exact: true }).click();
await expect.poll(() => authorizationRequests).toBe(1);
await expect(page).toHaveURL("https://slack.test/manager-consent");
});
@@ -63,6 +63,47 @@ it("opens manager authorization directly when there is no saved workspace", asyn
expect(navigation).toHaveBeenCalledWith({ authorizationUrl: "https://slack.com/oauth" });
expect(api.provisionManagedSlack).not.toHaveBeenCalled();
});
it.each([0, 1, 2])("offers workspace reconnection before an app exists with %i active workspaces", async (activeWorkspaces) => {
endpoint.setup!.slackManagerError = "slack_manager_reauthorize";
api.slackSetupOptions.mockResolvedValue({ managedAvailable: true, workspaces: Array.from({ length: activeWorkspaces }, (_, i) => ({ grantId: `grant-${i}`, workspaceName: `Workspace ${i}` })) });
await render();
expect(container.querySelector('[role="alert"]')?.textContent).toBe("Reconnect your Slack workspace to continue setting up this agent.");
const reconnect = Array.from(container.querySelectorAll("button")).find(item => item.textContent === "Reconnect Slack workspace");
expect(reconnect).toBeDefined();
expect(reconnect!.disabled).toBe(false);
expect(container.textContent).not.toContain("Connect another Slack workspace");
expect(api.authorizeSlackManager).not.toHaveBeenCalled();
await act(async () => reconnect!.click());
expect(api.authorizeSlackManager).toHaveBeenCalledExactlyOnceWith("endpoint");
expect(navigation).toHaveBeenCalledWith({ authorizationUrl: "https://slack.com/oauth" });
expect(api.provisionManagedSlack).not.toHaveBeenCalled();
});
it.each([0, 1, 2])("offers workspace reconnection after an authorization request fails with %i active workspaces", async (activeWorkspaces) => {
api.slackSetupOptions.mockResolvedValue({ managedAvailable: true, workspaces: Array.from({ length: activeWorkspaces }, (_, i) => ({ grantId: `grant-${i}`, workspaceName: `Workspace ${i}` })) });
api.authorizeSlackManager.mockRejectedValueOnce(new Error("Reconnect your Slack workspace to continue setting up this agent."));
await render({ autoStart: activeWorkspaces === 0 });
if (activeWorkspaces) {
const connectAnother = Array.from(container.querySelectorAll("button")).find(item => item.textContent === "Connect another Slack workspace");
await act(async () => connectAnother!.click());
}
const reconnect = Array.from(container.querySelectorAll("button")).find(item => item.textContent === "Reconnect Slack workspace");
expect(reconnect).toBeDefined();
expect(reconnect!.disabled).toBe(false);
expect(api.authorizeSlackManager).toHaveBeenCalledTimes(1);
await act(async () => reconnect!.click());
expect(api.authorizeSlackManager).toHaveBeenCalledTimes(2);
expect(navigation).toHaveBeenCalledWith({ authorizationUrl: "https://slack.com/oauth" });
expect(api.provisionManagedSlack).not.toHaveBeenCalled();
});
it("keeps one workspace reconnect action when a saved app needs reauthorization", async () => {
endpoint.setup!.slackRegistration = { status: "failed", appId: "app", managerGrantId: "grant", errorCode: "slack_manager_reauthorize" } as NonNullable<ChatEndpoint["setup"]>["slackRegistration"];
await render();
const reconnect = Array.from(container.querySelectorAll("button")).filter(item => item.textContent === "Reconnect Slack workspace");
expect(reconnect).toHaveLength(1);
await act(async () => reconnect[0]!.click());
expect(api.authorizeSlackManager).toHaveBeenCalledExactlyOnceWith("endpoint");
expect(api.provisionManagedSlack).not.toHaveBeenCalled();
});
it("does not start while Choose agent is visible or after Save & exit", async () => {
await render({ autoStart: false });
expect(api.provisionManagedSlack).not.toHaveBeenCalled();
@@ -16,6 +16,7 @@ export function ManagedSlackSetup({ endpoint, disabled, saveDetails, onSaved, on
const [selectedGrant, setSelectedGrant] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const [authorizationRequested, setAuthorizationRequested] = useState(false);
const [confirmed, setConfirmed] = useState(false);
const inFlight = useRef(false);
const requestId = useRef(crypto.randomUUID());
@@ -23,7 +24,8 @@ export function ManagedSlackSetup({ endpoint, disabled, saveDetails, onSaved, on
const started = Boolean(registration);
const workspaces = choices.data?.workspaces ?? [];
const grantId = registration?.managerGrantId ?? selectedGrant ?? (workspaces.length === 1 ? workspaces[0]!.grantId : null);
const needsAuthorization = !grantId || registration?.errorCode === "slack_manager_reauthorize" || Boolean(grantId && !workspaces.some(workspace => workspace.grantId === grantId));
const needsAuthorization = authorizationRequested || !grantId || endpoint.setup?.slackManagerError === "slack_manager_reauthorize" || registration?.errorCode === "slack_manager_reauthorize" || Boolean(grantId && !workspaces.some(workspace => workspace.grantId === grantId));
const reconnectWorkspace = needsAuthorization && (started || Boolean(error) || endpoint.setup?.slackManagerError === "slack_manager_reauthorize");
const uncertain = registration?.status === "uncertain";
const creating = registration?.status === "creating";
async function run(action: () => Promise<void>) {
@@ -34,6 +36,7 @@ export function ManagedSlackSetup({ endpoint, disabled, saveDetails, onSaved, on
finally { inFlight.current = false; setBusy(false); onBusy(false); }
}
async function authorize() {
setAuthorizationRequested(true);
const authorization = await chatEndpointsApi.authorizeSlackManager(endpoint.id);
const target = await prepareOAuthNavigation(authorization);
if (target.kind === "reauthentication" && authorization.handoff) savePendingCloudHandoff(authorization.handoff.session);
@@ -71,21 +74,21 @@ export function ManagedSlackSetup({ endpoint, disabled, saveDetails, onSaved, on
{message && <p role="alert" className="text-sm text-destructive">{message}</p>}
{busy || choices.isPending || creating ? <p role="status" className="flex items-center gap-2 text-sm text-muted-foreground"><Loader2 className="size-4 animate-spin" />{busy ? needsAuthorization ? "Opening Slack…" : "Connecting your agent…" : creating ? "Setting up your Slack app…" : "Loading Slack…"}</p>
: !choices.data?.managedAvailable ? <p className="text-sm">Managed Slack setup is unavailable. Try again later.</p>
: <>
: reconnectWorkspace ? null : <>
{workspaces.length === 1 && <p className="text-sm">Add <strong>{endpoint.assignedAgentName}</strong> to <strong>{workspaces[0]!.workspaceName}</strong>.</p>}
{workspaces.length > 1 && <Select value={grantId ?? ""} onValueChange={setSelectedGrant} disabled={busy || started}>
<SelectTrigger aria-label="Slack workspace"><SelectValue placeholder="Choose a Slack workspace" /></SelectTrigger>
<SelectContent>{workspaces.map(workspace => <SelectItem key={workspace.grantId} value={workspace.grantId}>{workspace.workspaceName}</SelectItem>)}</SelectContent>
</Select>}
{(!started || registration?.errorCode === "slack_manager_reauthorize") && workspaces.length > 0 && <div><Button variant="link" className="h-auto p-0" disabled={busy} onClick={() => void run(authorize)}>{started ? "Reconnect Slack workspace" : "Connect another Slack workspace"}</Button></div>}
{!started && workspaces.length > 0 && <div><Button variant="link" className="h-auto p-0" disabled={busy} onClick={() => void run(authorize)}>Connect another Slack workspace</Button></div>}
</>}
{uncertain && <div className="space-y-3 text-sm">
<a className="underline underline-offset-4" href={registration?.managementUrl ?? "https://api.slack.com/apps"} target="_blank" rel="noopener noreferrer">Open Slack app settings</a>
<label className="flex items-center gap-2"><Checkbox checked={confirmed} onCheckedChange={value => setConfirmed(value === true)} disabled={busy} />I checked Slack and no app was created. Create a new app.</label>
</div>}
<SetupWizardFooter onSaveExit={onSaveExit} disabled={busy}>
{choices.isError || !choices.isPending && !choices.data?.managedAvailable ? <Button disabled={busy || choices.isFetching} onClick={() => void choices.refetch()}>Retry</Button> : <Button disabled={busy || disabled || creating || choices.isPending || !choices.data?.managedAvailable || (workspaces.length > 1 && !grantId) || (uncertain && !confirmed)} onClick={() => void run(connect)}>
{busy && <Loader2 className="size-4 animate-spin" />}{needsAuthorization && started ? "Reconnect Slack" : registration?.appId ? "Continue in Slack" : "Continue"}
{choices.isError || !choices.isPending && !choices.data?.managedAvailable ? <Button disabled={busy || choices.isFetching} onClick={() => void choices.refetch()}>Retry</Button> : <Button disabled={busy || disabled || creating || choices.isPending || !choices.data?.managedAvailable || (workspaces.length > 1 && !grantId && !reconnectWorkspace) || (uncertain && !confirmed)} onClick={() => void run(connect)}>
{busy && <Loader2 className="size-4 animate-spin" />}{reconnectWorkspace ? "Reconnect Slack workspace" : registration?.appId ? "Continue in Slack" : "Continue"}
</Button>}
</SetupWizardFooter>
</div>;
+9 -2
View File
@@ -7,7 +7,7 @@ import { type ChatEndpoint } from "@/api/chatEndpoints";
import { storybookAgents, storybookAuthSession } from "./paperclipData";
import { defaultSlackAppConfiguration } from "@paperclipai/shared";
export type SlackSetupScenario = "choose" | "create" | "manual" | "install" | "declined" | "approval_denied" | "uncertain" | "manifest_pending" | "recovery" | "verify" | "avatar_failed" | "welcome_failed" | "success";
export type SlackSetupScenario = "choose" | "create" | "manual" | "install" | "declined" | "approval_denied" | "manager_reauthorize" | "manager_authorization_failed" | "uncertain" | "manifest_pending" | "recovery" | "verify" | "avatar_failed" | "welcome_failed" | "success";
/** Production wizard over a local provider fixture. No requests go to Slack. */
export function SlackSetupFixture({ scenario = "create", managed = false, managedAvailable = true, workspaceCount = 1, optionsDelayMs = 0, optionsError = false }: { scenario?: SlackSetupScenario; managed?: boolean; managedAvailable?: boolean; workspaceCount?: number; optionsDelayMs?: number; optionsError?: boolean }) {
@@ -27,7 +27,10 @@ export function SlackSetupFixture({ scenario = "create", managed = false, manage
},
};
const grantId = "11111111-1111-4111-8111-111111111111";
let authorized = workspaceCount > 0 || new URLSearchParams(window.location.search).get("slackFixtureAuthorized") === "1";
const authorizationReturned = new URLSearchParams(window.location.search).get("slackFixtureAuthorized") === "1";
let authorized = workspaceCount > 0 || authorizationReturned;
let authorizationFailed = false;
if (scenario === "manager_reauthorize" && !authorizationReturned) endpoint.setup!.slackManagerError = "slack_manager_reauthorize";
const created = () => {
endpoint.setup!.slackRegistration = { status: "install", ...(managed ? { managerGrantId: grantId } : {}), appId: "ASTORY", managementUrl: "https://api.slack.com/apps/ASTORY" };
endpoint.setup!.slackAvatar = scenario === "avatar_failed" ? { status: "failed", errorCode: "slack_avatar_upload_failed" } : { status: "uploaded", uploadedAt: new Date().toISOString() };
@@ -61,6 +64,10 @@ export function SlackSetupFixture({ scenario = "create", managed = false, manage
return Response.json({ managedAvailable: managed && managedAvailable, defaultMethod: managed ? "managed" : "automatic", workspaces: managed && authorized ? Array.from({ length: Math.max(1, workspaceCount) }, (_, i) => ({ grantId: i ? "22222222-2222-4222-8222-222222222222" : grantId, workspaceId: `TSTORY${i}`, workspaceName: i ? "Research workspace" : "Paperclip", userId: "UPERSON" })) : [] });
}
if (path === "/api/chat-endpoints/slack-story/slack/managed/authorize") {
if (scenario === "manager_authorization_failed" && !authorizationReturned && !authorizationFailed) {
authorizationFailed = true;
return Response.json({ error: "Reconnect your Slack workspace to continue setting up this agent." }, { status: 422 });
}
authorized = true;
const returnUrl = new URL(window.location.href);
returnUrl.hash = "";
@@ -63,6 +63,35 @@ export const Success: Story = { name: "02 · Connect · Success", args: { scenar
} };
export const ApprovalPending: Story = { name: "Recovery · Slack approval pending", args: { scenario: "declined" } };
export const ApprovalDeclined: Story = { name: "Recovery · Slack approval declined", args: { scenario: "approval_denied" } };
export const WorkspaceReconnect: Story = {
name: "Recovery · Reconnect workspace before app creation",
args: { scenario: "manager_reauthorize", workspaceCount: 0 },
play: async ({ canvasElement, args }) => {
const canvas = within(canvasElement);
if (new URLSearchParams(window.location.search).get("slackFixtureAuthorized") === "1") {
if ((args.workspaceCount ?? 1) > 1) {
await expect(await canvas.findByRole("combobox", { name: "Slack workspace" })).toBeVisible();
await expect(canvas.queryByRole("alert")).not.toBeInTheDocument();
await expect(canvas.getByRole("button", { name: /^Continue$/ })).toBeDisabled();
return;
}
await expect(await canvas.findByRole("heading", { name: "Send a message to your agent" })).toBeVisible();
return;
}
if (args.scenario === "manager_authorization_failed" && (args.workspaceCount ?? 0) > 1 && !canvas.queryByRole("alert")) {
await userEvent.click(await canvas.findByRole("button", { name: "Connect another Slack workspace" }));
}
await expect(await canvas.findByRole("alert")).toHaveTextContent("Reconnect your Slack workspace to continue setting up this agent.");
await waitFor(() => expect(canvas.getByRole("button", { name: "Reconnect Slack workspace" })).toBeEnabled());
await expect(canvas.getByRole("button", { name: "Save & exit" })).toBeVisible();
await expect(canvas.queryByRole("button", { name: "Continue" })).not.toBeInTheDocument();
await expect(canvas.queryByRole("button", { name: "Connect another Slack workspace" })).not.toBeInTheDocument();
},
};
export const MobileWorkspaceReconnect: Story = { ...WorkspaceReconnect, name: "Mobile · Reconnect workspace", globals: { viewport: { value: "mobile1", isRotated: false } } };
export const WorkspaceReconnectWithSavedGrant: Story = { ...WorkspaceReconnect, name: "Recovery · Reconnect with older workspace grants", args: { scenario: "manager_reauthorize", workspaceCount: 2 } };
export const WorkspaceAuthorizationFailed: Story = { ...WorkspaceReconnect, name: "Recovery · Workspace authorization request failed", args: { scenario: "manager_authorization_failed", workspaceCount: 0 } };
export const WorkspaceAuthorizationFailedWithSavedGrants: Story = { ...WorkspaceReconnect, name: "Recovery · Workspace authorization failed with older grants", args: { scenario: "manager_authorization_failed", workspaceCount: 2 } };
export const EventConfigurationPending: Story = { name: "Recovery · App configuration pending", args: { scenario: "manifest_pending" } };
export const UncertainCreation: Story = { name: "Recovery · Uncertain creation", args: { scenario: "uncertain" } };
export const SavedCredentials: Story = { name: "Recovery · Saved credentials", args: { scenario: "recovery" } };