Files
paperclip/doc/connections/SLACK-AUTOMATIC-SETUP.md
DottaandPaperclip 2e52dfa864 fix(slack): retain DM thread tasks after completion (#19486)
## Thinking Path

> - Paperclip manages AI agents and their work.
> - Slack conversations store that work in tasks and comments.
> - A native thread must keep its task when work finishes.
> - The server treated all DMs as linear conversations.
> - A reply in a completed DM thread therefore started a new task
without its earlier comments.
> - This pull request uses the native thread identity for task
continuity.
> - People can continue the same work with its saved context.

## Linked Issues or Issue Description

**What happened?**

A reply in a Slack DM thread created a new task after the preceding task
was Done or Cancelled. It also created a new task when the saved
conversation was completed. The new task lacked earlier comments.

**Expected behavior**

A native Slack thread keeps one task in channels and DMs. Later replies
retain earlier user and agent comments. Top-level DMs keep their
existing task generation rules.

**Steps to reproduce**

1. Start work in a Slack DM thread.
2. Mark its task Done.
3. Reply in the same thread.
4. Before this fix, the reply creates another task.

**Paperclip version or commit**

Reproduced from master at eb5c24b61c.

**Deployment mode**

Built from source. Tests use local PostgreSQL and provider fixtures.

Related PR: #16151 covers the DM mention exemption. This fix preserves
that behavior. GitHub searches found no duplicate fix for completion
routing.

## What Changed

- Detect Slack native thread roots in the Slack module.
- Classify native DM threads as persistent threads for task routing.
- Select the resource type from the actual DM destination. Keep DM
access checks.
- Preserve DM task controls. Select the latest DM task even after
completion. Require a delivered control receipt before an explicit new
task generation.
- Add completion, duplicate, saved-history, separate-root, Idle, and
explicit-control regressions.
- Document the task boundary. Correct only the inaccurate DM-thread
statement in the existing feature recipe.

## Verification

- Before the production edit, the new PostgreSQL regression failed in
all three threaded-DM completion cases: two conversations existed
instead of one. The channel-thread and top-level-DM controls passed.
- The initial eight routing cases passed. CI then found five existing
slash-control failures. All five reproduced locally. Greptile reported
the same regression at 4/5.
- The first correction passed all 16 focused PostgreSQL cases. Secondary
review then found that slash commands skipped Done, Cancelled, and
completed DM tasks. Four new cases failed before the lookup change.
Commit 23ff4f04f passed all 20 focused cases, including status, explicit
new/close, delivered receipts, and a new task generation. The original
same-thread continuity cases still pass.
- Command: `pnpm exec vitest run
server/src/__tests__/chat-channels.integration.test.ts -t 'preserves
Slack thread history across completion|keeps separate Slack DM thread
roots|returns two answered Slack turns to Idle|binds Slack DM slash
controls|treats D-prefixed Slack status|serializes duplicate Slack
admission with an owned provider-reply settlement|suppresses a queued
provider reply when destination reach|continues to accept authenticated
Slack slash close/new'`.
- Map validation and `git diff --check` passed. Map validation proves
structure only.
- All 107 neighboring Slack adapter, SDK runtime, and receipt tests
passed across three files.
- The initial complete server typecheck passed with
`PAPERCLIP_TYPECHECK_LOW_MEMORY=1 pnpm --filter @paperclipai/server
typecheck`, including all three test-tree shards.
- Full local recursive typecheck and build stopped because this
workspace has no `cargo`. A separate default server typecheck was killed
under concurrent memory load; its lower-memory rerun passed. The broad
local test run was interrupted to free memory, so no full-local-suite
pass is claimed. The complete server typecheck passed again for
correction 367b6f9b3, including all three test-tree shards. The [full CI
pipeline](https://github.com/paperclipai/paperclip/actions/runs/42250458200)
passed for exact head 367b6f9b3f. This
includes typecheck, build, all chat and other test lanes, browser E2E,
Runner, and aggregate verify. The first CI run passed broad typecheck,
build, E2E, Runner, and other test groups, but its chat failures remain
recorded above.
- The initial regression launch could not load the unbuilt plugin SDK.
It ran after building the required workspace dependencies. A test-only
resource assertion was corrected to read persisted DM resources, which
the settings list omits. The completed-conversation case preserves an
existing review status.
- The initial correction test used a follow-up timestamp older than the
delivered control. The chronology gate correctly rejected it. A current
provider timestamp now verifies the new generation without weakening
that gate.
- Greptile's map finding was addressed by removing recipe expansions and
all agent-access map changes. Both review threads have replies and are
resolved. Greptile reviewed exact head
367b6f9b3f at [5/5 with zero new
findings](https://github.com/paperclipai/paperclip/pull/19486#issuecomment-6689117840).
The secondary Paperclip Review rated that head 4/5 and found the
completed-task slash lookup error. Commit 23ff4f04f fixes this finding.
Greptile and Paperclip Review both rate head
23ff4f04f6 at 5/5. All three review
threads are resolved. The [full CI
pipeline](https://github.com/paperclipai/paperclip/actions/runs/42255926149)
now passes on this exact head. This includes typecheck, build, all test
lanes, browser E2E, Runner checks, Canary Dry Run, and aggregate verify.
All checks are terminal: 54 success, 1 neutral, and 3 skipped. Snyk also
passes. The PR has no merge conflict.
- The complete server typecheck passed again on 23ff4f04f, including all
three test-tree shards.
- The new test first asserted the conversation-list state. That API
displays terminal tasks as completed before the control is sent. The
test now reads stored binding state to check that completion waits for
the delivered receipt.
- No live Slack send or deployment was performed.

## Risks

- Native DM threads now reopen the existing task after Done or
Cancelled. Explicit new/close controls still release the binding after
their response is delivered. Top-level DMs still start new generations
after completion.
- Existing split tasks stay separate. Future replies use the latest
saved binding. This change does not merge old tasks or copy surrounding
DM history into a newly created thread.
- No schema, credential, provider scope, or permission changes are
required.

## Model Used

OpenAI Codex, based on GPT-6, with reasoning, tool use, repository
editing, and code execution. The runtime does not expose a more precise
serving model ID or context-window size.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [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 <[email protected]>
2026-11-07 08:35:29 -06:00

17 KiB
Raw Permalink Blame History

Automatic Slack app setup

New Slack bot drafts default to automatic setup. Existing drafts without a slackSetupMethod remain manual. Paperclip uses Slack's Manifest API and OAuth v2 directly; neither the operator nor the assisting agent needs the Slack CLI.

Operator setup

  1. Enable Chat connectors in Experimental settings and select an agent in Connectors → Slack → Chat with an agent. Once an agent is selected, Advanced reveals the generated app name, bot name, and slash command. Defaults use the agent name without random suffixes.
  2. On App configuration access token, select Get your App configuration access token. In Slack app settings, open Your App Configuration Tokens → Generate Token, select the workspace, and paste the temporary Access Token directly into Paperclip's password field. Do not supply its refresh token. Select Create Slack app.
  3. After creation and configuration succeed, Paperclip advances to Install Slack app and opens Slack installation in a new window. Approve installation in the intended workspace. If the window is blocked or closed, select Install in Slack. If workspace policy requires administrator approval, return to this saved draft when approval is available. The existing app is reused. Paperclip links the Slack account returned by OAuth to the signed-in Paperclip account that started installation and sends one welcome DM: “Hi, I’m . Your Slack account is connected to Paperclip.” Use your own Slack account.
  4. On Send a message to your agent, select Open Slack and send a message. Paperclip checks incoming events automatically. A signed message event from the saved app/workspace or Slack's signed challenge completes the check. The same fourth screen then shows Success with a checkmark and Done; there is no separate Try it screen. The welcome-message event can complete this check before you send a message. Slack may still display an unverified URL. If the wizard keeps waiting, expand Didn’t work? for Event Subscriptions, Request URL, and Retry instructions. Opening a settings link is not proof. A failed welcome DM does not block setup; open Slack and message the bot directly.

Avatar provisioning is automatic and has no wizard step. Failed or interrupted uploads do not block onboarding; manual upload remains available in the saved connection’s Settings → Agent avatar section.

Automatic creation now omits event subscriptions from the initial manifest, saves the returned signing secret, then applies the full canonical manifest with apps.manifest.update. This removes the creation-time signing-secret race. The 2026-10-07 live experiment did not receive a URL challenge after this update; Slack nevertheless delivered an event, and the operator confirmed receiving an agent response without clicking Retry. A manifest update alone never advances verification. Manual creation continues to use the full canonical manifest.

Slack's settings-page Request URL verification remains distinct from Paperclip's connection check. Automatic setup accepts an authenticated message/app-mention event only after the runtime accepts the request, with the current signing secret, expected app/workspace/bot binding, current callback URL, and active connection. Manual setup retains the signed-challenge requirement. Paperclip can answer a signed challenge as soon as creation has saved the signing secret, even before OAuth installation finishes. This path performs no Slack API calls and does not initialize the bot runtime or wait for the creation operation's lease. Pre-install verification survives configuration only for the same signing secret and webhook URL. It does not authorize installation or activate the connection. The verification DM is queued separately from the HTTP acknowledgement, with durable pending/sending/sent state. Repeated challenges do not send another DM; failed or ambiguous sends do not block setup or replay automatically. Background recovery processes pending messages and quarantines sends interrupted by a restart.

Paperclip captures the signing secret and client secret from creation and obtains the bot token during installation. Durable secrets are stored in the company vault and are not returned by setup APIs or added to the agent prompt. The temporary configuration token is used for app creation, apps.manifest.update, and apps.icon.set, then discarded after the request. Save & exit keeps the draft and all saved non-secret progress.

Create manually and Use an existing app are under Advanced on the token step. Create manually uses the same generated manifest. Use an existing app keeps the existing credential-entry workflow. These paths retain explicit personal account linking through the displayed /command connect command. To connect a different account after setup, use the connection’s Access page. Both options remain available for recovery on the same draft. The selected automatic, manual, or existing-app method is saved, so an existing-app draft reopens at credential entry. Agent instructions require the user to enter the temporary token and handle login/admin approval.

Invite people copies instructions for the saved app’s connect command. Each recipient gets their own expiring confirmation link in Slack and confirms their identity while signed in to Paperclip. New organization members require membership approval. Existing members can self-link; disconnecting an identity does not permanently block that member from reconnecting. Guest access remains a separate, explicit setting for restricted work.

The person joining runs /<saved slash command> connect themselves (for example, /maya connect), without an @person argument. The command discovers their identity without starting agent work or granting access. Slack conversation agents receive this saved command on each fresh or resumed turn, alongside the confirmation and membership-approval instructions. If the saved command is unavailable, they refer the connection manager to Access → Invite people instead of guessing from the agent name. Inviting a person or bot to a Slack channel does not grant that person Paperclip access.

Allowed Channels updates every five seconds while Slack Settings is open. Inviting the bot to a new channel enables replies and writes there automatically; no additional Paperclip configuration is required. An explicit off switch stays off across repeated invitations, reconnects, and inventory refreshes.

A bare @mention starts a normal agent conversation. Paperclip creates the task, subscribes to the Slack thread, and starts the agent; later replies in that thread continue the same task without another mention. Normal account and channel access rules still apply, and repeated Slack deliveries do not create duplicate tasks.

A native Slack thread keeps the same task in channels and DMs, including after the task is Done or Cancelled. A new reply reopens that task with its saved comments. DM access settings and task controls still apply to threads inside DMs. An explicit /new or /close starts the next task generation only after its control response is delivered. Task completion alone does not release the binding. Top-level DMs keep their linear lifecycle and can start a new task after completion. For a thread that was split before this fix, later replies continue its latest saved task. Earlier tasks remain separate; this change does not merge history or copy messages from the surrounding DM into a new thread.

Agents can ask interactive questions in Slack through Paperclip's saved ask_user_questions interactions. Native runners use request_human_input; legacy adapters use the issue-interactions API documented in the injected Paperclip skill. Slack shows native answer buttons or an Answer questions button and form, depending on the question and connection capabilities. Submitting an answer wakes the assigned agent on the same task. This works even when the adapter's built-in question tool is unavailable.

The app icon upload and Settings download use the agent’s 512×512 PNG on Paperclip’s dark-mode background (#171717). Slack flattens transparent app icons onto white, so this export has an opaque background before upload. Normal Paperclip avatars retain transparency. Existing Slack apps need an icon re-upload to adopt the new background; changing Paperclip does not replace their saved icon.

Deployment

Automatic setup requires a canonical public HTTPS board origin and a public HTTPS webhook ingress. The server derives URLs and permissions from its configuration; the browser cannot supply a manifest, scopes, or callback destination.

  • The OAuth redirect is <canonical board origin>/api/chat-slack/oauth/callback. It uses the existing authenticated board callback path and Cloud bootstrap checks. Keep board authentication enabled.
  • Webhook URLs use PAPERCLIP_CHAT_WEBHOOK_PUBLIC_URL when configured, otherwise the canonical board origin. They end in /api/chat-webhooks/<publicId>/slack. A separate webhook ingress must route signed webhook requests to the instance.
  • Avatar upload renders the assigned agent's preset PNG on the server and sends its bytes through apps.icon.set as multipart form data. Slack does not need to fetch an image from the tenant's authenticated board origin. The image is 512 × 512 with the Paperclip dark background. The temporary configuration token stays in the Authorization header and is discarded after setup.
  • Cloud resolves its current canonical origin from its claimed runtime identity. Self-hosted deployments use the configured authentication public base URL (PAPERCLIP_AUTH_PUBLIC_BASE_URL or PAPERCLIP_PUBLIC_URL). Both URLs must have valid certificates and be reachable by their intended callers. A private Tailscale Serve address is insufficient for Slack webhooks.
  • Origin changes invalidate outstanding authorization attempts. Restore the saved origins or reconcile the existing Slack app and use manual recovery. Never loosen authentication or signature verification to bypass a failed callback.

Recovery and invariants

Saved state Operator action
Invalid/expired configuration token Generate a new configuration token and retry. Draft details are preserved.
Creation uncertain after timeout/restart Inspect Slack app settings. Recover an existing app manually on this draft. Start another creation only after explicitly confirming that no app exists.
App saved; event configuration pending after failure/restart Enter an app configuration access token and select Retry app configuration. The same saved app and canonical manifest are reused; installation is blocked until this update succeeds.
App created; installation declined/pending Install the saved app again. No configuration token is needed.
Revoked bot token or uninstalled app Start fresh installation authorization for the same saved app. Existing workspace, bot, and account bindings are preserved; consent started before revocation cannot restore the connection.
Authorization expired or code exchange uncertain Start fresh installation authorization. Used codes are never replayed.
Credentials saved; connection check failed Use Retry connecting. Paperclip reuses vaulted credentials. If Slack access changed or the token was revoked, use Authorize in Slack again for the same app.
Wrong app/workspace/bot or missing scopes Correct the installation of this app. Activation remains blocked.
Avatar upload failed or interrupted Continue setup with the saved app. Optionally upload the avatar from Settings later. The configuration token is not retained for retries.
Existing or revoked personal account link conflicts Manage account links in Access settings. Installation never overwrites someone else’s link or restores a revoked link.
Welcome DM failed or interrupted Continue setup and open Slack directly. A saved dispatch is never replayed after refresh, restart, or reauthorization.
Removed connection Pending state and app-registration secrets are invalidated. Remove the customer's app separately through its Slack management link if desired.

App details are immutable after creation dispatch, including when the outcome is uncertain. The endpoint's existing credential lease serializes creation, configuration, recovery, and removal across server processes. Generic connection removal uses the same lock. The unique-bot constraint still applies.

Registration secrets are separate from runtime credentials. The received bot token is vaulted before auth.test, inventory, and configuration. Staged bot/signing secret copies are deleted only after runtime binding commits. Client credentials remain in the registration vault for subsequent authorization. OAuth’s authed_user.id identifies the installer; the bot token confirms that person’s workspace through users.info. Company membership and existing identity-link constraints are checked before linking. Reauthorization preserves the original linked account. Welcome-DM dispatch is saved before calling chat.postMessage; an interrupted dispatch becomes uncertain instead of sending a duplicate. The welcome contains no confirmation token and starts no agent work. Local activity records contain safe IDs and outcome codes. This feature adds no telemetry.

Verification

Focused checks:

pnpm exec vitest run packages/shared/src/slack-app-manifest.test.ts ui/src/pages/apps/chat/SlackAutomaticSetup.test.tsx
pnpm exec vitest run server/src/__tests__/chat-channels.integration.test.ts -t 'automatic Slack registration'
pnpm exec playwright test --config tests/e2e/playwright.config.ts tests/e2e/chat-adapters-ui-providers.spec.ts
pnpm check:token-gates

The Storybook stories under Connections / Slack / Automatic setup render the production wizard with simulated provider responses. They cover the automatic journey, manual setup, pending/declined installation, uncertain creation, saved credential recovery, avatar failure without an extra wizard step, verification waiting, welcome-DM failure, and mobile layouts. These are fixture checks.

Partial live qualification on 2026-10-07 used an isolated authenticated instance behind TryCloudflare and the operator's authorized Slack installation. The operator created and installed the app through the wizard. Safe activity recorded successful avatar upload, installer linking, and welcome delivery. A signed Request URL challenge was recorded after Retry; the later verification confirmation was sent to the already-linked DM using that saved receipt, without creating another app. No credentials or OAuth codes are included in this evidence. The new pre-install challenge path, notification concurrency/restart recovery, revocation, removal, and provider failure cases passed deterministic fixtures. In a subsequent two-phase creation run, Slack accepted the manifest update but sent no URL challenge. An Events API callback returned HTTP 200, and the operator confirmed a real agent reply without clicking Retry. The new automatic advancement based on that kind of event is covered by fixtures; the operator subsequently confirmed live automatic advancement after another message. Same-thread follow-up, reauthorization, and removal qualification remain outstanding.

For live acceptance, use an isolated HTTPS Paperclip instance, a dedicated test app, and an explicitly authorized Slack workspace and destination. Have the user enter the configuration token directly. Verify app creation, consent return, signed URL verification, avatar status, automatic installer linking, welcome DM, a real message and same-thread follow-up, the assigned agent run, and Slack delivery. Resume an interrupted setup, reauthorize the same app, and remove the Paperclip connection with an outstanding attempt. Record sanitized IDs/links and outcomes, without secret fields, OAuth codes, or provider payloads. Record live results separately from deterministic fixtures.

Provider references: Manifest creation API, OAuth installation, Manifest reference, App icon API, Sending a DM.

Agent behavior checks

Slack per-turn guidance covers saved interactive questions, automatic final replies, current-chat file handoff, explicit actions, delivery uncertainty, and action policies. Tool-description changes refresh the stored catalog without re-enabling removed tools or changing their review ownership.

The connector probe catalog keeps eleven manual acceptance probes next to that guidance, with related deterministic checks selectable through pnpm test:slack-connector. No automated model campaign is registered by that command. An attended legacy Codex test on 2026-10-07 delivered real Slack choices, accepted an answer, resumed the same task, and returned a correct reply; other probes and runtimes remain unqualified until their own provider evidence is recorded.