mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-28 13:09:40 +01:00
fix(slack): upload agent avatars directly during Cloud setup (#15566)
## Thinking Path > - Paperclip helps people manage AI agents for work. > - Slack setup creates a dedicated bot for an agent. > - The setup should upload that agent's avatar. > - The current upload asks Slack to fetch an image from the board origin. > - Cloud requires a tenant session at that origin, so Slack receives HTTP 401. > - This change renders the PNG on the server and uploads the file directly. ## Linked Issues or Issue Description Refs #15413. **What happened?** Automatic Slack setup left the app and bot with default icons on Cloud staging. An unauthenticated request to the exact avatar URL returned HTTP 401 with `tenant_session_required`. Local setup did not expose this Cloud ingress requirement. **Expected behavior** New Slack bots receive the assigned agent's 512-pixel avatar with the Paperclip dark background. **Steps to reproduce** 1. Create a Slack app through automatic setup on a Cloud tenant. 2. Complete installation. 3. Inspect the bot avatar in Slack. The previous URL-based upload cannot fetch the image without a tenant session. ## What Changed - Render the assigned agent's preset PNG with the existing bounded worker pool. - Send PNG bytes as multipart `file` data to `apps.icon.set` instead of passing a board URL. - Keep the temporary token in the Authorization header. Let fetch set the multipart boundary. - Recheck management permission and credential-lease ownership after rendering. Close the worker pool during chat service shutdown. - Cover actual PNG dimensions, uploaded bytes, failure recovery, and secret-safe responses. Update deployment documentation. ## Verification - Passed: 84 focused tests across automatic Slack registration and on-demand agent avatars. - Passed: full repository build. - Passed: full repository typecheck. All 54 current-head GitHub checks passed, including the complete test matrix, all browser shards, build, typecheck, canary, and security checks. Greptile completed on `79e79f6fc` with 5/5 and no actionable findings or open review threads. - The Cloud fetch failure was reproduced without browser credentials. No Cloud access rule was changed. - A real Slack upload with this new path still requires deployment and a fresh automatic setup. Existing apps retain the manual avatar-upload fallback. ## Risks - The renderer can time out or Slack can reject the upload. Both failures preserve the saved app and leave installation usable. - The renderer adds a bounded, lazy worker pool to Slack registration. Shutdown closes it. - No migration, bot permissions, credential retention, or Cloud authentication behavior changes. ## Model Used OpenAI Codex, GPT-6 family, with reasoning, repository tools, code execution, and browser inspection. The runtime does not expose a more specific authoring 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:
1 parent
2f0c485dec
commit
f47614046d
4 files changed
+66
-18
No files matched your search
@@ -4059,14 +4059,16 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => {
|
||||
return fallback(input, init);
|
||||
});
|
||||
const sdk = new FakeChatSdkRuntime();
|
||||
const { service } = createService(sdk, provider, overrides);
|
||||
const avatarBytes = Buffer.from("synthetic-png-bytes");
|
||||
const renderAvatar = vi.fn(async () => avatarBytes);
|
||||
const { service } = createService(sdk, provider, { renderSlackAvatar: renderAvatar, ...overrides });
|
||||
const endpoint = await service.create(company.companyId, { provider: "slack", assignedAgentId: company.assignedAgentId }, actor.userId);
|
||||
await service.update(endpoint.id, { slackApp: appDetails }, actor.userId);
|
||||
const app = routesApp(db, company.companyId, service);
|
||||
const createInput = { requestId: randomUUID(), credentials: { configurationToken: configToken } };
|
||||
const create = (input = createInput) => service.slackRegistration.create(endpoint.id, actor, input);
|
||||
const install = async () => new URL((await service.slackRegistration.install(endpoint.id, actor)).authorizationUrl).searchParams.get("state")!;
|
||||
return { ...company, endpoint, service, sdk, app, state, provider, create, install, createInput, token, appId, botId, installerId };
|
||||
return { ...company, endpoint, service, sdk, app, state, provider, create, install, createInput, token, appId, botId, installerId, avatarBytes, renderAvatar };
|
||||
}
|
||||
function setupEvent(f: Awaited<ReturnType<typeof fixture>>, patch: Record<string, unknown> = {}, url = f.endpoint.setup.webhookUrl!, secret = signingSecret, timestamp?: string) {
|
||||
return signedSlackWebhookRequest({ url, contentType: "application/json", signingSecret: secret, ...(timestamp ? { timestamp } : {}),
|
||||
@@ -4136,7 +4138,7 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => {
|
||||
for (const canary of [configToken, signingSecret, clientSecret, f.token]) expect(publicState).not.toContain(canary);
|
||||
await request(f.app).patch(`/api/chat-endpoints/${f.endpoint.id}`).send({ slackApp: appDetails }).expect(409);
|
||||
});
|
||||
it("uploads the assigned agent's public avatar only after the app credentials are durable", async () => {
|
||||
it("uploads avatar bytes without fetching a tenant-session-protected URL, after app credentials are durable", async () => {
|
||||
const f = await fixture();
|
||||
await db.update(agents).set({ appearance: { schemaVersion: 1, characterVersion: "cap-v1", paletteId: "cherry-pop" } }).where(eq(agents.id, f.assignedAgentId));
|
||||
f.state.beforeIcon = async () => {
|
||||
@@ -4148,10 +4150,40 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => {
|
||||
await f.create();
|
||||
const [, init] = f.provider.mock.calls.find(([url]) => String(url).endsWith("apps.icon.set"))!;
|
||||
expect(init).toMatchObject({ method: "POST", redirect: "error", headers: { authorization: `Bearer ${configToken}` } });
|
||||
const fields = new URLSearchParams(String(init!.body));
|
||||
expect(Object.fromEntries(fields)).toEqual({ app_id: f.appId, url: "https://paperclip.example/api/agent-avatars/cap-v1/cherry-pop/rest.png?size=512&scale=1&background=paperclip-dark" });
|
||||
expect(f.renderAvatar).toHaveBeenCalledWith({ appearance: { schemaVersion: 1, characterVersion: "cap-v1", paletteId: "cherry-pop" },
|
||||
size: 512, scale: 1, pose: "rest", muted: false, background: "paperclip-dark" });
|
||||
expect(init!.body).toBeInstanceOf(FormData);
|
||||
const fields = init!.body as FormData;
|
||||
expect(fields.get("app_id")).toBe(f.appId);
|
||||
expect(fields.has("url")).toBe(false);
|
||||
expect(fields.has("token")).toBe(false);
|
||||
expect(init!.headers).not.toHaveProperty("content-type"); // fetch sets the multipart boundary.
|
||||
const file = fields.get("file") as File;
|
||||
expect(file.type).toBe("image/png");
|
||||
expect(file.name).toBe("agent-avatar.png");
|
||||
expect(Buffer.from(await file.arrayBuffer())).toEqual(f.avatarBytes);
|
||||
expect(f.provider.mock.calls.every(([url]) => !String(url).includes("/agent-avatars/"))).toBe(true);
|
||||
expect((await request(f.app).get(`/api/chat-endpoints/${f.endpoint.id}`).expect(200)).body.setup.slackAvatar.status).toBe("uploaded");
|
||||
});
|
||||
it("uploads a real 512-pixel PNG from the production renderer", async () => {
|
||||
const f = await fixture({ renderSlackAvatar: undefined });
|
||||
await f.create();
|
||||
const [, init] = f.provider.mock.calls.find(([url]) => String(url).endsWith("apps.icon.set"))!;
|
||||
const file = (init!.body as FormData).get("file") as File;
|
||||
const png = Buffer.from(await file.arrayBuffer());
|
||||
expect(png.subarray(0, 8)).toEqual(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]));
|
||||
expect(png.readUInt32BE(16)).toBe(512);
|
||||
expect(png.readUInt32BE(20)).toBe(512);
|
||||
expect((await f.service.get(f.endpoint.id)).setup.slackAvatar?.status).toBe("uploaded");
|
||||
});
|
||||
it("keeps the saved app installable after local avatar rendering fails", async () => {
|
||||
const f = await fixture({ renderSlackAvatar: async () => { throw new Error("render failed"); } });
|
||||
await f.create();
|
||||
expect((await f.service.get(f.endpoint.id)).setup.slackAvatar).toEqual({ status: "failed", errorCode: "slack_avatar_upload_failed" });
|
||||
expect(f.provider.mock.calls.some(([url]) => String(url).endsWith("apps.icon.set"))).toBe(false);
|
||||
await expect(f.install()).resolves.toMatch(/^slack-install\./);
|
||||
expect(f.provider.mock.calls.filter(([url]) => String(url).endsWith("apps.manifest.create"))).toHaveLength(1);
|
||||
});
|
||||
it.each(["failIcon", "timeoutIcon"] as const)("keeps installation usable after %s without leaking provider echoes or creating another app", async failure => {
|
||||
const f = await fixture();
|
||||
f.state[failure] = true;
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { chatCredentialMutationLease, CREDENTIAL_MUTATION_LEASE_TTL_MS, type CredentialMutationLeaseGuard } from "./chat-credential-mutation-lease.js";
|
||||
import type { AgentAvatarRequest } from "./agent-avatars.js";
|
||||
import { slackChatRegistrationService, slackRegistrationProjection } from "./chat-slack-registration.js";
|
||||
import { chatSlackRegistrations } from "@paperclipai/db";
|
||||
import { SLACK_CHAT_BOT_SCOPES } from "@paperclipai/shared";
|
||||
@@ -1525,6 +1526,7 @@ export interface ChatChannelServiceOptions {
|
||||
actionId: string;
|
||||
claimId: string;
|
||||
}) => Promise<void>;
|
||||
renderSlackAvatar?: (request: AgentAvatarRequest) => Promise<Buffer>;
|
||||
storage?: StorageService;
|
||||
}
|
||||
|
||||
@@ -38130,7 +38132,7 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) {
|
||||
}
|
||||
|
||||
const slackRegistration = slackChatRegistrationService(db, {
|
||||
publicOrigin: getPublicBaseUrl, webhookOrigin: getWebhookPublicBaseUrl, fetch: fetchImpl,
|
||||
publicOrigin: getPublicBaseUrl, webhookOrigin: getWebhookPublicBaseUrl, fetch: fetchImpl, renderAvatar: options.renderSlackAvatar,
|
||||
withLock: async (endpointId, work) => {
|
||||
const record = await endpointRecord(endpointId);
|
||||
if (!record) throw notFound("Chat endpoint not found");
|
||||
@@ -38400,6 +38402,7 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) {
|
||||
// Stop every provider runtime before releasing leader rows. This gives a
|
||||
// standby an immediate takeover path without overlapping Gateway sockets.
|
||||
await runtime.shutdown();
|
||||
await slackRegistration.close();
|
||||
await Promise.all(
|
||||
ownedDiscordGateways.map((ownership) =>
|
||||
releaseDiscordGatewayLeaseRow(ownership),
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
import { createAgentAvatarPool } from "./agent-avatar-pool.js";
|
||||
import type { AgentAvatarRequest } from "./agent-avatars.js";
|
||||
import { removeSlackRegistration } from "./chat-slack-registration-cleanup.js";
|
||||
import { createHash, randomBytes } from "node:crypto";
|
||||
import { and, eq, gt, inArray, like, sql } from "drizzle-orm";
|
||||
import { agents, chatEndpoints, chatSlackRegistrations, companies, toolConnections, toolOauthStates, type Db } from "@paperclipai/db";
|
||||
import { agentAvatarUrl, resolveAgentAppearance, buildSlackAppManifest, slackAppConfigurationSchema, slackRegistrationErrorMessage, type SlackRegistrationInput, type SlackRegistrationState, type SlackAvatarState, type SlackAccountState } from "@paperclipai/shared";
|
||||
import { resolveAgentAppearance, buildSlackAppManifest, slackAppConfigurationSchema, slackRegistrationErrorMessage, type SlackRegistrationInput, type SlackRegistrationState, type SlackAvatarState, type SlackAccountState } from "@paperclipai/shared";
|
||||
import { badRequest, conflict, forbidden, notFound, unprocessable } from "../errors.js";
|
||||
import { accessService } from "./access.js";
|
||||
import { logActivity } from "./activity-log.js";
|
||||
@@ -39,6 +41,7 @@ export function slackChatRegistrationService(db: Db, options: {
|
||||
publicOrigin: () => string | null;
|
||||
webhookOrigin: () => string | null;
|
||||
fetch?: typeof fetch;
|
||||
renderAvatar?: (request: AgentAvatarRequest) => Promise<Buffer>;
|
||||
withLock: <T>(endpointId: string, work: (lease: CredentialMutationLeaseGuard) => Promise<T>) => Promise<T>;
|
||||
runtimeSigningSecret: (endpointId: string) => Promise<string>;
|
||||
runtimeBotToken: (endpointId: string) => Promise<string>;
|
||||
@@ -48,6 +51,7 @@ export function slackChatRegistrationService(db: Db, options: {
|
||||
}) {
|
||||
const fetchImpl = options.fetch ?? fetch;
|
||||
const vault = secretService(db);
|
||||
let avatarPool: ReturnType<typeof createAgentAvatarPool> | undefined;
|
||||
function origin(value: string | null) {
|
||||
if (!value) throw badRequest("Configure a public HTTPS URL before creating a Slack app");
|
||||
const url = new URL(value);
|
||||
@@ -81,11 +85,11 @@ export function slackChatRegistrationService(db: Db, options: {
|
||||
action: `chat_slack.${action}`, entityType: "chat_endpoint", entityId: row.endpointId,
|
||||
details: { endpointId: row.endpointId, appId: row.appId, ...(code ? { code } : {}) } });
|
||||
}
|
||||
async function api(method: string, fields: Record<string, string>, bearer?: string) {
|
||||
async function api(method: string, fields: Record<string, string> | FormData, bearer?: string) {
|
||||
const response = await fetchImpl(`https://slack.com/api/${method}`, {
|
||||
method: "POST", redirect: "error", signal: AbortSignal.timeout(timeoutMs),
|
||||
headers: { "content-type": "application/x-www-form-urlencoded", ...(bearer ? { authorization: `Bearer ${bearer}` } : {}) },
|
||||
body: new URLSearchParams(fields),
|
||||
headers: { ...(fields instanceof FormData ? {} : { "content-type": "application/x-www-form-urlencoded" }), ...(bearer ? { authorization: `Bearer ${bearer}` } : {}) },
|
||||
body: fields instanceof FormData ? fields : new URLSearchParams(fields),
|
||||
});
|
||||
const result = object(await response.json());
|
||||
if (!response.ok || result.ok !== true) {
|
||||
@@ -211,9 +215,17 @@ export function slackChatRegistrationService(db: Db, options: {
|
||||
try {
|
||||
await endpoint(endpointId, actor);
|
||||
await lease.assertOwned();
|
||||
// Public preset artwork from our configured origin; never accept a caller's URL.
|
||||
const imageUrl = new URL(agentAvatarUrl(resolveAgentAppearance(current.agentAppearance, current.endpoint.assignedAgentId), 512, 1, "rest", false, "paperclip-dark"), origin(options.publicOrigin())).href;
|
||||
await api("apps.icon.set", { app_id: createdAppId, url: imageUrl }, input.credentials.configurationToken);
|
||||
// Cloud ingress requires a tenant session. Send the preset PNG bytes so
|
||||
// Slack does not need to fetch an authenticated Paperclip URL.
|
||||
const render = options.renderAvatar ?? (avatarPool ??= createAgentAvatarPool()).render;
|
||||
const png = await render({ appearance: resolveAgentAppearance(current.agentAppearance, current.endpoint.assignedAgentId),
|
||||
size: 512, scale: 1, pose: "rest", muted: false, background: "paperclip-dark" });
|
||||
await endpoint(endpointId, actor);
|
||||
await lease.assertOwned();
|
||||
const upload = new FormData();
|
||||
upload.set("app_id", createdAppId);
|
||||
upload.set("file", new Blob([new Uint8Array(png)], { type: "image/png" }), "agent-avatar.png");
|
||||
await api("apps.icon.set", upload, input.credentials.configurationToken);
|
||||
avatar = { status: "uploaded", uploadedAt: new Date().toISOString() };
|
||||
} catch {
|
||||
// Provider echoes (including tokens) never become saved state or activity.
|
||||
@@ -492,5 +504,6 @@ export function slackChatRegistrationService(db: Db, options: {
|
||||
return `/${encodeURIComponent(row.prefix)}/apps/chat/connect?provider=slack&resume=${encodeURIComponent(endpointId)}`;
|
||||
}
|
||||
return { create, install, pending, expiredReturn, complete, cleanup, returnPath, registration, notifyVerified, processPendingVerificationMessages,
|
||||
close: async () => { await avatarPool?.close(); },
|
||||
resume: (endpointId: string, actor: SlackSetupActor) => options.withLock(endpointId, lease => resumeLocked(endpointId, actor, lease)) };
|
||||
}
|
||||
Reference in new issue
Block a user