mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-05 06:03:51 +01:00
fix(slack): preserve routing text when saving link destinations
Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
1 parent
0bcc1c1237
commit
eaa9f03afd
7 files changed
+65
-37
No files matched your search
@@ -194,7 +194,7 @@ import {
|
||||
} from "@paperclipai/db";
|
||||
import { defaultGitHubReviewPolicy, type ChatProvider } from "@paperclipai/shared";
|
||||
import { isPaperclipExternalChatTurn } from "@paperclipai/adapter-utils/server-utils";
|
||||
import type { Attachment, Author, Message, Thread } from "chat";
|
||||
import { Chat, type Attachment, type Author, type Message, type Thread } from "chat";
|
||||
import { errorHandler } from "../middleware/index.js";
|
||||
import { issueRoutes } from "../routes/issues.js";
|
||||
import { deliverReconciledExecutions } from "../services/execution-recovery-resolution.js";
|
||||
@@ -61499,6 +61499,26 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => {
|
||||
},
|
||||
);
|
||||
|
||||
it("does not admit a Slack task from a bot handle hidden in a link destination", async () => {
|
||||
const fixture = await seedCompany();
|
||||
const { callbacks, endpoint, service } = await configuredSlackEndpoint(fixture, { requireAtMention: true });
|
||||
const channel = makeThread({ channelId: "C-HIDDEN-HANDLE", id: "slack:C-HIDDEN-HANDLE:1740000001.100000" });
|
||||
const adapter = new PaperclipSlackAdapter({ botToken: "xoxb-synthetic", signingSecret: "synthetic", userName: "test-bot" });
|
||||
const sdk = Object.create(Chat.prototype) as { setMentionFlags(adapter: PaperclipSlackAdapter, message: Message): boolean };
|
||||
try {
|
||||
const message = adapter.parseMessage({ type: "message", channel: "C-HIDDEN-HANDLE", ts: "1740000001.100000", user: "U-EXTERNAL", username: "alex", text: "Look <https://example.com/@test-bot|profile>" });
|
||||
expect(sdk.setMentionFlags(adapter, message)).toBe(false);
|
||||
await deliverMessage({ callbacks, endpointId: endpoint.id, thread: channel.thread, message, trigger: "subscribed_message" });
|
||||
expect(await readChatConversationsByEndpointId(endpoint.id)).toHaveLength(0);
|
||||
expect(await readIssueCommentsByCompanyId(fixture.companyId)).toHaveLength(0);
|
||||
const [delivery] = await readChatDeliveriesByEndpointId(endpoint.id);
|
||||
expect(delivery.state).toBe("filtered");
|
||||
expect(JSON.stringify(delivery.normalizedEvent)).not.toContain("https://example.com/@test-bot");
|
||||
} finally {
|
||||
await retirePublicationFixture(service, endpoint.id);
|
||||
}
|
||||
});
|
||||
|
||||
it("persists full Slack link destinations in task requests, replies, edits and wake comments", async () => {
|
||||
const fixture = await seedCompany();
|
||||
const { callbacks, endpoint, service, wakeup } = await configuredSlackEndpoint(fixture);
|
||||
|
||||
@@ -2286,7 +2286,7 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) {
|
||||
);
|
||||
}
|
||||
const body =
|
||||
githubInboundCommentText({ manual: githubManual, repository: resource.providerResourceId, thread: thread.id, sender: { id: principalResolution.principal.externalId, login: principalResolution.principal.handle }, message: message.text }) ||
|
||||
githubInboundCommentText({ manual: githubManual, repository: resource.providerResourceId, thread: thread.id, sender: { id: principalResolution.principal.externalId, login: principalResolution.principal.handle }, message: endpoint.provider === "slack" ? normalized.message.text : message.text }) ||
|
||||
(message.attachments.length > 0
|
||||
? taskEndpoint.provider === "microsoft-teams" &&
|
||||
!thread.isDM &&
|
||||
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
} from "../telegram/messages.js";
|
||||
import {
|
||||
slackMessageSentAt,
|
||||
slackInboundRequestText,
|
||||
} from "../slack/messages.js";
|
||||
import {
|
||||
teamsActivitySentAt,
|
||||
@@ -290,7 +291,7 @@ export function createInboundEnvelope(db: Db, options: InboundEnvelopeOptions) {
|
||||
: null,
|
||||
providerUpdateId:
|
||||
endpoint.provider === "telegram" ? (providerUpdateId ?? null) : null,
|
||||
text: message.text.slice(0, MAX_INBOUND_TEXT),
|
||||
text: (endpoint.provider === "slack" ? slackInboundRequestText(message) : message.text).slice(0, MAX_INBOUND_TEXT),
|
||||
mentionedBot: message.isMention === true,
|
||||
providerSentAt: providerSentAt?.toISOString() ?? null,
|
||||
...(providerSentAtSource ? { providerSentAtSource } : {}),
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
} from "../telegram/messages.js";
|
||||
import {
|
||||
slackLifecycleFilesDigest,
|
||||
slackInboundRequestText,
|
||||
} from "../slack/messages.js";
|
||||
import {
|
||||
discordLifecycleFilesDigest,
|
||||
@@ -1023,7 +1024,8 @@ export function createChatMessageLifecycle(db: Db, options: MessageLifecycleOpti
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const text = `An external message was edited:\n\n${event.message.text.slice(0, MAX_INBOUND_TEXT)}`;
|
||||
const requestText = event.provider === "slack" ? slackInboundRequestText(event.message) : event.message.text;
|
||||
const text = `An external message was edited:\n\n${requestText.slice(0, MAX_INBOUND_TEXT)}`;
|
||||
const telegramRich =
|
||||
event.provider === "telegram"
|
||||
? normalizeTelegramRichMessage(event.message.raw)
|
||||
@@ -1049,7 +1051,7 @@ export function createChatMessageLifecycle(db: Db, options: MessageLifecycleOpti
|
||||
event.message.metadata.editedAt ?? event.message.metadata.dateSent
|
||||
)?.toISOString() ?? null,
|
||||
raw: event.message.raw,
|
||||
revision: `${event.message.metadata.editedAt?.toISOString() ?? "unknown"}:${createHash("sha256").update(event.message.text).digest("hex")}${event.provider === "slack" ? `:${slackLifecycleFilesDigest(event.message.raw)}` : event.provider === "discord" ? `:${discordLifecycleFilesDigest(event.message.raw)}` : telegramRich ? `:${telegramRich.mediaDigest}` : ""}`,
|
||||
revision: `${event.message.metadata.editedAt?.toISOString() ?? "unknown"}:${createHash("sha256").update(requestText).digest("hex")}${event.provider === "slack" ? `:${slackLifecycleFilesDigest(event.message.raw)}` : event.provider === "discord" ? `:${discordLifecycleFilesDigest(event.message.raw)}` : telegramRich ? `:${telegramRich.mediaDigest}` : ""}`,
|
||||
},
|
||||
runtimeContext,
|
||||
);
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { SlackAdapter, type SlackEvent } from "@chat-adapter/slack";
|
||||
import { ConsoleLogger, type ChatInstance } from "chat";
|
||||
import { Chat, ConsoleLogger, type ChatInstance, type Message } from "chat";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { PaperclipSlackAdapter } from "./adapter.js";
|
||||
import { slackMessageMeetsMentionRequirement, slackInboundRequestText } from "./messages.js";
|
||||
|
||||
afterEach(() => vi.useRealTimers());
|
||||
|
||||
@@ -22,7 +23,8 @@ describe("Slack inbound link latency", () => {
|
||||
} as SlackEvent;
|
||||
const config = { botToken: "xoxb-synthetic", signingSecret: "synthetic", userName: "test-bot", logger: new ConsoleLogger("silent") };
|
||||
const received = await new Candidate(config).parse(event);
|
||||
expect(received.text).toBe("Review this link (https://example.com/review)");
|
||||
expect(received.text).toBe("Review this link");
|
||||
expect(slackInboundRequestText(received)).toBe("Review this link (https://example.com/review)");
|
||||
expect(received.links).toMatchObject([{ url: "https://example.com/review" }]);
|
||||
expect(received.attachments).toMatchObject([{ name: "notes.txt", fetchData: expect.any(Function) }]);
|
||||
expect(state.get).not.toHaveBeenCalled();
|
||||
@@ -57,7 +59,23 @@ describe("Slack inbound link destinations", () => {
|
||||
])("preserves author links for async and sync parsing: %s", async (text, expected) => {
|
||||
const adapter = new Candidate(config);
|
||||
const event = { type: "message", channel: "C123", ts: "1740000001.1", username: "Test sender", text } as SlackEvent;
|
||||
expect((await adapter.parse(event)).text).toBe(expected);
|
||||
expect(adapter.parseMessage(event).text).toBe(expected);
|
||||
const received = await adapter.parse(event);
|
||||
expect(slackInboundRequestText(received)).toBe(expected);
|
||||
expect(slackInboundRequestText(adapter.parseMessage(event))).toBe(expected);
|
||||
});
|
||||
});
|
||||
|
||||
// Exercise the pinned SDK routing implementation, rather than a copy of its regex.
|
||||
it("does not route a hidden link destination as a bot mention", () => {
|
||||
const adapter = new PaperclipSlackAdapter({ botToken: "xoxb-synthetic", signingSecret: "synthetic", userName: "test-bot", logger: new ConsoleLogger("silent") });
|
||||
const sdk = Object.create(Chat.prototype) as { setMentionFlags(adapter: PaperclipSlackAdapter, message: Message): boolean };
|
||||
for (const url of ["https://example.com/@test-bot", "https://example.com/?user=@test-bot"]) {
|
||||
const message = adapter.parseMessage({ type: "message", channel: "C123", ts: "1740000001.1", username: "Test sender", text: `Look <${url}|profile>` });
|
||||
expect(sdk.setMentionFlags(adapter, message)).toBe(false);
|
||||
expect(message.isMention).toBe(false);
|
||||
expect(slackMessageMeetsMentionRequirement({ requireAtMention: true }, { id: "slack:C123:1740000001.1", isDM: false }, "subscribed_message", message)).toBe(false);
|
||||
}
|
||||
const addressed = adapter.parseMessage({ type: "message", channel: "C123", ts: "1740000001.1", username: "Test sender", text: "@test-bot review this" });
|
||||
expect(sdk.setMentionFlags(adapter, addressed)).toBe(true);
|
||||
expect(slackMessageMeetsMentionRequirement({ requireAtMention: true }, { id: "slack:C123:1740000001.1", isDM: false }, "mention", addressed)).toBe(true);
|
||||
});
|
||||
@@ -3,37 +3,11 @@ import type { ModalElement } from "chat";
|
||||
import { slackDeferredCallbackActive } from "./cloud-callback.js";
|
||||
import { slackFormOpenContext } from "./cloud-forms.js";
|
||||
import { SlackCloudReceiptError } from "./cloud-event.js";
|
||||
import { SlackAdapter, type SlackEvent } from "@chat-adapter/slack";
|
||||
import { toPlainText, walkAst, type Message } from "chat";
|
||||
import { SlackAdapter } from "@chat-adapter/slack";
|
||||
import type { AdapterPostableMessage, LinkPreview, RawMessage } from "chat";
|
||||
import { slackSelectionMessage } from "./cards.js";
|
||||
|
||||
function preserveLinkDestinations(message: Message): Message {
|
||||
// Intake persists text, whereas the SDK's plain-text projection keeps only
|
||||
// link labels. Use author content, never unfurl/preview metadata, and leave
|
||||
// the original formatted AST intact for other SDK consumers.
|
||||
const formatted = walkAst(structuredClone(message.formatted), (node) => {
|
||||
if (node.type !== "link") return node;
|
||||
const label = toPlainText({ type: "root", children: [node] });
|
||||
return { type: "text", value: label === node.url ? label : `${label} (${node.url})` };
|
||||
});
|
||||
message.text = toPlainText(formatted);
|
||||
return message;
|
||||
}
|
||||
|
||||
export class PaperclipSlackAdapter extends SlackAdapter {
|
||||
protected override async parseSlackMessage(
|
||||
event: SlackEvent,
|
||||
threadId: string,
|
||||
options?: { skipSelfMention?: boolean },
|
||||
): Promise<Message> {
|
||||
return preserveLinkDestinations(await super.parseSlackMessage(event, threadId, options));
|
||||
}
|
||||
|
||||
protected override parseSlackMessageSync(event: SlackEvent, threadId: string): Message {
|
||||
return preserveLinkDestinations(super.parseSlackMessageSync(event, threadId));
|
||||
}
|
||||
|
||||
override async openModal(triggerId: string, modal: ModalElement, contextId?: string): Promise<{ viewId: string }> {
|
||||
const current = slackFormOpenContext();
|
||||
if (!current) {
|
||||
|
||||
@@ -1,9 +1,22 @@
|
||||
import type { Message, Thread } from "chat";
|
||||
import { toPlainText, walkAst, type Message, type Thread } from "chat";
|
||||
import type { EndpointRow } from "../runtime-types.js";
|
||||
import type { ChatSdkMessageCallbackEvent } from "../../chat-sdk-runtime.js";
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
|
||||
// Render only for persisted request content. Message.text remains the SDK's
|
||||
// routing projection: hidden destinations must not become bot mentions or
|
||||
// match onNewMessage patterns. Keep the author AST intact for SDK consumers.
|
||||
export function slackInboundRequestText(message: Pick<Message, "text"> & Partial<Pick<Message, "formatted">>): string {
|
||||
if (!message.formatted?.children.length) return message.text;
|
||||
const formatted = walkAst(structuredClone(message.formatted), (node) => {
|
||||
if (node.type !== "link") return node;
|
||||
const label = toPlainText({ type: "root", children: [node] });
|
||||
return { type: "text", value: label === node.url ? label : `${label} (${node.url})` };
|
||||
});
|
||||
return toPlainText(formatted);
|
||||
}
|
||||
|
||||
export function slackLifecycleFilesDigest(raw: unknown): string {
|
||||
const files =
|
||||
raw && typeof raw === "object" && !Array.isArray(raw)
|
||||
|
||||
Reference in new issue
Block a user