Files
PaperClipAI/ui/src/components/chat/ExternallyConnectedTaskBanner.test.tsx
T
DottaandPaperclip 889947c238 feat: add experimental native chat connectors (#13038)
## 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>
2026-09-10 10:06:45 -05:00

1257 lines
43 KiB
TypeScript

// @vitest-environment jsdom
import type { AnchorHTMLAttributes, ReactNode } from "react";
import { flushSync } from "react-dom";
import { createRoot, type Root } from "react-dom/client";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import type { IssueAttachment } from "@paperclipai/shared";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { ExternallyConnectedTaskBanner } from "./ExternallyConnectedTaskBanner";
import { boardSendDraftKey, readBoardSendDraft } from "./board-send-draft";
import { ApiError } from "@/api/client";
const mockChatEndpointsApi = vi.hoisted(() => ({
getIssueBinding: vi.fn(),
publishBoardMessage: vi.fn(),
getPublicationBatchStatus: vi.fn(),
}));
const pushToastMock = vi.hoisted(() => vi.fn());
const uploadAttachmentMock = vi.hoisted(() => vi.fn());
vi.mock("@/api/issues", () => ({
issuesApi: { uploadAttachment: uploadAttachmentMock },
}));
vi.mock("@/hooks/useChatConnectorsEnabled", () => ({
useChatConnectorsEnabled: () => ({ enabled: true, loaded: true }),
}));
vi.mock("@/api/chatEndpoints", () => ({
chatEndpointsApi: mockChatEndpointsApi,
}));
vi.mock("@/context/ToastContext", () => ({
useToast: () => ({ pushToast: pushToastMock }),
}));
vi.mock("@/lib/router", () => ({
Link: ({
children,
to,
...props
}: {
children?: ReactNode;
to: string;
} & AnchorHTMLAttributes<HTMLAnchorElement>) => (
<a href={to} {...props}>
{children}
</a>
),
}));
(
globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean }
).IS_REACT_ACT_ENVIRONMENT = true;
async function act(callback: () => void | Promise<void>) {
let result: void | Promise<void> = undefined;
flushSync(() => {
result = callback();
});
await result;
}
async function flushReact() {
for (let index = 0; index < 5; index += 1) {
await Promise.resolve();
await new Promise((resolve) => window.setTimeout(resolve, 0));
}
flushSync(() => {});
}
function findButton(container: HTMLElement, label: string) {
const button = [...container.querySelectorAll("button")].find(
(candidate) => candidate.textContent?.trim() === label,
);
if (!button) throw new Error(`Button not found: ${label}`);
return button;
}
function setTextareaValue(textarea: HTMLTextAreaElement, value: string) {
const setter = Object.getOwnPropertyDescriptor(
HTMLTextAreaElement.prototype,
"value",
)?.set;
setter?.call(textarea, value);
textarea.dispatchEvent(new Event("input", { bubbles: true }));
}
describe("ExternallyConnectedTaskBanner publication truth", () => {
let container: HTMLDivElement;
let root: Root;
async function renderBanner(
attachments: IssueAttachment[] = [],
issueCacheRefs?: string[],
existingQueryClient?: QueryClient,
) {
const queryClient =
existingQueryClient ??
new QueryClient({
defaultOptions: { queries: { retry: false } },
});
flushSync(() => {
root.render(
<QueryClientProvider client={queryClient}>
<ExternallyConnectedTaskBanner
attachments={attachments}
companyId="company-1"
issueId="issue-1"
issueCacheRefs={issueCacheRefs}
/>
</QueryClientProvider>,
);
});
await flushReact();
return queryClient;
}
async function composeAndSubmit(value = "Visible board update") {
await act(() => findButton(container, "Send to channel").click());
const textarea = container.querySelector("textarea");
if (!textarea) throw new Error("Board update textarea missing");
await act(() => setTextareaValue(textarea, value));
await act(() => {
const sendButtons = [...container.querySelectorAll("button")].filter(
(button) => button.textContent?.trim() === "Send to channel",
);
sendButtons.at(-1)?.click();
});
await flushReact();
}
beforeEach(() => {
vi.clearAllMocks();
sessionStorage.clear();
mockChatEndpointsApi.getPublicationBatchStatus.mockImplementation(
() => new Promise(() => {}),
);
mockChatEndpointsApi.getIssueBinding.mockResolvedValue({
endpointId: "endpoint-1",
provider: "slack",
botLabel: "Maya",
externalLabel: "#paperclip",
externalUrl: "https://example.slack.com/archives/channel-1",
conversationId: "conversation-1",
publicationState: null,
assignedAgentLocked: true,
});
container = document.createElement("div");
document.body.appendChild(container);
root = createRoot(container);
});
afterEach(() => {
flushSync(() => root.unmount());
container.remove();
vi.restoreAllMocks();
});
it("only reports success and clears the draft after confirmed publication", async () => {
mockChatEndpointsApi.publishBoardMessage.mockResolvedValue({
id: "publication-1",
state: "published",
attempts: 1,
publishedAt: "2026-09-06T12:00:00.000Z",
});
await renderBanner();
await composeAndSubmit();
expect(mockChatEndpointsApi.publishBoardMessage).toHaveBeenCalledWith(
"endpoint-1",
"conversation-1",
"Visible board update",
expect.any(String),
[],
);
expect(pushToastMock).toHaveBeenCalledWith({
title: "Sent to channel",
body: "The board update was published to the connected conversation.",
tone: "success",
});
expect(container.querySelector("textarea")).toBeNull();
});
it("publishes only explicitly checked unbound task files", async () => {
mockChatEndpointsApi.publishBoardMessage.mockResolvedValue({
id: "publication-file",
state: "published",
attempts: 1,
});
const attachment = {
id: "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa",
companyId: "company-1",
issueId: "issue-1",
issueCommentId: null,
assetId: "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb",
provider: "local_disk",
objectKey: "issues/issue-1/result.txt",
contentType: "text/plain",
byteSize: 12,
sha256: "a".repeat(64),
originalFilename: "result.txt",
createdByAgentId: "agent-1",
createdByUserId: null,
createdAt: new Date(),
updatedAt: new Date(),
contentPath:
"/api/attachments/aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa/content",
} satisfies IssueAttachment;
await renderBanner([
attachment,
{
...attachment,
id: "cccccccc-cccc-4ccc-8ccc-cccccccccccc",
issueCommentId: "dddddddd-dddd-4ddd-8ddd-dddddddddddd",
originalFilename: "already-bound.txt",
},
]);
await act(() => findButton(container, "Send to channel").click());
expect(container.textContent).toContain("result.txt");
expect(container.textContent).not.toContain("already-bound.txt");
const checkbox = container.querySelector('button[role="checkbox"]');
if (!checkbox) throw new Error("Attachment checkbox missing");
await act(() => (checkbox as HTMLButtonElement).click());
const textarea = container.querySelector("textarea");
if (!textarea) throw new Error("Board update textarea missing");
await act(() => setTextareaValue(textarea, "Send the requested file."));
await act(() => {
const sendButtons = [...container.querySelectorAll("button")].filter(
(button) => button.textContent?.trim() === "Send to channel",
);
sendButtons.at(-1)?.click();
});
await flushReact();
expect(mockChatEndpointsApi.publishBoardMessage).toHaveBeenCalledWith(
"endpoint-1",
"conversation-1",
"Send the requested file.",
expect.any(String),
[attachment.id],
);
});
it("uploads a new file on an empty task without sending, then preserves its exact selection for publication", async () => {
let finishUpload!: (value: unknown) => void;
uploadAttachmentMock.mockImplementationOnce(
() =>
new Promise((resolve) => {
finishUpload = resolve;
}),
);
mockChatEndpointsApi.publishBoardMessage.mockResolvedValue({
id: "uploaded-file-publication",
state: "streaming",
attempts: 1,
});
await renderBanner();
await act(() => findButton(container, "Send to channel").click());
await act(() =>
setTextareaValue(
container.querySelector("textarea")!,
"The requested image.",
),
);
const input =
container.querySelector<HTMLInputElement>('input[type="file"]');
expect(input).not.toBeNull();
const file = new File(["synthetic image bytes"], "cat.png", {
type: "image/png",
});
Object.defineProperty(input!, "files", {
value: [file],
configurable: true,
});
await act(() => {
input!.dispatchEvent(new Event("change", { bubbles: true }));
});
await flushReact();
expect(uploadAttachmentMock).toHaveBeenCalledWith(
"company-1",
"issue-1",
file,
);
expect(findButton(container, "Uploading…").disabled).toBe(true);
const send = [...container.querySelectorAll("button")]
.filter((button) => button.textContent?.trim() === "Send to channel")
.at(-1)!;
expect(send.disabled).toBe(true);
expect(mockChatEndpointsApi.publishBoardMessage).not.toHaveBeenCalled();
finishUpload({
id: "uploaded-image",
companyId: "company-1",
issueId: "issue-1",
issueCommentId: null,
originalFilename: "cat.png",
});
await flushReact();
expect(container.textContent).toContain(
"Files stay on this task until you send them to the channel.",
);
expect(
container
.querySelector('button[role="checkbox"]')
?.getAttribute("aria-checked"),
).toBe("true");
expect(mockChatEndpointsApi.publishBoardMessage).not.toHaveBeenCalled();
await act(() => send.click());
await flushReact();
expect(mockChatEndpointsApi.publishBoardMessage).toHaveBeenCalledWith(
"endpoint-1",
"conversation-1",
"The requested image.",
expect.any(String),
["uploaded-image"],
);
expect(findButton(container, "Attach file").disabled).toBe(true);
expect(
readBoardSendDraft(
boardSendDraftKey(
"company-1",
"issue-1",
"endpoint-1",
"conversation-1",
),
)?.attachmentNames,
).toEqual([{ id: "uploaded-image", name: "cat.png" }]);
});
it("keeps the message editable after an unconfirmed upload and never sends it automatically", async () => {
uploadAttachmentMock.mockRejectedValueOnce(
new Error("Upload connection interrupted"),
);
await renderBanner();
await act(() => findButton(container, "Send to channel").click());
await act(() =>
setTextareaValue(
container.querySelector("textarea")!,
"Keep this draft.",
),
);
const input =
container.querySelector<HTMLInputElement>('input[type="file"]');
expect(input).not.toBeNull();
Object.defineProperty(input!, "files", {
value: [new File(["file"], "report.txt")],
configurable: true,
});
await act(() => {
input!.dispatchEvent(new Event("change", { bubbles: true }));
});
await flushReact();
expect(container.textContent).toContain("Upload connection interrupted");
expect(container.textContent).toContain("Check task files before retrying");
expect(container.querySelector("textarea")?.value).toBe("Keep this draft.");
expect(container.querySelector("textarea")?.disabled).toBe(false);
expect(findButton(container, "Attach file").disabled).toBe(false);
expect(mockChatEndpointsApi.publishBoardMessage).not.toHaveBeenCalled();
});
it("does not select a late upload in a different conversation", async () => {
let finishUpload!: (value: unknown) => void;
uploadAttachmentMock.mockImplementationOnce(
() =>
new Promise((resolve) => {
finishUpload = resolve;
}),
);
const queryClient = await renderBanner();
await act(() => findButton(container, "Send to channel").click());
const input =
container.querySelector<HTMLInputElement>('input[type="file"]');
expect(input).not.toBeNull();
Object.defineProperty(input!, "files", {
value: [new File(["file"], "old.txt")],
configurable: true,
});
await act(() => {
input!.dispatchEvent(new Event("change", { bubbles: true }));
});
await flushReact();
queryClient.setQueryData(["issue-chat-binding", "company-1", "issue-1"], {
endpointId: "endpoint-2",
conversationId: "conversation-2",
provider: "slack",
externalLabel: "#second",
assignedAgentLocked: true,
});
await flushReact();
await act(() => findButton(container, "Send to channel").click());
finishUpload({
id: "old-upload",
companyId: "company-1",
issueId: "issue-1",
issueCommentId: null,
originalFilename: "old.txt",
});
await flushReact();
expect(container.textContent).not.toContain("old.txt");
expect(container.querySelectorAll('button[role="checkbox"]')).toHaveLength(
0,
);
expect(findButton(container, "Attach file").disabled).toBe(false);
expect(mockChatEndpointsApi.publishBoardMessage).not.toHaveBeenCalled();
});
it.each(["published", "cancelled"] as const)(
"keeps exact selected file names and checks through binding/reload, then excludes them from a new %s draft",
async (finalState) => {
const attachment = {
id: "file-selected",
companyId: "company-1",
issueId: "issue-1",
issueCommentId: null,
assetId: "asset-selected",
provider: "local_disk",
objectKey: "selected.txt",
contentType: "text/plain",
byteSize: 12,
sha256: "a".repeat(64),
originalFilename: "selected.txt",
createdByAgentId: null,
createdByUserId: "board",
createdAt: new Date(),
updatedAt: new Date(),
contentPath: "/api/attachments/file-selected/content",
} satisfies IssueAttachment;
const internalOnly = {
...attachment,
id: "file-internal",
originalFilename: "internal-only.txt",
};
mockChatEndpointsApi.publishBoardMessage.mockResolvedValue({
id: "original-anchor",
state: "streaming",
attempts: 1,
});
mockChatEndpointsApi.getPublicationBatchStatus.mockResolvedValue({
publication: { id: "file-part", state: "pending", attempts: 0 },
total: 2,
published: 1,
});
const queryClient = await renderBanner([attachment, internalOnly]);
await act(() => findButton(container, "Send to channel").click());
await act(() =>
(
container.querySelector(
'button[role="checkbox"]',
) as HTMLButtonElement
).click(),
);
await act(() =>
setTextareaValue(container.querySelector("textarea")!, "Exact files"),
);
await act(() =>
[...container.querySelectorAll("button")]
.filter((button) => button.textContent?.trim() === "Send to channel")
.at(-1)
?.click(),
);
await flushReact();
const bound = { ...attachment, issueCommentId: "board-comment" };
await renderBanner([bound, internalOnly], undefined, queryClient);
const assertRetainedFiles = () => {
expect(container.textContent).toContain("Files in this send");
expect(container.textContent).toContain("selected.txt");
expect(container.textContent).not.toContain("internal-only.txt");
const checks = container.querySelectorAll('button[role="checkbox"]');
expect(checks.length).toBe(1);
expect(checks[0]?.getAttribute("aria-checked")).toBe("true");
expect((checks[0] as HTMLButtonElement).disabled).toBe(true);
};
assertRetainedFiles();
// Reload with attachment metadata still loading must retain saved names.
flushSync(() => root.unmount());
root = createRoot(container);
const restoredClient = await renderBanner([]);
assertRetainedFiles();
await renderBanner([bound, internalOnly], undefined, restoredClient);
assertRetainedFiles();
mockChatEndpointsApi.getPublicationBatchStatus.mockResolvedValue({
publication: { id: "file-part", state: finalState, attempts: 1 },
total: 2,
published: finalState === "published" ? 2 : 1,
awaitingConsent: 0,
declined: 0,
expired: 0,
cancelled: finalState === "cancelled" ? 1 : 0,
settled: 2,
canDismiss: true,
});
await restoredClient.invalidateQueries({
queryKey: ["chat-publication-batch"],
});
await flushReact();
await act(() =>
findButton(
container,
finalState === "published"
? "Send to channel"
: "Dismiss delivery receipt",
).click(),
);
expect(container.textContent).not.toContain("selected.txt");
expect(container.textContent).toContain("internal-only.txt");
const newCheck = container.querySelector(
'button[role="checkbox"]',
) as HTMLButtonElement;
expect(newCheck.getAttribute("aria-checked")).toBe("false");
expect(newCheck.disabled).toBe(false);
expect(mockChatEndpointsApi.publishBoardMessage).toHaveBeenCalledTimes(1);
expect(
mockChatEndpointsApi.publishBoardMessage.mock.calls[0]?.[4],
).toEqual([attachment.id]);
},
);
it("refreshes a retained send and clears it only after every batch part is published", async () => {
mockChatEndpointsApi.publishBoardMessage.mockResolvedValue({
id: "text-part",
state: "streaming",
attempts: 1,
});
mockChatEndpointsApi.getPublicationBatchStatus.mockResolvedValue({
publication: { id: "file-part", state: "pending", attempts: 0 },
total: 2,
published: 1,
});
const queryClient = await renderBanner();
await composeAndSubmit();
await flushReact();
expect(mockChatEndpointsApi.getPublicationBatchStatus).toHaveBeenCalledWith(
"endpoint-1",
"conversation-1",
"text-part",
);
expect(container.querySelector("textarea")?.value).toBe(
"Visible board update",
);
expect(container.textContent).toContain("Queued for channel");
mockChatEndpointsApi.getPublicationBatchStatus.mockResolvedValue({
publication: { id: "file-part", state: "published", attempts: 1 },
total: 2,
published: 2,
});
await queryClient.invalidateQueries({
queryKey: ["chat-publication-batch"],
});
await flushReact();
expect(container.querySelector("textarea")).toBeNull();
expect(mockChatEndpointsApi.publishBoardMessage).toHaveBeenCalledTimes(1);
expect(
mockChatEndpointsApi.getPublicationBatchStatus.mock.calls.every(
(call) => call[2] === "text-part",
),
).toBe(true);
});
it("keeps a draft across status read errors and invalidates canonical task aliases", async () => {
mockChatEndpointsApi.publishBoardMessage.mockResolvedValue({
id: "text-part",
state: "streaming",
attempts: 1,
});
mockChatEndpointsApi.getPublicationBatchStatus.mockRejectedValue(
new Error("Status temporarily unavailable"),
);
const queryClient = await renderBanner([], ["issue-1", "CHA-2"]);
const invalidated = vi.spyOn(queryClient, "invalidateQueries");
await composeAndSubmit();
await flushReact();
expect(container.textContent).toContain(
"Delivery status could not be refreshed",
);
expect(container.querySelector("textarea")?.value).toBe(
"Visible board update",
);
expect(container.querySelector("textarea")?.disabled).toBe(true);
expect(invalidated).toHaveBeenCalledWith({
queryKey: ["issues", "comments", "CHA-2"],
});
mockChatEndpointsApi.getPublicationBatchStatus.mockResolvedValue({
publication: { id: "file-part", state: "published", attempts: 1 },
total: 2,
published: 1,
});
await queryClient.invalidateQueries({
queryKey: ["chat-publication-batch"],
});
await flushReact();
expect(container.querySelector("textarea")?.disabled).toBe(true);
expect(mockChatEndpointsApi.publishBoardMessage).toHaveBeenCalledTimes(1);
});
it.each(["github", "microsoft-teams"] as const)(
"explains %s file delivery boundaries before publication",
async (provider) => {
mockChatEndpointsApi.getIssueBinding.mockResolvedValue({
endpointId: "endpoint-github",
provider,
botLabel: "Maya",
externalLabel: "paperclipai/paperclip#42",
externalUrl: "https://github.com/paperclipai/paperclip/issues/42",
conversationId: "conversation-github",
publicationState: null,
assignedAgentLocked: true,
});
const attachment = {
id: "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa",
companyId: "company-1",
issueId: "issue-1",
issueCommentId: null,
assetId: "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb",
provider: "local_disk",
objectKey: "issues/issue-1/result.txt",
contentType: "text/plain",
byteSize: 12,
sha256: "a".repeat(64),
originalFilename: "result.txt",
createdByAgentId: "agent-1",
createdByUserId: null,
createdAt: new Date(),
updatedAt: new Date(),
contentPath:
"/api/attachments/aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa/content",
} satisfies IssueAttachment;
await renderBanner([attachment]);
await act(() => findButton(container, "Send to channel").click());
if (provider === "github") {
expect(container.textContent).toContain(
"GitHub Apps cannot upload file bytes in comments.",
);
expect(container.textContent).toContain(
"GitHub receives an authenticated task link when this Board has a public URL, or a private-task notice otherwise.",
);
} else {
expect(container.textContent).toContain(
"In personal Teams chats, recipients accept each file before upload.",
);
expect(container.textContent).toContain(
"Channels and group chats receive supported images directly; other files stay on the task, with a task link or private-task notice.",
);
expect(container.textContent).not.toContain(
"Teams asks the recipient to accept each file before upload.",
);
}
expect(container.textContent).not.toContain(
"Only checked files will be published to the external conversation.",
);
},
);
it.each([
["pending", "Queued for channel"],
["streaming", "Publishing to channel"],
["retry", "Delivery retry scheduled"],
["delivery_unknown", "Delivery not confirmed"],
["failed", "Channel delivery failed"],
["cancelled", "Channel delivery cancelled"],
] as const)(
"keeps the draft and shows Activity guidance for %s",
async (state, title) => {
mockChatEndpointsApi.publishBoardMessage.mockResolvedValue({
id: `publication-${state}`,
state,
attempts: 1,
redactedError:
state === "failed" ? "Provider rejected the update" : null,
});
await renderBanner();
await composeAndSubmit();
const textarea = container.querySelector("textarea");
expect(textarea?.value).toBe("Visible board update");
expect(textarea?.disabled).toBe(true);
expect(container.textContent).toContain(title);
expect(
container.querySelector('a[href="/apps/chat/endpoint-1/activity"]'),
).not.toBeNull();
expect(pushToastMock).toHaveBeenLastCalledWith(
expect.objectContaining({
title,
action: {
label: "View activity",
href: "/apps/chat/endpoint-1/activity",
},
}),
);
expect(pushToastMock).not.toHaveBeenCalledWith(
expect.objectContaining({ title: "Sent to channel" }),
);
},
);
it("reuses the same request identity when the client retries an unconfirmed request", async () => {
mockChatEndpointsApi.publishBoardMessage
.mockRejectedValueOnce(new Error("Connection interrupted."))
.mockResolvedValueOnce({
id: "publication-1",
state: "published",
attempts: 1,
});
await renderBanner();
await composeAndSubmit();
const retainedDraft = container.querySelector("textarea");
expect(retainedDraft?.value).toBe("Visible board update");
expect(retainedDraft?.disabled).toBe(true);
expect(container.textContent).toContain("Delivery result not confirmed");
expect(findButton(container, "Retry safely")).not.toBeNull();
const firstKey =
mockChatEndpointsApi.publishBoardMessage.mock.calls[0]?.[3];
await act(() => findButton(container, "Retry safely").click());
await flushReact();
expect(mockChatEndpointsApi.publishBoardMessage).toHaveBeenCalledTimes(2);
expect(mockChatEndpointsApi.publishBoardMessage.mock.calls[1]?.[3]).toBe(
firstKey,
);
expect(container.querySelector("textarea")).toBeNull();
});
it("keeps a request-scoped durable rejection through reload and allows an explicit corrected send", async () => {
const file = {
id: "bound-file",
companyId: "company-1",
issueId: "issue-1",
issueCommentId: null,
originalFilename: "report.txt",
} as IssueAttachment;
mockChatEndpointsApi.publishBoardMessage.mockImplementationOnce(
(endpointId, conversationId, _body, idempotencyKey) =>
Promise.reject(
new ApiError(
"A selected file already belongs to another comment",
409,
{
details: {
code: "chat_board_send_attachments_already_bound",
endpointId,
conversationId,
idempotencyKey,
attachmentIds: [file.id],
},
},
),
),
);
const queryClient = await renderBanner([file]);
await act(() => findButton(container, "Send to channel").click());
await act(() =>
(
container.querySelector('button[role="checkbox"]') as HTMLButtonElement
).click(),
);
await act(() =>
setTextareaValue(
container.querySelector("textarea")!,
"Share the result",
),
);
await act(() =>
[...container.querySelectorAll("button")]
.filter((button) => button.textContent?.trim() === "Send to channel")
.at(-1)
?.click(),
);
await flushReact();
const originalKey =
mockChatEndpointsApi.publishBoardMessage.mock.calls[0][3];
expect(container.textContent).toContain("Update was not sent");
expect(container.textContent).not.toContain(
"Delivery result not confirmed",
);
expect(container.querySelector("textarea")?.disabled).toBe(true);
expect(findButton(container, "Edit rejected send")).toBeTruthy();
flushSync(() => root.unmount());
root = createRoot(container);
await renderBanner([file], undefined, queryClient);
expect(container.textContent).toContain("Update was not sent");
expect(container.querySelector("textarea")?.value).toBe("Share the result");
expect(mockChatEndpointsApi.publishBoardMessage).toHaveBeenCalledTimes(1);
await act(() => findButton(container, "Edit rejected send").click());
await flushReact();
expect(container.querySelector("textarea")?.disabled).toBe(false);
expect(container.querySelector("textarea")?.value).toBe("Share the result");
expect(container.querySelectorAll('button[role="checkbox"]')).toHaveLength(
0,
);
expect(container.textContent).toContain(
"Attach a new copy or share the task link",
);
mockChatEndpointsApi.publishBoardMessage.mockResolvedValueOnce({
id: "new-send",
state: "published",
attempts: 1,
});
await act(() =>
[...container.querySelectorAll("button")]
.filter((button) => button.textContent?.trim() === "Send to channel")
.at(-1)
?.click(),
);
await flushReact();
expect(mockChatEndpointsApi.publishBoardMessage).toHaveBeenCalledTimes(2);
expect(mockChatEndpointsApi.publishBoardMessage.mock.calls[1][3]).not.toBe(
originalKey,
);
expect(mockChatEndpointsApi.publishBoardMessage.mock.calls[1][4]).toEqual(
[],
);
});
it.each([
"uncoded",
"foreign-endpoint",
"foreign-conversation",
"foreign-key",
"foreign-file",
"empty-files",
"server-error",
])(
"does not unlock an uncertain send on a %s rejection-shaped error",
async (kind) => {
mockChatEndpointsApi.publishBoardMessage.mockImplementationOnce(
(endpointId, conversationId, _body, idempotencyKey) =>
Promise.reject(
new ApiError("Conflict", kind === "server-error" ? 500 : 409, {
details: {
code:
kind === "uncoded"
? "conflict"
: "chat_board_send_attachments_already_bound",
endpointId: kind === "foreign-endpoint" ? "other" : endpointId,
conversationId:
kind === "foreign-conversation" ? "other" : conversationId,
idempotencyKey:
kind === "foreign-key" ? "other" : idempotencyKey,
attachmentIds:
kind === "empty-files"
? []
: [
kind === "foreign-file"
? "unselected-file"
: "selected-file",
],
},
}),
),
);
await renderBanner([
{
id: "selected-file",
issueCommentId: null,
originalFilename: "selected.txt",
} as IssueAttachment,
]);
await act(() => findButton(container, "Send to channel").click());
await act(() =>
(
container.querySelector(
'button[role="checkbox"]',
) as HTMLButtonElement
).click(),
);
await act(() =>
setTextareaValue(
container.querySelector("textarea")!,
"Keep exact request",
),
);
await act(() =>
[...container.querySelectorAll("button")]
.filter((button) => button.textContent?.trim() === "Send to channel")
.at(-1)
?.click(),
);
await flushReact();
expect(container.textContent).toContain("Delivery result not confirmed");
expect(container.textContent).not.toContain("Edit rejected send");
expect(container.querySelector("textarea")?.disabled).toBe(true);
expect(mockChatEndpointsApi.publishBoardMessage).toHaveBeenCalledTimes(1);
},
);
it("removes a selected file when authoritative task metadata binds it elsewhere, before a send", async () => {
const file = {
id: "now-bound",
issueCommentId: null,
originalFilename: "already-used.txt",
} as IssueAttachment;
const queryClient = await renderBanner([file]);
await act(() => findButton(container, "Send to channel").click());
await act(() =>
(
container.querySelector('button[role="checkbox"]') as HTMLButtonElement
).click(),
);
await act(() =>
setTextareaValue(
container.querySelector("textarea")!,
"Keep this message",
),
);
await renderBanner(
[{ ...file, issueCommentId: "saved-board-comment" }],
undefined,
queryClient,
);
expect(container.textContent).toContain(
"Attach a new copy or share the task link",
);
mockChatEndpointsApi.publishBoardMessage.mockResolvedValueOnce({
id: "text-only",
state: "published",
attempts: 1,
});
await act(() =>
[...container.querySelectorAll("button")]
.filter((button) => button.textContent?.trim() === "Send to channel")
.at(-1)
?.click(),
);
await flushReact();
expect(mockChatEndpointsApi.publishBoardMessage.mock.calls[0][4]).toEqual(
[],
);
});
it("requires an explicit new send after a cancelled publication", async () => {
mockChatEndpointsApi.publishBoardMessage.mockResolvedValue({
id: "publication-cancelled",
state: "cancelled",
attempts: 1,
});
await renderBanner();
await composeAndSubmit();
const retainedDraft = container.querySelector("textarea");
expect(retainedDraft?.value).toBe("Visible board update");
expect(retainedDraft?.disabled).toBe(true);
expect(container.textContent).not.toContain("Start a new send");
expect(container.textContent).not.toContain("Dismiss delivery receipt");
expect(mockChatEndpointsApi.publishBoardMessage).toHaveBeenCalledTimes(1);
});
it("retains a Teams consent wait across reload without another send", async () => {
const part = {
id: "consent-file",
state: "awaiting_consent",
attempts: 1,
fileTransfer: {
provider: "microsoft-teams",
phase: "awaiting_consent",
filename: "report.txt",
version: 2,
},
};
mockChatEndpointsApi.publishBoardMessage.mockResolvedValue(part);
mockChatEndpointsApi.getPublicationBatchStatus.mockResolvedValue({
publication: part,
total: 2,
published: 1,
parts: [{ id: "text", state: "published", attempts: 1 }, part],
awaitingConsent: 1,
declined: 0,
expired: 0,
cancelled: 0,
settled: 1,
canDismiss: false,
});
await renderBanner();
await composeAndSubmit();
expect(container.textContent).toContain("Waiting for file consent");
expect(container.textContent).toContain("report.txt");
expect(container.textContent).not.toContain("Dismiss delivery receipt");
expect(container.querySelector("textarea")?.disabled).toBe(true);
await act(() => root.unmount());
root = createRoot(container);
await renderBanner();
expect(container.textContent).toContain("Waiting for file consent");
expect(
mockChatEndpointsApi.getPublicationBatchStatus,
).toHaveBeenLastCalledWith("endpoint-1", "conversation-1", "consent-file");
expect(mockChatEndpointsApi.publishBoardMessage).toHaveBeenCalledTimes(1);
});
it.each([false, true])(
"dismisses a mixed terminal receipt only on explicit whole-batch permission (storage failure %s)",
async (storageFailure) => {
const part = {
id: "declined-file",
state: "cancelled",
attempts: 1,
fileTransfer: {
provider: "microsoft-teams",
phase: "declined",
filename: "declined.txt",
version: 3,
},
};
mockChatEndpointsApi.publishBoardMessage.mockResolvedValue(part);
mockChatEndpointsApi.getPublicationBatchStatus.mockResolvedValue({
publication: part,
total: 3,
published: 1,
awaitingConsent: 0,
declined: 1,
expired: 1,
cancelled: 0,
settled: 3,
canDismiss: true,
parts: [
{ id: "text", state: "published", attempts: 1 },
part,
{
...part,
id: "expired-file",
fileTransfer: {
...part.fileTransfer,
phase: "expired",
filename: "expired.txt",
},
},
],
});
await renderBanner();
await composeAndSubmit();
expect(container.textContent).toContain(
"1 published · 1 declined · 1 expired",
);
expect(container.textContent).toContain("expired.txt");
const removeItemSpy = storageFailure
? vi
.spyOn(Object.getPrototypeOf(sessionStorage), "removeItem")
.mockImplementation(() => {
throw new Error("storage denied");
})
: null;
await act(() =>
findButton(container, "Dismiss delivery receipt").click(),
);
expect(mockChatEndpointsApi.publishBoardMessage).toHaveBeenCalledTimes(1);
if (storageFailure) {
expect(container.querySelector("textarea")?.disabled).toBe(true);
expect(container.textContent).toContain("could not be cleared");
removeItemSpy!.mockRestore();
await act(() =>
findButton(container, "Dismiss delivery receipt").click(),
);
expect(container.querySelector("textarea")?.disabled).toBe(false);
expect(container.querySelector("textarea")?.value).toBe("");
expect(container.textContent).not.toContain("could not be cleared");
expect(mockChatEndpointsApi.publishBoardMessage).toHaveBeenCalledTimes(
1,
);
} else {
expect(container.querySelector("textarea")?.value).toBe("");
expect(container.querySelector("textarea")?.disabled).toBe(false);
expect(
readBoardSendDraft(
boardSendDraftKey(
"company-1",
"issue-1",
"endpoint-1",
"conversation-1",
),
),
).toBeNull();
expect(
pushToastMock.mock.calls.some(
([toast]) => toast.title === "Sent to channel",
),
).toBe(false);
}
},
);
it("does not release a cancelled head while another file still waits", async () => {
const part = { id: "cancelled-head", state: "cancelled", attempts: 1 };
mockChatEndpointsApi.publishBoardMessage.mockResolvedValue(part);
mockChatEndpointsApi.getPublicationBatchStatus.mockResolvedValue({
publication: part,
total: 2,
published: 0,
awaitingConsent: 1,
declined: 0,
expired: 0,
cancelled: 1,
settled: 1,
canDismiss: false,
});
await renderBanner();
await composeAndSubmit();
expect(container.textContent).toContain(
"Waiting for remaining file consent",
);
expect(container.textContent).not.toContain("Channel delivery cancelled");
expect(container.textContent).not.toContain("Dismiss delivery receipt");
expect(container.textContent).not.toContain("Start a new send");
expect(container.querySelector("textarea")?.disabled).toBe(true);
expect(mockChatEndpointsApi.publishBoardMessage).toHaveBeenCalledTimes(1);
});
it("restores a pending batch after reload without another POST", async () => {
mockChatEndpointsApi.publishBoardMessage.mockResolvedValue({
id: "original-anchor",
state: "streaming",
attempts: 1,
});
await renderBanner();
await composeAndSubmit("Reload-safe board send");
flushSync(() => root.unmount());
root = createRoot(container);
await renderBanner();
expect(container.querySelector("textarea")?.value).toBe(
"Reload-safe board send",
);
expect(container.querySelector("textarea")?.disabled).toBe(true);
expect(
mockChatEndpointsApi.getPublicationBatchStatus,
).toHaveBeenLastCalledWith(
"endpoint-1",
"conversation-1",
"original-anchor",
);
expect(mockChatEndpointsApi.publishBoardMessage).toHaveBeenCalledTimes(1);
});
it("restores an unconfirmed payload after reload and only explicitly retries the same identity", async () => {
mockChatEndpointsApi.publishBoardMessage.mockRejectedValueOnce(
new Error("Response lost"),
);
await renderBanner();
await composeAndSubmit("Exact request survives reload");
const firstCall = mockChatEndpointsApi.publishBoardMessage.mock.calls[0];
flushSync(() => root.unmount());
root = createRoot(container);
await renderBanner();
expect(container.querySelector("textarea")?.value).toBe(
"Exact request survives reload",
);
expect(container.querySelector("textarea")?.disabled).toBe(true);
expect(mockChatEndpointsApi.publishBoardMessage).toHaveBeenCalledTimes(1);
expect(
mockChatEndpointsApi.getPublicationBatchStatus,
).not.toHaveBeenCalled();
mockChatEndpointsApi.publishBoardMessage.mockResolvedValueOnce({
id: "confirmed",
state: "published",
attempts: 1,
});
await act(() => findButton(container, "Retry safely").click());
await flushReact();
expect(mockChatEndpointsApi.publishBoardMessage.mock.calls[1]).toEqual(
firstCall,
);
expect(container.querySelector("textarea")).toBeNull();
expect(sessionStorage.length).toBe(0);
});
it("does not send when browser storage cannot preserve the request identity", async () => {
await renderBanner();
vi.spyOn(
Object.getPrototypeOf(sessionStorage),
"setItem",
).mockImplementation(() => {
throw new Error("Storage full");
});
await composeAndSubmit();
expect(mockChatEndpointsApi.publishBoardMessage).not.toHaveBeenCalled();
expect(container.textContent).toContain("No update was sent");
});
it("isolates an in-flight send and its late response when the binding scope changes", async () => {
let finishOldSend!: (value: unknown) => void;
mockChatEndpointsApi.publishBoardMessage.mockImplementationOnce(
() =>
new Promise((resolve) => {
finishOldSend = resolve;
}),
);
const queryClient = await renderBanner();
await composeAndSubmit("Original conversation only");
expect(container.textContent).not.toContain(
"Delivery result not confirmed",
);
const originalCall = mockChatEndpointsApi.publishBoardMessage.mock.calls[0];
queryClient.setQueryData(["issue-chat-binding", "company-1", "issue-1"], {
endpointId: "endpoint-2",
conversationId: "conversation-2",
provider: "slack",
externalLabel: "#second",
assignedAgentLocked: true,
});
await flushReact();
await act(() => findButton(container, "Send to channel").click());
expect(container.querySelector("textarea")?.value).toBe("");
const sendButtons = [...container.querySelectorAll("button")].filter(
(button) => button.textContent?.trim() === "Send to channel",
);
expect(sendButtons.at(-1)?.disabled).toBe(true);
finishOldSend({ id: "old-anchor", state: "streaming", attempts: 1 });
await flushReact();
expect(container.querySelector("textarea")?.value).toBe("");
expect(
mockChatEndpointsApi.getPublicationBatchStatus,
).not.toHaveBeenCalledWith("endpoint-2", "conversation-2", "old-anchor");
expect(
readBoardSendDraft(
boardSendDraftKey(
"company-1",
"issue-1",
"endpoint-1",
"conversation-1",
),
),
).toMatchObject({
body: "Original conversation only",
idempotencyKey: originalCall[3],
publication: { id: "old-anchor" },
});
expect(
readBoardSendDraft(
boardSendDraftKey(
"company-1",
"issue-1",
"endpoint-2",
"conversation-2",
),
),
).toBeNull();
mockChatEndpointsApi.publishBoardMessage.mockResolvedValueOnce({
id: "new-anchor",
state: "published",
attempts: 1,
});
await act(() =>
setTextareaValue(
container.querySelector("textarea")!,
"New conversation only",
),
);
await act(() => sendButtons.at(-1)?.click());
await flushReact();
expect(
mockChatEndpointsApi.publishBoardMessage.mock.calls[1]?.slice(0, 3),
).toEqual(["endpoint-2", "conversation-2", "New conversation only"]);
expect(
mockChatEndpointsApi.publishBoardMessage.mock.calls[1]?.[3],
).not.toBe(originalCall[3]);
});
});