mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-02 19:08:33 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - People also ask agents for work in their existing chat tools. > - Each external conversation needs one task and a current authorized source. > - Retries, Stop, and provider failures must not duplicate work or expose private data. > - The first chat PR establishes the opt-in provider and data contracts. > - This PR adds experimental channel integration and its durable control plane. > - Users can request work from connected channels and inspect delivery in Paperclip. ## Linked Issues or Issue Description Refs #13100 and #13092. This is the second of exactly two chat PRs. Foundation #13100 is merged and changed 143 files. Runner prerequisite #13092 is also merged. This PR changes 400 files against master, below the 500-file review limit. It contains no wireframe images or HTML galleries. ## What Changed - Add native Slack, GitHub, Microsoft Teams, Telegram, and Discord chat connections. Keep chat disabled unless the operator enables experimental chat connectors. Preserve the production GitHub tool connection and its normal setup path. - Bind each provider bot identity to one immutable Paperclip agent. Bind each admitted external conversation to one task. Paperclip owns tasks, runs, permissions, and audit records. - Add durable admission, per-conversation queues, questions, task controls, progress, final replies, images, files, and delivery receipts. Board comments remain internal unless explicitly sent to the channel. - Check current identity, provider reach, resource access, credentials, runtime generation, and exact source before provider effects. Keep private responses private. Never send raw reasoning, private logs, credentials, or tool arguments. - Hold uncertain sends for explicit audited resolution. Make Board Send-to-channel atomic and idempotent. Keep reconnect and setup credentials in Paperclip secret storage. - Preserve current native-runner authority across retries, lost acknowledgements, and recovery. Keep immutable input and completion contracts separate from newer user input. Receipt reconciliation cannot launch a provider. - Reconcile chat close/new ordering and provider-effect lock order. Audit resource access changes in the same transaction. Submit only the selected resource from each UI toggle so stale pages cannot undo unrelated access changes. - Drain Codex stdout before certifying process exit. Bound the drain with the existing shutdown grace. Preserve observed terminal authority without treating an undrained process as successful or reusable. - Incorporate master `018ca5da` with its ACP Stop, mobile task layout, runner packaging, and official lock changes. Preserve dedicated chat-answer continuations in both directions when ordinary queued comments are adopted after Stop. - Fence late adapter readiness behind an earlier Stop for the same run. Preserve verified cleanup for registered adapters. Handle single Stop, agent pause, duplicate Stops, and failure release without creating a false cancellation receipt. - Incorporate master's `6dd48cad4` wake-queue extraction. Preserve exact failed-chat retry authorization and lineage, retired question-source suppression, and the block on generic recovery that would discard the admitted source. Fresh deferred input retains its separate promotion path. - Incorporate master `2a05b5ed3` and its queue-admission extraction, simplified transaction ports, and separate runner CI job. Preserve exact durable receipts, actor separation, and dedicated-answer isolation through the new module. A failed receipt insert rolls back the accompanying deferred-wake merge. ## Verification Current head: `afe19299d06253cb628eb398e91d1200ea9f412a`, incorporating master `2a05b5ed3457ea33efd6895520447d1d97fe98d8`. The conflicts are resolved. This successor fixes two test-harness boundaries exposed by CI: per-case route-module preparation and actual durable-save completion before intentional runner termination. Production code and all existing test/turn deadlines are unchanged. [Exact-head Greptile review](https://github.com/paperclipai/paperclip/pull/13038#issuecomment-5587250594) is **5/5**, completed September 10 at 13:20:55 UTC, with no actionable findings or open review threads. [Fresh exact-head CI](https://github.com/paperclipai/paperclip/actions/runs/34481724341) passes **all 24 jobs**, including Build and both required aggregates. Normal exact-head guarded merge was attempted and rejected by the remaining branch approval policy: CODEOWNER review is required and no human approval is present. Normal **squash auto-merge is enabled** as of September 10 at 13:36:26 UTC. Requested CODEOWNERS have been notified; no approval bypass or self-approval was used. Earlier-head results below remain historical evidence, not qualification of this successor. - Final exact-head Linux evidence: 995/995 chat integration cases; 36/36 agent-skills routes; 35/35 runner live-session cases, including real process kill/resume; 1948 runner Vitest cases with three existing benchmark/platform guards; 870/870 API-authority cases; and 104 browser cases with four existing optional skips. Rust, conformance/replay, full repository build, typecheck, canary, all server/workspace shards, and both required aggregates pass with normal CI concurrency. Earlier failed attempts remain recorded below. - Latest test-only qualification: 141/141 route/permissions/authentication cases pass in separate cold forks, with plain server types and independent review clear. The real-runner suite passes 35/35, with plain runner types and independent review clear. A controlled premature-save acknowledgement fails as expected; matching ownership/effect/process evidence, rejected saves, real turn outcome, test abort, and pre-kill liveness are covered. No local reproduction of the original CI scheduling failure is claimed. The preceding [CI run](https://github.com/paperclipai/paperclip/actions/runs/34479680858) passes 21/24 jobs, including all 995 Linux chat cases and browser aggregate (104 passed, four existing optional skips); only Build, the skills serialized shard, and the required verification aggregate fail. Its exact-head Greptile review was 5/5. Both failed job logs are retained. - Final fixture qualification: all eight focused Discord cases and all 995 chat integration cases pass. The exact modal statement/PID is observed before taking the real connection lock; the test then proves its actual blocking relationship before mutation. Original SQL execution, provider behavior, negative assertions, and 1s/15s timeouts remain unchanged. Independent review is clear and test/production hashes remain frozen. The preceding [CI attempt](https://github.com/paperclipai/paperclip/actions/runs/34477184777) passed 22 jobs, including Build/runner, typecheck, canary, all other test shards, and browser aggregate (104 passed, four existing optional skips); the two fixture failures and failed verification aggregate remain recorded, not relabeled as a pass. - Current queue-module composition: 308/308 recovery/batching/queue/Stop tests; 995/995 full chat integration; 89/89 module tests, including real PostgreSQL receipt-insert rollback; 24/24 workflow/module-boundary tests; plain server and UI types. All four actual local process/ACP browser paths pass in 1.4 minutes. Fresh databases, no skips or retries, stable reviewed source hashes. The initial boundary failure is retained; its no-op service wrapper was removed without changing recovery context or weakening the check. An exploratory standalone test-directory typecheck fails because its new upstream transformation config is not a standalone typechecking project; standard CI/build does not invoke it, and no configuration was weakened to suppress those diagnostics. - The preceding head `e02a63d462ce5d47433b0aeb632bb6fd20aab1ba` passed [all 24 CI jobs](https://github.com/paperclipai/paperclip/actions/runs/34436462958) and exact-head Greptile review at 5/5. Required CODEOWNER review prevented its normal merge before master advanced again. - Final extracted-module composition: 307/307 recovery, batching, queue and Stop-control tests; 995/995 full chat integration; 49/49 module tests including eight PostgreSQL adapter cases; and 19/19 issue-update tests. Plain server types pass. All four actual local process/ACP browser paths pass in 1.3 minutes. Fresh databases, no skips or retries in these cohorts, frozen source hashes, and independent review clear. - The preceding head `3e4e1c1c` passes [all PR CI jobs](https://github.com/paperclipai/paperclip/actions/runs/34415826820), including Build and required `ci / verify` and `ci / e2e`. Both the original Rust failure and the previously load-sensitive lineage fixture pass with unchanged Linux concurrency. Master advanced afterward and required this reconciliation. - Final master composition: 448/448 focused UI tests, 186/186 adapter tests, 24/24 queue/control tests, and 11/11 packaging tests. Plain UI, server, shared, and adapter types pass. Token gates and diff checks pass. Independent server and UI reviews are clear. - Stop-registration regression: both real-service cases fail against exact `a95` source and pass with the fix. The full corrected recovery/control suite passes 265/265. Duplicate-owner and failed-Stop controls also pass. Plain server types pass. The readiness barrier prevents provider startup without adding an acknowledgment to an already terminal run. - Final qualification strengthens terminal-field equality and repeats both affected cases successfully on a fresh database. All four actual local process/ACP browser paths pass again in 1.3 minutes, without skips or retries. The final screenshot shows Cancelled, a paused subtree, retained input, and no error toast. - Two new actual-service regressions fail before the merge fix. They prove that queued-comment adoption could consume a dedicated chat answer or add unrelated input to that answer. The fixed four-case cohort passes, including ordinary upstream continuation and adapter Stop controls. Full recovery passes 257/257. All four actual local process/ACP Stop browser flows pass in 1.4 minutes, without skips or retries, on a fresh database. - The unchanged runner artifact was qualified with 171/171 transport tests, 870/870 API-authority tests, conformance 1/1, and replay 11/11. Six controlled reader tests prove the exit/drain repair. Its local serial Rust workspace passed 546 top-level cases plus two invoked helpers; the later passing Linux CI supplies default-concurrency evidence. - Prior exact-source full chat integration passes 995/995. Settings regressions cover concurrent stale pages, 501 destinations, pending state, rejected updates, and explicit retry. These deterministic tests do not prove live provider behavior. - Retained failed attempts and their causes are in the [qualification log](https://github.com/paperclipai/paperclip/blob/afe19299d06253cb628eb398e91d1200ea9f412a/doc/plans/chat-adapters/2026-09-08-chat-queue-and-webhook-repair.md). The first merge adapter run timed out while macOS slept for 290 seconds. Its unchanged repeat passed with a temporary sleep guard. No assertion, deadline, or CI gate was weakened. Review commands include `pnpm --filter @paperclipai/server exec vitest run src/__tests__/heartbeat-process-recovery.test.ts src/__tests__/issue-queued-comments-routes.test.ts` and `pnpm exec playwright test --config tests/e2e/playwright.config.ts tests/e2e/acp-stop-continuation.spec.ts`. Database suites require fresh disposable databases. See the [browser runbook](https://github.com/paperclipai/paperclip/blob/afe19299d06253cb628eb398e91d1200ea9f412a/doc/plans/chat-adapters/2026-09-04-chat-adapters-browser-e2e-runbook.md) for provider setup and separate live acceptance steps. ## Risks - This remains experimental. Deterministic tests and bounded live evidence do not establish every provider feature, tenant, permission layout, or media shape. Teams work-tenant qualification is still open. - Failed and uncertain provider effects remain visible and can require operator action. A transport receipt does not prove recipient visibility. - Native controller and runner artifacts must remain compatible. Preserve lease ownership, terminal authority, source binding, and quarantine during future changes. - Access and audit rows commit together, but activity notifications remain best-effort. This is not a new durable event outbox. - The PR operation does not deploy a live server, replace its runner, or change provider permissions. Remaining live qualification is documented in the [temporary handoff](https://github.com/paperclipai/paperclip/blob/afe19299d06253cb628eb398e91d1200ea9f412a/doc/plans/chat-adapters/2026-09-08-open-qualification-followups.md). ## Model Used OpenAI Codex assisted with implementation, tool execution, testing, and review. The work records `gpt-6-astra` assistance. The environment does not report a context-window size. No private reasoning traces are included. ## 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>
1132 lines
35 KiB
TypeScript
1132 lines
35 KiB
TypeScript
import { createHash, randomUUID } from "node:crypto";
|
|
import { mkdir, mkdtemp } from "node:fs/promises";
|
|
import { tmpdir } from "node:os";
|
|
import path from "node:path";
|
|
|
|
import { eq } from "drizzle-orm";
|
|
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
|
import {
|
|
activityLog,
|
|
agents,
|
|
assets,
|
|
chatConversations,
|
|
chatDeliveries,
|
|
chatEndpointResources,
|
|
chatEndpoints,
|
|
chatExternalPrincipals,
|
|
chatIdentityLinks,
|
|
chatMessageLinks,
|
|
chatPublications,
|
|
companies,
|
|
companyMemberships,
|
|
createDb,
|
|
heartbeatRuns,
|
|
issueAttachments,
|
|
issueComments,
|
|
issues,
|
|
issueWorkProducts,
|
|
toolApplications,
|
|
toolConnections,
|
|
} from "@paperclipai/db";
|
|
|
|
import { startEmbeddedPostgresTestDatabase } from "../../__tests__/helpers/embedded-postgres.js";
|
|
import { createLocalDiskStorageProvider } from "../../storage/local-disk-provider.js";
|
|
import { createStorageService } from "../../storage/service.js";
|
|
import type { StorageService } from "../../storage/types.js";
|
|
import { issueService } from "../issues.js";
|
|
import { mergeHeartbeatRunResultJson } from "../heartbeat-run-summary.js";
|
|
import {
|
|
prepareReusedChatAttachment,
|
|
resolveExternalChatResponseWaitAuthorization,
|
|
type ChatAttachmentReuseSource,
|
|
} from "./chat-attachment-reuse.js";
|
|
import { PaperclipRunnerToolAuthority } from "./paperclip-runner-tool-authority.js";
|
|
|
|
describe("native same-conversation chat attachment reuse", () => {
|
|
let temporary: Awaited<
|
|
ReturnType<typeof startEmbeddedPostgresTestDatabase>
|
|
> | null = null;
|
|
let db: ReturnType<typeof createDb>;
|
|
let storage: ReturnType<typeof createStorageService>;
|
|
|
|
const companyId = "10000000-0000-4000-8000-000000000101";
|
|
const agentId = "10000000-0000-4000-8000-000000000102";
|
|
const issueId = "10000000-0000-4000-8000-000000000103";
|
|
const runId = "10000000-0000-4000-8000-000000000104";
|
|
const endpointId = "10000000-0000-4000-8000-000000000105";
|
|
const conversationId = "10000000-0000-4000-8000-000000000106";
|
|
const resourceId = "10000000-0000-4000-8000-000000000107";
|
|
const principalId = "10000000-0000-4000-8000-000000000108";
|
|
const userId = "chat-user-1";
|
|
let currentCommentId: string;
|
|
let sourceCommentId: string;
|
|
let sourceAttachmentId: string;
|
|
const sourceBody = Buffer.from(
|
|
"same-conversation historical bytes\n",
|
|
"utf8",
|
|
);
|
|
|
|
beforeAll(async () => {
|
|
temporary = await startEmbeddedPostgresTestDatabase("native-chat-reuse-");
|
|
db = createDb(temporary.connectionString);
|
|
const storageRoot = await mkdtemp(
|
|
path.join(tmpdir(), "paperclip-chat-reuse-"),
|
|
);
|
|
await mkdir(storageRoot, { recursive: true });
|
|
storage = createStorageService(createLocalDiskStorageProvider(storageRoot));
|
|
await db.insert(companies).values({
|
|
id: companyId,
|
|
name: "Native chat attachment reuse",
|
|
issuePrefix: "NCR",
|
|
issueCounter: 1,
|
|
});
|
|
await db.insert(agents).values({
|
|
id: agentId,
|
|
companyId,
|
|
name: "Native chat agent",
|
|
adapterType: "paperclip_runner",
|
|
adapterConfig: { provider: "codex" },
|
|
runtimeConfig: {},
|
|
status: "active",
|
|
});
|
|
await db.insert(issues).values({
|
|
id: issueId,
|
|
companyId,
|
|
issueNumber: 1,
|
|
identifier: "NCR-1",
|
|
title: "Reuse the earlier file",
|
|
status: "in_progress",
|
|
workMode: "standard",
|
|
assigneeAgentId: agentId,
|
|
});
|
|
await db.insert(heartbeatRuns).values({
|
|
id: runId,
|
|
companyId,
|
|
agentId,
|
|
status: "running",
|
|
runtimeMode: "native",
|
|
nativeIssueId: issueId,
|
|
invocationSource: "assignment",
|
|
triggerDetail: "system",
|
|
contextSnapshot: {},
|
|
});
|
|
await db
|
|
.update(issues)
|
|
.set({ executionRunId: runId })
|
|
.where(eq(issues.id, issueId));
|
|
|
|
const applicationId = randomUUID();
|
|
const connectionId = randomUUID();
|
|
await db.insert(toolApplications).values({
|
|
id: applicationId,
|
|
companyId,
|
|
applicationKey: `chat:discord:${endpointId}`,
|
|
name: "Discord reuse",
|
|
type: "chat",
|
|
status: "active",
|
|
});
|
|
await db.insert(toolConnections).values({
|
|
id: connectionId,
|
|
companyId,
|
|
applicationId,
|
|
name: "Discord reuse",
|
|
uid: `chat-discord-${endpointId}`,
|
|
connectionPurpose: "channel",
|
|
transport: "chat_sdk",
|
|
status: "active",
|
|
enabled: true,
|
|
});
|
|
await db.insert(chatEndpoints).values({
|
|
id: endpointId,
|
|
companyId,
|
|
connectionId,
|
|
provider: "discord",
|
|
publicId: randomUUID(),
|
|
assignedAgentId: agentId,
|
|
status: "active",
|
|
providerAccountId: "guild-1",
|
|
allowUnlinkedPeople: false,
|
|
});
|
|
await db.insert(chatEndpointResources).values({
|
|
id: resourceId,
|
|
companyId,
|
|
endpointId,
|
|
type: "channel",
|
|
providerResourceId: "channel-1",
|
|
label: "#files",
|
|
availability: "available",
|
|
enabled: true,
|
|
});
|
|
await db.insert(chatConversations).values({
|
|
id: conversationId,
|
|
companyId,
|
|
endpointId,
|
|
resourceId,
|
|
issueId,
|
|
externalConversationId: "channel-1",
|
|
externalThreadId: "thread-1",
|
|
externalLabel: "#files thread",
|
|
state: "active",
|
|
});
|
|
await db.insert(chatExternalPrincipals).values({
|
|
id: principalId,
|
|
companyId,
|
|
provider: "discord",
|
|
providerAccountId: "guild-1",
|
|
externalId: "discord-user-1",
|
|
kind: "user",
|
|
});
|
|
await db.insert(chatIdentityLinks).values({
|
|
companyId,
|
|
endpointId,
|
|
principalId,
|
|
paperclipUserId: userId,
|
|
status: "linked",
|
|
});
|
|
await db.insert(companyMemberships).values({
|
|
companyId,
|
|
principalType: "user",
|
|
principalId: userId,
|
|
status: "active",
|
|
membershipRole: "member",
|
|
});
|
|
|
|
const sourceComment = await issueService(db).addComment(
|
|
issueId,
|
|
"The earlier upload",
|
|
{ userId },
|
|
);
|
|
sourceCommentId = sourceComment.id;
|
|
const stored = await storage.putFile({
|
|
companyId,
|
|
namespace: `issues/${issueId}`,
|
|
originalFilename: "earlier.txt",
|
|
contentType: "text/plain",
|
|
body: sourceBody,
|
|
});
|
|
const sourceAttachment = await issueService(db).createAttachment({
|
|
issueId,
|
|
issueCommentId: sourceCommentId,
|
|
provider: stored.provider,
|
|
objectKey: stored.objectKey,
|
|
contentType: stored.contentType,
|
|
byteSize: stored.byteSize,
|
|
sha256: stored.sha256,
|
|
originalFilename: stored.originalFilename,
|
|
createdByUserId: userId,
|
|
});
|
|
sourceAttachmentId = sourceAttachment.id;
|
|
const sourceDeliveryId = randomUUID();
|
|
await db.insert(chatDeliveries).values({
|
|
id: sourceDeliveryId,
|
|
companyId,
|
|
endpointId,
|
|
conversationId,
|
|
principalId,
|
|
providerEventId: "source-event",
|
|
deduplicationKey: "source-event",
|
|
eventKind: "message",
|
|
normalizedEvent: {},
|
|
state: "processed",
|
|
attempts: 1,
|
|
processedAt: new Date(),
|
|
});
|
|
await db.insert(chatMessageLinks).values({
|
|
companyId,
|
|
endpointId,
|
|
conversationId,
|
|
deliveryId: sourceDeliveryId,
|
|
commentId: sourceCommentId,
|
|
providerMessageId: "source-message",
|
|
direction: "inbound",
|
|
});
|
|
|
|
const currentComment = await issueService(db).addComment(
|
|
issueId,
|
|
"Please send that earlier file again",
|
|
{ userId },
|
|
);
|
|
currentCommentId = currentComment.id;
|
|
const currentDeliveryId = randomUUID();
|
|
await db.insert(chatDeliveries).values({
|
|
id: currentDeliveryId,
|
|
companyId,
|
|
endpointId,
|
|
conversationId,
|
|
principalId,
|
|
providerEventId: "current-event",
|
|
deduplicationKey: "current-event",
|
|
eventKind: "message",
|
|
normalizedEvent: {},
|
|
state: "processed",
|
|
attempts: 1,
|
|
processedAt: new Date(),
|
|
});
|
|
await db.insert(chatMessageLinks).values({
|
|
companyId,
|
|
endpointId,
|
|
conversationId,
|
|
deliveryId: currentDeliveryId,
|
|
commentId: currentCommentId,
|
|
providerMessageId: "current-message",
|
|
direction: "inbound",
|
|
});
|
|
await db
|
|
.update(heartbeatRuns)
|
|
.set({
|
|
contextSnapshot: {
|
|
source: "chat:discord",
|
|
paperclipHarnessCheckedOut: true,
|
|
wakeCommentIds: [currentCommentId],
|
|
commentId: currentCommentId,
|
|
paperclipWake: {
|
|
reason: "External chat message received",
|
|
externalChatProvider: "discord",
|
|
checkedOutByHarness: true,
|
|
issue: { id: issueId, workMode: "standard" },
|
|
commentIds: [currentCommentId],
|
|
},
|
|
},
|
|
})
|
|
.where(eq(heartbeatRuns.id, runId));
|
|
});
|
|
|
|
afterAll(async () => {
|
|
await temporary?.cleanup();
|
|
});
|
|
|
|
function authority() {
|
|
return new PaperclipRunnerToolAuthority(db, {
|
|
companyId,
|
|
agentId,
|
|
issueId,
|
|
runId,
|
|
executionTargetKind: "remote",
|
|
storage,
|
|
});
|
|
}
|
|
|
|
it("authorizes an external-chat response wait only from current durable policy", async () => {
|
|
const binding = { companyId, agentId, issueId, runId };
|
|
const alternateRunId = randomUUID();
|
|
const [run] = await db
|
|
.select({ contextSnapshot: heartbeatRuns.contextSnapshot })
|
|
.from(heartbeatRuns)
|
|
.where(eq(heartbeatRuns.id, runId));
|
|
await db.insert(heartbeatRuns).values({
|
|
id: alternateRunId,
|
|
companyId,
|
|
agentId,
|
|
status: "succeeded",
|
|
runtimeMode: "native",
|
|
nativeIssueId: issueId,
|
|
invocationSource: "assignment",
|
|
triggerDetail: "system",
|
|
contextSnapshot: {},
|
|
});
|
|
try {
|
|
await expect(
|
|
resolveExternalChatResponseWaitAuthorization({ db, binding }),
|
|
).resolves.toBe("authorized");
|
|
|
|
await db
|
|
.update(issues)
|
|
.set({ assigneeAgentId: null })
|
|
.where(eq(issues.id, issueId));
|
|
await expect(
|
|
resolveExternalChatResponseWaitAuthorization({ db, binding }),
|
|
).resolves.toBe("revoked");
|
|
await db
|
|
.update(issues)
|
|
.set({ assigneeAgentId: agentId, executionRunId: alternateRunId })
|
|
.where(eq(issues.id, issueId));
|
|
await expect(
|
|
resolveExternalChatResponseWaitAuthorization({ db, binding }),
|
|
).resolves.toBe("revoked");
|
|
await db
|
|
.update(issues)
|
|
.set({ executionRunId: runId })
|
|
.where(eq(issues.id, issueId));
|
|
await db
|
|
.update(heartbeatRuns)
|
|
.set({ status: "succeeded", updatedAt: new Date() })
|
|
.where(eq(heartbeatRuns.id, runId));
|
|
await expect(
|
|
resolveExternalChatResponseWaitAuthorization({ db, binding }),
|
|
).resolves.toBe("revoked");
|
|
await db
|
|
.update(heartbeatRuns)
|
|
.set({ status: "running", updatedAt: new Date() })
|
|
.where(eq(heartbeatRuns.id, runId));
|
|
|
|
await db
|
|
.update(companyMemberships)
|
|
.set({ status: "suspended", updatedAt: new Date() })
|
|
.where(eq(companyMemberships.principalId, userId));
|
|
await expect(
|
|
resolveExternalChatResponseWaitAuthorization({ db, binding }),
|
|
).resolves.toBe("revoked");
|
|
await db
|
|
.update(companyMemberships)
|
|
.set({ status: "active", updatedAt: new Date() })
|
|
.where(eq(companyMemberships.principalId, userId));
|
|
|
|
const spoofedContext = {
|
|
...((run?.contextSnapshot as Record<string, unknown> | null) ?? {}),
|
|
};
|
|
delete spoofedContext.paperclipWake;
|
|
await db
|
|
.update(heartbeatRuns)
|
|
.set({
|
|
contextSnapshot: spoofedContext,
|
|
updatedAt: new Date(),
|
|
})
|
|
.where(eq(heartbeatRuns.id, runId));
|
|
await expect(
|
|
resolveExternalChatResponseWaitAuthorization({ db, binding }),
|
|
).resolves.toBe("not_applicable");
|
|
} finally {
|
|
await db
|
|
.update(issues)
|
|
.set({ assigneeAgentId: agentId, executionRunId: runId })
|
|
.where(eq(issues.id, issueId));
|
|
await db
|
|
.update(heartbeatRuns)
|
|
.set({
|
|
status: "running",
|
|
contextSnapshot: run?.contextSnapshot ?? {},
|
|
updatedAt: new Date(),
|
|
})
|
|
.where(eq(heartbeatRuns.id, runId));
|
|
await db
|
|
.update(companyMemberships)
|
|
.set({ status: "active", updatedAt: new Date() })
|
|
.where(eq(companyMemberships.principalId, userId));
|
|
await db
|
|
.delete(heartbeatRuns)
|
|
.where(eq(heartbeatRuns.id, alternateRunId));
|
|
}
|
|
});
|
|
|
|
it("lists metadata only and clones exact bytes once into current-run provenance", async () => {
|
|
const runner = authority();
|
|
const listed = await runner.execute({
|
|
tool: "list_chat_attachments",
|
|
callId: "list",
|
|
arguments: { sourceCommentId, limit: 10 },
|
|
});
|
|
expect(listed).toEqual({
|
|
attachments: [
|
|
{
|
|
sourceCommentId,
|
|
attachmentId: sourceAttachmentId,
|
|
filename: "earlier.txt",
|
|
contentType: "text/plain",
|
|
byteSize: sourceBody.length,
|
|
sha256: createHash("sha256").update(sourceBody).digest("hex"),
|
|
createdAt: expect.any(String),
|
|
contentAccess: "metadata_only",
|
|
},
|
|
],
|
|
nextCursor: null,
|
|
complete: true,
|
|
});
|
|
expect(JSON.stringify(listed)).not.toContain("objectKey");
|
|
expect(JSON.stringify(listed)).not.toContain("/api/attachments/");
|
|
|
|
const call = {
|
|
tool: "reuse_chat_attachment",
|
|
callId: "reuse",
|
|
arguments: {
|
|
idempotencyKey: "reuse-earlier-v1",
|
|
sourceCommentId,
|
|
attachmentId: sourceAttachmentId,
|
|
title: "Earlier requested file",
|
|
},
|
|
};
|
|
const first = (await runner.execute(call)) as Record<string, unknown>;
|
|
const replay = await runner.execute({ ...call, callId: "reuse-replay" });
|
|
const duplicate = (await runner.execute({
|
|
...call,
|
|
callId: "reuse-new-key",
|
|
arguments: { ...call.arguments, idempotencyKey: "reuse-earlier-v2" },
|
|
})) as Record<string, unknown>;
|
|
expect(first).toMatchObject({
|
|
disposition: "applied",
|
|
source: { commentId: sourceCommentId, attachmentId: sourceAttachmentId },
|
|
prepared: {
|
|
attachmentId: expect.any(String),
|
|
workProductId: expect.any(String),
|
|
commentId: expect.any(String),
|
|
sha256: createHash("sha256").update(sourceBody).digest("hex"),
|
|
},
|
|
});
|
|
expect(replay).toEqual(first);
|
|
expect(duplicate).toMatchObject({
|
|
disposition: "duplicate",
|
|
prepared: (first as { prepared: unknown }).prepared,
|
|
});
|
|
const preparedId = (first as { prepared: { attachmentId: string } })
|
|
.prepared.attachmentId;
|
|
const attachments = await db
|
|
.select({
|
|
id: issueAttachments.id,
|
|
originatingRunId: issueAttachments.originatingRunId,
|
|
objectKey: assets.objectKey,
|
|
sha256: assets.sha256,
|
|
})
|
|
.from(issueAttachments)
|
|
.innerJoin(assets, eq(assets.id, issueAttachments.assetId))
|
|
.where(eq(issueAttachments.issueId, issueId));
|
|
expect(attachments).toHaveLength(2);
|
|
expect(attachments.find((row) => row.id === preparedId)).toMatchObject({
|
|
originatingRunId: runId,
|
|
sha256: createHash("sha256").update(sourceBody).digest("hex"),
|
|
});
|
|
const prepared = attachments.find((row) => row.id === preparedId)!;
|
|
const object = await storage.getObject(companyId, prepared.objectKey);
|
|
const chunks: Buffer[] = [];
|
|
for await (const chunk of object.stream) chunks.push(Buffer.from(chunk));
|
|
expect(Buffer.concat(chunks)).toEqual(sourceBody);
|
|
const [workProduct] = await db
|
|
.select()
|
|
.from(issueWorkProducts)
|
|
.where(eq(issueWorkProducts.externalId, preparedId));
|
|
expect(workProduct).toMatchObject({
|
|
createdByRunId: runId,
|
|
metadata: expect.objectContaining({
|
|
contentPath: `/api/attachments/${preparedId}/content`,
|
|
reusedFromAttachmentId: sourceAttachmentId,
|
|
reusedFromCommentId: sourceCommentId,
|
|
}),
|
|
});
|
|
const [run] = await db
|
|
.select({ resultJson: heartbeatRuns.resultJson })
|
|
.from(heartbeatRuns)
|
|
.where(eq(heartbeatRuns.id, runId));
|
|
const receipts = (
|
|
run.resultJson as {
|
|
semanticToolReceipts: Record<
|
|
string,
|
|
{
|
|
operationId: string;
|
|
input: unknown;
|
|
result: unknown;
|
|
}
|
|
>;
|
|
}
|
|
).semanticToolReceipts;
|
|
expect(receipts["reuse-earlier-v1"]).toMatchObject({
|
|
operationId: "reuse_chat_attachment",
|
|
input: call.arguments,
|
|
});
|
|
expect(receipts["reuse-earlier-v1"]?.result).toEqual(first);
|
|
expect(receipts["reuse-earlier-v2"]?.result).toEqual(duplicate);
|
|
const completedResult = mergeHeartbeatRunResultJson(
|
|
{
|
|
...(run.resultJson ?? {}),
|
|
nativeResult: {
|
|
schema: "paperclip.run_result.v1",
|
|
summary: "Prepared the earlier file again.",
|
|
},
|
|
},
|
|
"Prepared the earlier file again.",
|
|
);
|
|
await db
|
|
.update(heartbeatRuns)
|
|
.set({ resultJson: completedResult })
|
|
.where(eq(heartbeatRuns.id, runId));
|
|
const persistedCompletion = (
|
|
await db
|
|
.select({ resultJson: heartbeatRuns.resultJson })
|
|
.from(heartbeatRuns)
|
|
.where(eq(heartbeatRuns.id, runId))
|
|
)[0]?.resultJson as {
|
|
semanticToolReceipts: typeof receipts;
|
|
nativeResult: { summary: string };
|
|
};
|
|
expect(persistedCompletion.semanticToolReceipts).toEqual(receipts);
|
|
expect(persistedCompletion.nativeResult.summary).toBe(
|
|
"Prepared the earlier file again.",
|
|
);
|
|
const reuseActivity = (
|
|
await db.select().from(activityLog).where(eq(activityLog.runId, runId))
|
|
).find(
|
|
(row) => row.details?.source === "paperclip_runner_chat_attachment_reuse",
|
|
);
|
|
expect(reuseActivity?.details).toMatchObject({
|
|
sourceAttachmentId,
|
|
sourceCommentId,
|
|
attachmentId: preparedId,
|
|
});
|
|
});
|
|
|
|
it("bounds a stalled storage write and removes the late object without creating rows", async () => {
|
|
const [source] = await db
|
|
.select({
|
|
sourceCommentId: issueAttachments.issueCommentId,
|
|
attachmentId: issueAttachments.id,
|
|
filename: assets.originalFilename,
|
|
contentType: assets.contentType,
|
|
byteSize: assets.byteSize,
|
|
sha256: assets.sha256,
|
|
objectKey: assets.objectKey,
|
|
createdAt: issueAttachments.createdAt,
|
|
})
|
|
.from(issueAttachments)
|
|
.innerJoin(assets, eq(assets.id, issueAttachments.assetId))
|
|
.where(eq(issueAttachments.id, sourceAttachmentId));
|
|
if (!source?.sourceCommentId || !source.filename) {
|
|
throw new Error("source fixture missing");
|
|
}
|
|
let releaseWrite!: () => void;
|
|
const writeGate = new Promise<void>((resolve) => {
|
|
releaseWrite = resolve;
|
|
});
|
|
let resolveDeleted!: (objectKey: string) => void;
|
|
const deleted = new Promise<string>((resolve) => {
|
|
resolveDeleted = resolve;
|
|
});
|
|
const delayedStorage: StorageService = {
|
|
...storage,
|
|
putFile: async (input) => {
|
|
const stored = await storage.putFile(input);
|
|
await writeGate;
|
|
return stored;
|
|
},
|
|
deleteObject: async (targetCompanyId, objectKey) => {
|
|
await storage.deleteObject(targetCompanyId, objectKey);
|
|
resolveDeleted(objectKey);
|
|
},
|
|
};
|
|
const before = await db
|
|
.select({ id: issueAttachments.id })
|
|
.from(issueAttachments)
|
|
.where(eq(issueAttachments.issueId, issueId));
|
|
await expect(
|
|
prepareReusedChatAttachment({
|
|
db,
|
|
binding: { companyId, issueId, runId, agentId },
|
|
source: source as ChatAttachmentReuseSource,
|
|
title: "Must time out",
|
|
storage: delayedStorage,
|
|
storageTimeoutMs: 20,
|
|
}),
|
|
).rejects.toThrow(
|
|
"paperclip_runner_chat_attachment_storage_write_timed_out",
|
|
);
|
|
releaseWrite();
|
|
const deletedObjectKey = await Promise.race([
|
|
deleted,
|
|
new Promise<never>((_resolve, reject) =>
|
|
setTimeout(() => reject(new Error("late object was not removed")), 500),
|
|
),
|
|
]);
|
|
expect((await storage.headObject(companyId, deletedObjectKey)).exists).toBe(
|
|
false,
|
|
);
|
|
expect(
|
|
await db
|
|
.select({ id: issueAttachments.id })
|
|
.from(issueAttachments)
|
|
.where(eq(issueAttachments.issueId, issueId)),
|
|
).toEqual(before);
|
|
});
|
|
|
|
it("pages a stable deduplicated attachment history with equal timestamps", async () => {
|
|
const equalCreatedAt = new Date("2026-09-07T18:00:00.000Z");
|
|
const newAttachmentIds: string[] = [];
|
|
for (let index = 0; index < 3; index += 1) {
|
|
const comment = await issueService(db).addComment(
|
|
issueId,
|
|
`Historical upload ${index}`,
|
|
{ userId },
|
|
);
|
|
const body = Buffer.from(`historical-${index}\n`, "utf8");
|
|
const stored = await storage.putFile({
|
|
companyId,
|
|
namespace: `issues/${issueId}`,
|
|
originalFilename: `historical-${index}.txt`,
|
|
contentType: "text/plain",
|
|
body,
|
|
});
|
|
const attachment = await issueService(db).createAttachment({
|
|
issueId,
|
|
issueCommentId: comment.id,
|
|
provider: stored.provider,
|
|
objectKey: stored.objectKey,
|
|
contentType: stored.contentType,
|
|
byteSize: stored.byteSize,
|
|
sha256: stored.sha256,
|
|
originalFilename: stored.originalFilename,
|
|
createdByUserId: userId,
|
|
});
|
|
newAttachmentIds.push(attachment.id);
|
|
await db
|
|
.update(issueAttachments)
|
|
.set({ createdAt: equalCreatedAt })
|
|
.where(eq(issueAttachments.id, attachment.id));
|
|
const deliveryId = randomUUID();
|
|
await db.insert(chatDeliveries).values({
|
|
id: deliveryId,
|
|
companyId,
|
|
endpointId,
|
|
conversationId,
|
|
principalId,
|
|
providerEventId: `historical-event-${index}`,
|
|
deduplicationKey: `historical-event-${index}`,
|
|
eventKind: "message",
|
|
normalizedEvent: {},
|
|
state: "processed",
|
|
attempts: 1,
|
|
processedAt: new Date(),
|
|
});
|
|
await db.insert(chatMessageLinks).values({
|
|
companyId,
|
|
endpointId,
|
|
conversationId,
|
|
deliveryId,
|
|
commentId: comment.id,
|
|
providerMessageId: `historical-message-${index}`,
|
|
direction: "inbound",
|
|
});
|
|
}
|
|
const [publicationCommentA, publicationCommentB] = await Promise.all([
|
|
issueService(db).addComment(issueId, "Published file A", { userId }),
|
|
issueService(db).addComment(issueId, "Published file B", { userId }),
|
|
]);
|
|
for (const [index, comment] of [
|
|
publicationCommentA,
|
|
publicationCommentB,
|
|
].entries()) {
|
|
await db.insert(chatPublications).values({
|
|
companyId,
|
|
endpointId,
|
|
conversationId,
|
|
issueId,
|
|
commentId: comment.id,
|
|
idempotencyKey: `published-duplicate-${index}`,
|
|
payload: {
|
|
text: "Shared the earlier file.",
|
|
attachmentIds: [sourceAttachmentId],
|
|
},
|
|
state: "published",
|
|
providerMessageId: `published-message-${index}`,
|
|
publishedAt: new Date(),
|
|
});
|
|
}
|
|
const seen: string[] = [];
|
|
let cursor: string | null = null;
|
|
for (let pageNumber = 0; pageNumber < 4; pageNumber += 1) {
|
|
const page = (await authority().execute({
|
|
tool: "list_chat_attachments",
|
|
callId: `page-${pageNumber}`,
|
|
arguments: { limit: 2, cursor },
|
|
})) as {
|
|
attachments: Array<{ attachmentId: string }>;
|
|
nextCursor: string | null;
|
|
complete: boolean;
|
|
};
|
|
seen.push(
|
|
...page.attachments.map((attachment) => attachment.attachmentId),
|
|
);
|
|
cursor = page.nextCursor;
|
|
if (page.complete) break;
|
|
}
|
|
expect(new Set(seen)).toEqual(
|
|
new Set([sourceAttachmentId, ...newAttachmentIds]),
|
|
);
|
|
expect(seen).toHaveLength(4);
|
|
const invalidCursor = Buffer.from(
|
|
JSON.stringify({
|
|
schema: "paperclip.chat-attachment-list-cursor.v1",
|
|
conversationId,
|
|
sourceCommentId: null,
|
|
createdAt: equalCreatedAt.toISOString(),
|
|
attachmentId: "not-a-uuid",
|
|
sourceCommentIdTieBreak: "also-not-a-uuid",
|
|
}),
|
|
"utf8",
|
|
).toString("base64url");
|
|
await expect(
|
|
authority().execute({
|
|
tool: "list_chat_attachments",
|
|
callId: "malformed-cursor",
|
|
arguments: { cursor: invalidCursor },
|
|
}),
|
|
).rejects.toThrow("paperclip_runner_chat_attachment_cursor_invalid");
|
|
});
|
|
|
|
it("keeps an older confirmed lineage when a newer publication was deleted", async () => {
|
|
const stored = await storage.putFile({
|
|
companyId,
|
|
namespace: `issues/${issueId}`,
|
|
originalFilename: "published-twice.txt",
|
|
contentType: "text/plain",
|
|
body: Buffer.from("published twice\n", "utf8"),
|
|
});
|
|
const parent = await issueService(db).addComment(
|
|
issueId,
|
|
"Internal preparation parent",
|
|
{ userId },
|
|
);
|
|
const attachment = await issueService(db).createAttachment({
|
|
issueId,
|
|
issueCommentId: parent.id,
|
|
provider: stored.provider,
|
|
objectKey: stored.objectKey,
|
|
contentType: stored.contentType,
|
|
byteSize: stored.byteSize,
|
|
sha256: stored.sha256,
|
|
originalFilename: stored.originalFilename,
|
|
createdByUserId: userId,
|
|
});
|
|
const olderCommentId = "20000000-0000-4000-8000-000000000111";
|
|
const newerCommentId = "20000000-0000-4000-8000-000000000222";
|
|
await db.insert(issueComments).values([
|
|
{
|
|
id: olderCommentId,
|
|
companyId,
|
|
issueId,
|
|
authorType: "user",
|
|
authorUserId: userId,
|
|
body: "First confirmed publication",
|
|
},
|
|
{
|
|
id: newerCommentId,
|
|
companyId,
|
|
issueId,
|
|
authorType: "user",
|
|
authorUserId: userId,
|
|
body: "Later deleted publication",
|
|
},
|
|
]);
|
|
await db.insert(chatPublications).values([
|
|
{
|
|
companyId,
|
|
endpointId,
|
|
conversationId,
|
|
issueId,
|
|
commentId: olderCommentId,
|
|
idempotencyKey: "confirmed-published-older",
|
|
payload: { text: "First send", attachmentIds: [attachment.id] },
|
|
state: "published",
|
|
providerMessageId: "confirmed-older",
|
|
publishedAt: new Date("2026-09-07T18:01:00.000Z"),
|
|
},
|
|
{
|
|
companyId,
|
|
endpointId,
|
|
conversationId,
|
|
issueId,
|
|
commentId: newerCommentId,
|
|
idempotencyKey: "confirmed-published-newer",
|
|
payload: { text: "Second send", attachmentIds: [attachment.id] },
|
|
state: "published",
|
|
providerMessageId: "confirmed-newer",
|
|
publishedAt: new Date("2026-09-07T18:02:00.000Z"),
|
|
},
|
|
]);
|
|
await db.insert(chatDeliveries).values({
|
|
companyId,
|
|
endpointId,
|
|
conversationId,
|
|
principalId,
|
|
providerEventId: "delete-newer-publication",
|
|
deduplicationKey: "delete-newer-publication",
|
|
eventKind: "message_deleted",
|
|
normalizedEvent: {
|
|
message: { providerMessageId: "confirmed-newer" },
|
|
},
|
|
state: "processed",
|
|
attempts: 1,
|
|
processedAt: new Date(),
|
|
});
|
|
|
|
const page = (await authority().execute({
|
|
tool: "list_chat_attachments",
|
|
callId: "multi-lineage-list",
|
|
arguments: { limit: 50 },
|
|
})) as {
|
|
attachments: Array<{ attachmentId: string; sourceCommentId: string }>;
|
|
};
|
|
expect(
|
|
page.attachments.find(
|
|
(candidate) => candidate.attachmentId === attachment.id,
|
|
),
|
|
).toMatchObject({ sourceCommentId: olderCommentId });
|
|
await expect(
|
|
authority().execute({
|
|
tool: "reuse_chat_attachment",
|
|
callId: "deleted-newer-lineage",
|
|
arguments: {
|
|
idempotencyKey: "deleted-newer-lineage",
|
|
sourceCommentId: newerCommentId,
|
|
attachmentId: attachment.id,
|
|
title: "Deleted newer copy",
|
|
},
|
|
}),
|
|
).rejects.toThrow("paperclip_runner_chat_attachment_source_denied");
|
|
await expect(
|
|
authority().execute({
|
|
tool: "reuse_chat_attachment",
|
|
callId: "confirmed-older-lineage",
|
|
arguments: {
|
|
idempotencyKey: "confirmed-older-lineage",
|
|
sourceCommentId: olderCommentId,
|
|
attachmentId: attachment.id,
|
|
title: "Still confirmed older copy",
|
|
},
|
|
}),
|
|
).resolves.toMatchObject({ disposition: "applied" });
|
|
|
|
const unconfirmedStored = await storage.putFile({
|
|
companyId,
|
|
namespace: `issues/${issueId}`,
|
|
originalFilename: "unconfirmed.txt",
|
|
contentType: "text/plain",
|
|
body: Buffer.from("never confirmed\n", "utf8"),
|
|
});
|
|
const unconfirmedParent = await issueService(db).addComment(
|
|
issueId,
|
|
"Unconfirmed preparation parent",
|
|
{ userId },
|
|
);
|
|
const unconfirmedAttachment = await issueService(db).createAttachment({
|
|
issueId,
|
|
issueCommentId: unconfirmedParent.id,
|
|
provider: unconfirmedStored.provider,
|
|
objectKey: unconfirmedStored.objectKey,
|
|
contentType: unconfirmedStored.contentType,
|
|
byteSize: unconfirmedStored.byteSize,
|
|
sha256: unconfirmedStored.sha256,
|
|
originalFilename: unconfirmedStored.originalFilename,
|
|
createdByUserId: userId,
|
|
});
|
|
const unconfirmedComment = await issueService(db).addComment(
|
|
issueId,
|
|
"Publication row without provider confirmation",
|
|
{ userId },
|
|
);
|
|
await db.insert(chatPublications).values({
|
|
companyId,
|
|
endpointId,
|
|
conversationId,
|
|
issueId,
|
|
commentId: unconfirmedComment.id,
|
|
idempotencyKey: "unconfirmed-publication",
|
|
payload: {
|
|
text: "Not actually sent",
|
|
attachmentIds: [unconfirmedAttachment.id],
|
|
},
|
|
state: "published",
|
|
providerMessageId: null,
|
|
publishedAt: null,
|
|
});
|
|
expect(
|
|
await authority().execute({
|
|
tool: "list_chat_attachments",
|
|
callId: "unconfirmed-list",
|
|
arguments: { sourceCommentId: unconfirmedComment.id },
|
|
}),
|
|
).toEqual({ attachments: [], nextCursor: null, complete: true });
|
|
await expect(
|
|
authority().execute({
|
|
tool: "reuse_chat_attachment",
|
|
callId: "unconfirmed-reuse",
|
|
arguments: {
|
|
idempotencyKey: "unconfirmed-reuse",
|
|
sourceCommentId: unconfirmedComment.id,
|
|
attachmentId: unconfirmedAttachment.id,
|
|
title: "Must remain internal",
|
|
},
|
|
}),
|
|
).rejects.toThrow("paperclip_runner_chat_attachment_source_denied");
|
|
});
|
|
|
|
it("rejects forged source pairs, stale reach, and deleted historical sources", async () => {
|
|
const runner = authority();
|
|
const stored = await storage.putFile({
|
|
companyId,
|
|
namespace: `issues/${issueId}`,
|
|
originalFilename: "internal-only.txt",
|
|
contentType: "text/plain",
|
|
body: Buffer.from("internal only"),
|
|
});
|
|
const internalComment = await issueService(db).addComment(
|
|
issueId,
|
|
"Internal-only file",
|
|
{ userId: "internal-user" },
|
|
);
|
|
const internal = await issueService(db).createAttachment({
|
|
issueId,
|
|
issueCommentId: internalComment.id,
|
|
provider: stored.provider,
|
|
objectKey: stored.objectKey,
|
|
contentType: stored.contentType,
|
|
byteSize: stored.byteSize,
|
|
sha256: stored.sha256,
|
|
originalFilename: stored.originalFilename,
|
|
createdByUserId: "internal-user",
|
|
});
|
|
await expect(
|
|
runner.execute({
|
|
tool: "reuse_chat_attachment",
|
|
callId: "forged-pair",
|
|
arguments: {
|
|
idempotencyKey: "forged-pair",
|
|
sourceCommentId,
|
|
attachmentId: internal.id,
|
|
title: "Must not escape",
|
|
},
|
|
}),
|
|
).rejects.toThrow("paperclip_runner_chat_attachment_source_denied");
|
|
|
|
await db
|
|
.update(issues)
|
|
.set({ assigneeAgentId: null })
|
|
.where(eq(issues.id, issueId));
|
|
await expect(
|
|
runner.execute({
|
|
tool: "list_chat_attachments",
|
|
callId: "reassigned-list",
|
|
arguments: {},
|
|
}),
|
|
).rejects.toThrow("paperclip_runner_tool_binding_not_authorized");
|
|
await db
|
|
.update(issues)
|
|
.set({ assigneeAgentId: agentId })
|
|
.where(eq(issues.id, issueId));
|
|
|
|
await db
|
|
.update(chatEndpoints)
|
|
.set({ status: "paused" })
|
|
.where(eq(chatEndpoints.id, endpointId));
|
|
await expect(
|
|
runner.execute({
|
|
tool: "list_chat_attachments",
|
|
callId: "paused-endpoint-list",
|
|
arguments: {},
|
|
}),
|
|
).rejects.toThrow("paperclip_runner_chat_attachment_binding_denied");
|
|
await db
|
|
.update(chatEndpoints)
|
|
.set({ status: "active" })
|
|
.where(eq(chatEndpoints.id, endpointId));
|
|
|
|
await db
|
|
.update(companyMemberships)
|
|
.set({ status: "suspended" })
|
|
.where(eq(companyMemberships.principalId, userId));
|
|
await expect(
|
|
runner.execute({
|
|
tool: "reuse_chat_attachment",
|
|
callId: "revoked-principal-replay",
|
|
arguments: {
|
|
idempotencyKey: "reuse-earlier-v1",
|
|
sourceCommentId,
|
|
attachmentId: sourceAttachmentId,
|
|
title: "Earlier requested file",
|
|
},
|
|
}),
|
|
).rejects.toThrow("paperclip_runner_chat_attachment_principal_denied");
|
|
await db
|
|
.update(companyMemberships)
|
|
.set({ status: "active" })
|
|
.where(eq(companyMemberships.principalId, userId));
|
|
|
|
await db
|
|
.update(issues)
|
|
.set({ workMode: "ask" })
|
|
.where(eq(issues.id, issueId));
|
|
await expect(
|
|
runner.execute({
|
|
tool: "reuse_chat_attachment",
|
|
callId: "ask-mode-reuse",
|
|
arguments: {
|
|
idempotencyKey: "ask-mode-reuse",
|
|
sourceCommentId,
|
|
attachmentId: sourceAttachmentId,
|
|
title: "Earlier requested file",
|
|
},
|
|
}),
|
|
).rejects.toThrow("paperclip_runner_tool_mode_denied");
|
|
await db
|
|
.update(issues)
|
|
.set({ workMode: "standard" })
|
|
.where(eq(issues.id, issueId));
|
|
|
|
await db
|
|
.update(chatEndpointResources)
|
|
.set({ enabled: false })
|
|
.where(eq(chatEndpointResources.id, resourceId));
|
|
await expect(
|
|
runner.execute({
|
|
tool: "list_chat_attachments",
|
|
callId: "disabled-reach",
|
|
arguments: {},
|
|
}),
|
|
).rejects.toThrow("paperclip_runner_chat_attachment_destination_denied");
|
|
await db
|
|
.update(chatEndpointResources)
|
|
.set({ enabled: true })
|
|
.where(eq(chatEndpointResources.id, resourceId));
|
|
|
|
await db
|
|
.update(issueComments)
|
|
.set({ deletedAt: new Date() })
|
|
.where(eq(issueComments.id, sourceCommentId));
|
|
await expect(
|
|
runner.execute({
|
|
tool: "reuse_chat_attachment",
|
|
callId: "deleted-source-replay",
|
|
arguments: {
|
|
idempotencyKey: "reuse-earlier-v1",
|
|
sourceCommentId,
|
|
attachmentId: sourceAttachmentId,
|
|
title: "Earlier requested file",
|
|
},
|
|
}),
|
|
).rejects.toThrow("paperclip_runner_chat_attachment_source_denied");
|
|
expect(
|
|
await runner.execute({
|
|
tool: "list_chat_attachments",
|
|
callId: "deleted-source-list",
|
|
arguments: { sourceCommentId },
|
|
}),
|
|
).toEqual({ attachments: [], nextCursor: null, complete: true });
|
|
|
|
await db
|
|
.update(issueComments)
|
|
.set({ deletedAt: null })
|
|
.where(eq(issueComments.id, sourceCommentId));
|
|
await db.insert(chatDeliveries).values({
|
|
companyId,
|
|
endpointId,
|
|
conversationId,
|
|
principalId,
|
|
providerEventId: "source-edit-event",
|
|
deduplicationKey: "source-edit-event",
|
|
eventKind: "message_updated",
|
|
normalizedEvent: {
|
|
message: { targetProviderEventId: "source-event" },
|
|
},
|
|
state: "processed",
|
|
attempts: 1,
|
|
processedAt: new Date(),
|
|
});
|
|
await expect(
|
|
runner.execute({
|
|
tool: "reuse_chat_attachment",
|
|
callId: "edited-source-replay",
|
|
arguments: {
|
|
idempotencyKey: "reuse-earlier-v1",
|
|
sourceCommentId,
|
|
attachmentId: sourceAttachmentId,
|
|
title: "Earlier requested file",
|
|
},
|
|
}),
|
|
).rejects.toThrow("paperclip_runner_chat_attachment_source_denied");
|
|
});
|
|
});
|