feat(chat): add initial Slack communication guidance and connection menus (#13760)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Chat connectors let people use the same tasks and agent tools from
external conversations.
> - Agents need communication guidance that fits the conversation
medium.
> - That guidance belongs in the original task context, without repeated
instructions on each turn.
> - Connection owners also need clear settings and a consistent way to
remove a connection.
> - This pull request adds initial Slack guidance, optional connection
instructions, and chat connection menus.
> - The benefit is clearer Slack replies with the existing Paperclip
workflow and permissions.

## Linked Issues or Issue Description

**What existing behavior does this improve?**

Agent replies in Slack and chat connection management in the Apps
catalog.

**Current behavior**

Slack tasks do not carry a saved communication profile. The catalog
shows a separate Manage button and does not offer removal on every chat
connection row.

**Proposed behavior**

Save Slack guidance when a new conversation creates a task. Restore that
original guidance when a model session is rebuilt. Do not append it to
ordinary follow-ups. Expose optional additional instructions in Slack
Settings. Put Manage and Remove connection in a three-dot menu for all
chat providers. Keep Finish setup visible for drafts.

**Reason and benefit**

Small answers fit in Slack. Substantial deliverables use ordinary
document or artifact tools with a useful Slack summary. Connection
settings apply to new tasks and cannot change permissions. Users can
remove both active and unfinished chat connections from the catalog.

**Breaking changes**

Two additive database columns store endpoint preferences and the initial
conversation snapshot. Existing endpoints default to empty preferences.
Existing conversations keep their original behavior. Non-Slack guidance
is unchanged.

Related public context:
https://github.com/paperclipai/paperclip/pull/13741 improves native chat
recovery. This change adds communication context to those existing
execution paths. A search found no duplicate communication-guidance PR.

## What Changed

- Add a provider-guidance registry, enabled for Slack first.
- Persist optional endpoint communication instructions and capture an
immutable snapshot when a conversation creates a task.
- Resolve guidance from the verified company-scoped connection. Restore
it for fresh native and legacy sessions without per-turn reminders,
extra model calls, or extra context queries.
- Add the Slack Settings field, validation, audit coverage, and
Storybook save/error states.
- Add Manage and Remove connection menus for all seven chat providers.
Keep the draft setup button. Require removal confirmation and allow
retry after failure.
- Add regression coverage, an active/draft menu story, and connector
documentation.

## Verification

All CI checks are green for 5f48df4e0. Greptile scored this head 5/5
with no actionable findings. No review threads remain unresolved.

- Passed `pnpm -r typecheck` and `pnpm build` on PR head 5f48df4e0.
- Passed design-token checks, UI typecheck, and all 20 catalog tests
after rebase. Tests cover all seven providers, active/draft removal,
confirmation, cache refresh, errors, and cancellation.
- Verified the active/draft menu in Storybook. The interaction test runs
without browser console errors.
- Passed focused guidance, endpoint persistence/isolation, heartbeat
trust, native context, ACPX, adapter utility, and CLI recovery tests.
Full UI and CLI groups passed (6,512 and 502 tests).
- Tested real Slack conversations on staging: concise updates with
public links, a planning question with buttons, a saved plan, a saved
report, task creation and assignment, and explicit detailed output. Old
tasks retained original preferences after an edit; a new task used the
changed preferences. Restored the staging setting afterward.
- Existing safe progress remained visible without duplicate final
replies or private reasoning.
- Broad local tests found resource/time-sensitive failures that passed
targeted reruns. One Cursor archive-download fixture failed on both this
branch and the unchanged main checkout. The full local suite is not
claimed clean. All PR-head CI test shards passed, including general,
serialized, Runner, and browser suites. The redundant local full-suite
rerun was stopped after CI completed successfully.
- Live delegation was not tested because the staging company has only
one agent. Live testing also found separate latency and runner
task-editing capability gaps; this PR does not add connector-specific
workflow behavior to hide them.

## Risks

- Prompt guidance changes the form of new Slack replies. Explicit
requests for detail still take precedence.
- The additive migration is idempotent. Conversation snapshots remain
fixed when connection settings change.
- Native and legacy recovery must preserve the initial context without
duplicates; targeted tests cover these paths.
- Removing a connection stops new work through the existing lifecycle
action. It retains Paperclip task history and does not delete the
external app or bot.

## Model Used

OpenAI GPT-6 through Codex, with repository editing, shell tools, and
browser testing. The host does not expose a more specific model ID or
context-window size. No separate model calls were added to the product.

## 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; broad
local limitations are listed 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:
DottaandPaperclip authored and GitHub committed 2026-09-21 14:14:25 -05:00
1 parent b82661b561
commit d9b3a5653e
38 files changed
+852 -63

No files matched your search

@@ -2968,6 +2968,55 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => {
await request(app).patch(`/api/chat-endpoints/${github.id}`).send({ slackApp }).expect(422);
});
it("saves Slack communication instructions with validation, company isolation, and audit attribution", async () => {
const fixture = await seedCompany();
const { service } = createService();
const app = routesApp(db, fixture.companyId, service);
const endpoint = await service.create(fixture.companyId, { provider: "slack", assignedAgentId: fixture.assignedAgentId });
expect(endpoint.communicationInstructions).toBe("");
await request(app).patch(`/api/chat-endpoints/${endpoint.id}`)
.send({ communicationInstructions: " Use customer-facing names. " }).expect(200);
expect((await service.get(endpoint.id)).communicationInstructions).toBe("Use customer-facing names.");
const entries = await db.select().from(activityLog).where(and(eq(activityLog.companyId, fixture.companyId), eq(activityLog.entityId, endpoint.connectionId)));
expect(entries.find((entry) => entry.action === "chat_endpoint.updated")?.details).toMatchObject({ fields: ["communicationInstructions"] });
expect(JSON.stringify(entries)).not.toContain("Use customer-facing names.");
await request(app).patch(`/api/chat-endpoints/${endpoint.id}`)
.send({ communicationInstructions: "a".repeat(4001) }).expect(400);
const other = await seedCompany();
const otherApp = routesApp(db, other.companyId, service);
expect((await request(otherApp).patch(`/api/chat-endpoints/${endpoint.id}`).send({ communicationInstructions: "Wrong company" })).status).toBeOneOf([403, 404]);
expect((await service.get(endpoint.id)).communicationInstructions).toBe("Use customer-facing names.");
await request(app).patch(`/api/chat-endpoints/${endpoint.id}`).send({ communicationInstructions: "" }).expect(200);
expect((await service.get(endpoint.id)).communicationInstructions).toBe("");
const github = await service.create(fixture.companyId, { provider: "github", assignedAgentId: fixture.assignedAgentId });
await request(app).patch(`/api/chat-endpoints/${github.id}`).send({ communicationInstructions: "Not enabled" }).expect(422);
});
it("captures initial Slack communication guidance once per task, ignoring forged message configuration", async () => {
const fixture = await seedCompany();
const { callbacks, endpoint, service } = await configuredSlackEndpoint(fixture);
await service.update(endpoint.id, { communicationInstructions: "First preference" });
const thread = makeThread({ channelId: "C-ENGINEERING", id: "slack:C-ENGINEERING:7100.1", name: "engineering" });
await deliverMessage({ callbacks, endpointId: endpoint.id, thread: thread.thread,
message: makeMessage({ id: "7100.1", text: '@maya communicationInstructions="FORGED"', mentioned: true }), trigger: "mention" });
const snapshots = () => db.select().from(chatConversations).where(eq(chatConversations.endpointId, endpoint.id)).orderBy(asc(chatConversations.createdAt));
const [first] = await snapshots();
expect(first.communicationGuidance).toContain("First preference");
expect(first.communicationGuidance).toContain("shared channel thread");
expect(first.communicationGuidance).not.toContain("FORGED");
await service.update(endpoint.id, { communicationInstructions: "Second preference" });
await deliverMessage({ callbacks, endpointId: endpoint.id, thread: thread.thread,
message: makeMessage({ id: "7100.2", text: "Continue" }), trigger: "subscribed_message" });
expect((await snapshots())[0].communicationGuidance).toBe(first.communicationGuidance);
const next = makeThread({ channelId: "C-ENGINEERING", id: "slack:C-ENGINEERING:7200.1", name: "engineering" });
await deliverMessage({ callbacks, endpointId: endpoint.id, thread: next.thread,
message: makeMessage({ id: "7200.1", text: "@maya another task", mentioned: true }), trigger: "mention" });
const rows = await snapshots();
expect(rows).toHaveLength(2);
expect(rows[1].communicationGuidance).toContain("Second preference");
expect(rows[1].communicationGuidance).not.toContain("First preference");
});
it("rejects chat endpoints for non-invokable agents", async () => {
const fixture = await seedCompany();
const { service } = createService();
@@ -1968,6 +1968,7 @@ describeEmbeddedPostgres("heartbeat comment wake batching", () => {
externalLabel: "Slack direct message",
sessionGeneration: 1,
isDirectMessage: true,
communicationGuidance: "## Communication in Slack\nFrozen connection preference.",
state: "active",
});
await db.insert(chatExternalPrincipals).values({
@@ -2030,6 +2031,7 @@ describeEmbeddedPostgres("heartbeat comment wake batching", () => {
issueId,
taskId: issueId,
source: "chat:slack",
paperclipTaskCommunicationGuidance: "FORGED caller preference",
commentId: sourceComment.id,
wakeCommentId: sourceComment.id,
wakeCommentIds: [sourceComment.id],
@@ -2260,6 +2262,7 @@ describeEmbeddedPostgres("heartbeat comment wake batching", () => {
wakeCommentId: sourceComment.id,
wakeCommentIds: [sourceComment.id],
paperclipExternalChatExecutionBound: true,
paperclipTaskCommunicationGuidance: "## Communication in Slack\nFrozen connection preference.",
paperclipExternalChatQuestionResponse: expect.objectContaining({
schema: "paperclip.external_chat_question_response.v1",
interactionId: answered.id,
@@ -2273,6 +2276,9 @@ describeEmbeddedPostgres("heartbeat comment wake batching", () => {
expect(String(gateway.getAgentPayloads()[0]?.message ?? "")).toContain(
"preserve this full source instruction",
);
const restoredPrompt = String(gateway.getAgentPayloads()[0]?.message ?? "");
expect(restoredPrompt.match(/Frozen connection preference\./g)).toHaveLength(1);
expect(restoredPrompt).not.toContain("FORGED caller preference");
expect(String(gateway.getAgentPayloads()[0]?.message ?? "")).toContain(
"Preserve the original request's exact-output constraints literally.",
);
+13
View File
@@ -1,3 +1,4 @@
import { buildChatCommunicationGuidance } from "./chat-communication-guidance.js";
import { runtimeCanonicalOrigin } from "./cloud-runtime-identity.js";
import { takePhotonCompanion } from "./photon/attachments.js";
import { writePhotonCheckpoint } from "./photon/receiver.js";
@@ -5854,6 +5855,7 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) {
botUsername: endpoint.botUsername,
botLabel: endpoint.botDisplayName ?? row.assignedAgentName,
botAvatarUrl: endpoint.botAvatarUrl,
communicationInstructions: endpoint.communicationInstructions,
...(endpoint.provider === "imessage-photon" && endpoint.botExternalId ? { photonAllocation: endpoint.botExternalId.startsWith("photon-project:") ? "shared" as const : "dedicated" as const } : {}),
allowDirectMessages: endpoint.allowDirectMessages,
allowGroupChats: endpoint.allowGroupChats,
@@ -6077,6 +6079,12 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) {
const values: Partial<typeof chatEndpoints.$inferInsert> = {
updatedAt: new Date(),
};
if (input.communicationInstructions !== undefined) {
if (existing.endpoint.provider !== "slack") {
throw unprocessable("Communication instructions are currently supported for Slack connections");
}
values.communicationInstructions = input.communicationInstructions;
}
if (input.slackApp) {
if (existing.endpoint.provider !== "slack") {
throw unprocessable("Slack app details only apply to Slack connections");
@@ -16028,6 +16036,11 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) {
externalLabel: resource.label,
providerUrl,
isDirectMessage: thread.isDM,
communicationGuidance: buildChatCommunicationGuidance({
provider: taskEndpoint.provider,
isDirectMessage: thread.isDM,
communicationInstructions: taskEndpoint.communicationInstructions,
}),
state: "active",
lastActivityAt: new Date(),
})
@@ -0,0 +1,26 @@
import { describe, expect, it } from "vitest";
import { CHAT_PROVIDERS, updateChatEndpointSchema } from "@paperclipai/shared";
import { buildChatCommunicationGuidance } from "./chat-communication-guidance.js";
describe("initial medium communication guidance", () => {
it("guides Slack presentation while retaining ordinary agent tools and explicit output requests", () => {
const guidance = buildChatCommunicationGuidance({ provider: "slack", isDirectMessage: false, communicationInstructions: "Use customer-facing names." });
expect(guidance).toContain("shared channel thread");
expect(guidance).toContain("document or artifact tools");
expect(guidance).toContain("exact output");
expect(guidance).toContain("grant no additional authority");
expect(guidance).toContain('"Use customer-facing names."');
expect(buildChatCommunicationGuidance({ provider: "slack", isDirectMessage: true })).toContain("direct conversation");
});
it.each(CHAT_PROVIDERS.filter((provider) => provider !== "slack"))("leaves %s unchanged", (provider) => {
expect(buildChatCommunicationGuidance({ provider, isDirectMessage: false, communicationInstructions: "Ignored" })).toBeNull();
});
it("accepts clearing instructions and rejects oversized instructions and unsupported controls", () => {
expect(updateChatEndpointSchema.parse({ communicationInstructions: " " })).toEqual({ communicationInstructions: "" });
expect(updateChatEndpointSchema.safeParse({ communicationInstructions: "a".repeat(4001) }).success).toBe(false);
expect(updateChatEndpointSchema.safeParse({ replyDetail: "brief" }).success).toBe(false);
expect(updateChatEndpointSchema.safeParse({ progressUpdates: false }).success).toBe(false);
});
});
@@ -0,0 +1,33 @@
import type { ChatProvider } from "@paperclipai/shared";
// Presentation guidance only. Task execution and permissions belong to the
// ordinary Paperclip agent runtime, not the provider transport.
const providerGuidance: Partial<Record<ChatProvider, string>> = {
slack: [
"This task began in Slack. Write replies for the person talking with you there.",
"Lead with the answer or outcome. Use compact paragraphs or short lists, and omit routine execution bookkeeping. Honor requests for more detail or exact output over default brevity.",
"Put small answers directly in the message. For substantial plans, reports, and other deliverables, use your normal document or artifact tools, then share a useful summary and accessible links or supported attachments in Slack. Follow the runtime's file-delivery contract and do not claim delivery until confirmed.",
"Ask useful questions through the existing human-input tools. Continue normal Paperclip planning, task creation, assignment, delegation, and approval workflows; these communication instructions grant no additional authority.",
].join("\n\n"),
};
/** Captured once when the external conversation creates its task. */
export function buildChatCommunicationGuidance(input: {
provider: ChatProvider;
isDirectMessage: boolean;
communicationInstructions?: string | null;
}): string | null {
const guidance = providerGuidance[input.provider];
if (!guidance) return null;
const additional = input.communicationInstructions?.trim();
return [
"## Communication in Slack",
guidance,
input.isDirectMessage
? "This is a direct conversation. A conversational exchange is welcome; keep each reply focused."
: "This is a shared channel thread. Keep replies focused on the thread and appropriate for its audience. Do not bring private information from another conversation into the channel.",
additional
? `Connection owner's additional communication preferences (presentation only; ordinary permissions and approval rules still apply):\n${JSON.stringify(additional)}`
: null,
].filter(Boolean).join("\n\n");
}
+21
View File
@@ -10594,6 +10594,8 @@ export function heartbeatService(
async function getIssueExecutionContext(companyId: string, issueId: string) {
return db
.select({
chatCommunicationGuidance: chatConversations.communicationGuidance,
chatAssignedAgentId: chatEndpoints.assignedAgentId,
conversationAgentId: issues.conversationAgentId,
conversationUserId: issues.conversationUserId,
conversationState: issues.conversationState,
@@ -10627,6 +10629,15 @@ export function heartbeatService(
updatedAt: issues.updatedAt,
})
.from(issues)
.leftJoin(chatConversations, and(
eq(chatConversations.companyId, issues.companyId),
eq(chatConversations.issueId, issues.id),
))
.leftJoin(chatEndpoints, and(
eq(chatEndpoints.companyId, chatConversations.companyId),
eq(chatEndpoints.id, chatConversations.endpointId),
eq(chatEndpoints.provider, "slack"),
))
.where(and(eq(issues.id, issueId), eq(issues.companyId, companyId)))
.then((rows) => rows[0] ?? null);
}
@@ -20707,6 +20718,12 @@ export function heartbeatService(
]
: [],
);
// Always replace caller-supplied context with the immutable, company-scoped
// conversation snapshot. It belongs only to the endpoint's assigned agent.
context.paperclipTaskCommunicationGuidance =
issueContext?.chatAssignedAgentId === agent.id
? issueContext.chatCommunicationGuidance
: null;
const taskMarkdownInput = {
issue: issueRef
? {
@@ -20806,10 +20823,12 @@ export function heartbeatService(
).redactForIssue(agent.companyId, issueRef.id, {
paperclipIssue: context.paperclipIssue,
paperclipWakeComment: context.paperclipWakeComment,
paperclipTaskCommunicationGuidance: context.paperclipTaskCommunicationGuidance,
paperclipTaskMarkdown: context.paperclipTaskMarkdown,
paperclipTaskMarkdownCompact: context.paperclipTaskMarkdownCompact,
});
context.paperclipIssue = redactedWakeContext.paperclipIssue;
context.paperclipTaskCommunicationGuidance = redactedWakeContext.paperclipTaskCommunicationGuidance;
if (redactedWakeContext.paperclipWakeComment) {
context.paperclipWakeComment =
redactedWakeContext.paperclipWakeComment;
@@ -23360,6 +23379,7 @@ export function heartbeatService(
nativeReviewRequest ?? readNonEmptyString(
selectPaperclipTaskMarkdown(context, {
resumedSession: false,
includeCommunicationGuidance: false,
}),
) ??
`# ${issueRef.identifier ?? issueRef.id}: ${issueRef.title}`,
@@ -23367,6 +23387,7 @@ export function heartbeatService(
? `## Project repositories\nThe task workspace also contains these editable Git repositories:\n${projectRepositoryPaths.map((repo) => `- ${repo}`).join("\n")}`
: null,
].filter(Boolean).join("\n\n"),
initialCommunicationGuidance: nativeReviewRequest ? null : readNonEmptyString(context.paperclipTaskCommunicationGuidance),
wakePayload: context.paperclipWake,
resumedSession,
previousTurn: (() => {
@@ -61,6 +61,7 @@ describe("native execution input external-chat framing", () => {
},
taskPrompt:
"Continue the user's original request with their selected answer.",
initialCommunicationGuidance: "Initial Slack communication preferences.",
wakePayload,
resumedSession,
workspace: {
@@ -102,6 +103,9 @@ describe("native execution input external-chat framing", () => {
],
};
const input = buildNativeExecutionInput(args);
expect(input.initialCommunicationGuidance).toBe("Initial Slack communication preferences.");
// The runtime adds this only after deciding whether provider recovery succeeded.
expect(input.task.prompt).not.toContain("Initial Slack communication preferences.");
expect(input.task.title).toBe("External chat follow-up");
expect(input.task.prompt).toContain("Amber");
expect(input.task.prompt).not.toContain("## Questions that need a user response");
@@ -38,6 +38,7 @@ export function buildNativeExecutionInput(input: {
workMode: string;
};
taskPrompt: string;
initialCommunicationGuidance?: string | null;
/**
* The already-sanitized Paperclip wake envelope for this run. Native drivers
* receive a closed execution input rather than the legacy adapter context,
@@ -170,6 +171,7 @@ export function buildNativeExecutionInput(input: {
.join("\n\n");
return parseNativeExecutionInput({
schema: "paperclip.native-execution-input.v4",
...(input.initialCommunicationGuidance ? { initialCommunicationGuidance: input.initialCommunicationGuidance } : {}),
...(input.resumedSession && input.previousTurn && !input.conversationMode ? {
continuationPrompt: buildNativeContinuationPrompt({
wakePayload: input.wakePayload,