Files
PaperClipAI/ui/src/components/chat/ExternallyConnectedTaskBanner.test.tsx
T
DottaandPaperclip ed2c22ea8c feat(connections): simplify dedicated GitHub App setup (#15416)
## Thinking Path

> - Paperclip manages agent work and the tools each agent can use.
> - GitHub bots need their own App identity and restricted repository
access.
> - Manual App configuration and repeated setup gates make that
connection hard to finish.
> - GitHub can create an App from a manifest, but people must approve
creation and repository access.
> - Each Paperclip stack should own configuration, credentials,
signature verification, and task admission.
> - This change uses Cloud as an encrypted callback and event gateway,
then completes setup in the stack.
> - GitHub review bots have their own experimental setting. Chat
connector opt-in does not control them.

## Linked Issues or Issue Description

**What existing behavior does this improve?**

Dedicated GitHub App setup, bot settings, and task-scoped GitHub
replies.

**Current behavior**

Users must configure an App, copy credentials, repeat repository
selection, and complete manual verification gates. Review settings are
hard to scan. Mentions in descriptions can be missed, and automatic
completion text can produce an extra GitHub comment.

**Proposed behavior**

Choose an agent and connect GitHub under a personal account or
organization. GitHub asks for creation and installation consent.
Paperclip resumes the same draft, stores secrets locally, imports
access, verifies delivery, and opens Settings. Each accepted request has
one editable App-owned comment for progress and results. Review
assessments produce deterministic checks for the reviewed commit.

**Breaking changes**

GitHub bots require their own default-off experimental opt-in. The
setup-method and delegated-agent screens are removed. Per-person
automatic-run flags remain readable but are replaced by author filters.
Existing connections, direct webhooks, saved restrictions, and manual
existing-App recovery remain supported.

Companion gateway:
https://github.com/paperclipai/paperclip-cloud/pull/688 (merged). The
roadmap and related PRs were checked; no duplicate dedicated-App wizard
was found.

## What Changed

- Add an independent **GitHub review bots** setting across the catalog,
routes, identity admission, and task controls. Existing bots continue
running when the UI setting is off.
- Replace setup with Choose agent and Connect GitHub. Support personal
and organization owners, inline low-trust conversion, saved drafts,
known organization suggestions, automatic completion, and same-App
recovery.
- Keep manifests, OAuth PKCE, credential exchange, vault storage,
installation verification, and original webhook-signature validation in
the stack. Use the Cloud sealed gateway for public callbacks and
outbound local delivery.
- Add resumable owner metadata in migration 0323. Retry a failed
registration renewal through the same durable replacement rather than
creating another App route.
- Support authorized mentions in issue and PR bodies, comments, inline
comments, and review summaries. Preserve attachments, edited-source
identity, duplicate protection, and lifecycle invalidation. Filter
requests explicitly addressed to another connected bot.
- Give agents task-scoped review, comment, and update tools. Update one
working comment through progress and final output. Close coalesced
requests and recover delayed acknowledgements, including deleted earlier
working comments. Preserve automatic replies for legacy connections
without saved review configuration. Preserve partial publication
evidence and quarantine uncertain automatic fallbacks without blocking
Board messages or questions.
- Reorganize Settings and Access with rich slash-skill instructions,
numeric passing scores, clear automation controls, formal-review
tooltips, member and contributor sections, and verified App branding
links. Preserve invalid score drafts and automation choices across tabs.
- Paginate repositories in 20-row batches with search and a true
connection-wide toggle. Batch verification at GitHub's 500-ID token
limit. Keep saved repository overrides while hiding their editor.
- Give each review a detail URL that remains usable beyond the newest
100 records. Synchronize the manager OpenAPI contracts and add recovery,
authorization, UI, and browser regressions.
- Reconcile the current master branch and retain its agent avatar,
feature catalog, and extracted heartbeat preparation code. Preserve a
saved test-drive port and recover from an occupied high port.

## Verification

- Focused UI, independent experimental-setting, and CLI tests: 199
passed.
- `pnpm -r typecheck`, `pnpm build`, and `pnpm check:token-gates`
passed. The broad local Vitest attempt was interrupted after resource
timeouts and stale expectations; the affected regressions passed focused
reruns. The latest-head full CI matrix passed, including all browser
shards, server/chat suites, builds, typechecking, canary packaging, and
Docker context integrity. A Docker Hub 429 required a CI retry; it
passed without changing the code.
- Final review repairs: 127 attachment/event tests and server typecheck
passed. All 13 final integration regressions passed under the normal CI
timeout, covering legacy reply compatibility, deleted coalesced
comments, inline-only review completion, progress edits, and native
final recovery. Restart-safe description/review attachments passed the
attachment suite.
- Final regressions: four reply/lifecycle tests, both native GitHub wait
tests, 171 feature-gate/reply-contract tests, the routed review preview,
and five scheduler/reply regressions passed. The final fixture repair
also passed all six setup-continuation cases and all three complete
chat-test shards in CI, covering terminal receipts and retries under the
normal CI timeout. One loaded-host receipt run exceeded its local
timeout; the exact case passed in an isolated rerun and the complete CI
shard.
- GitHub integration tests cover personal and organization setup, retry
recovery, edited mentions, attachment provenance, coalesced requests,
delayed acknowledgements, partial review writes, old review URLs, and
company boundaries.
- Browser qualification: both GitHub journeys, all five provider
setup/management journeys, and the GitHub uncertain-send recovery
journey passed. GitHub setup, reconnect, and task replies run with chat
disabled; chat enabled alone cannot expose GitHub bots. The disposable
qualification database was removed after testing.
- Earlier live qualification verified App-owned issue replies, native
slash-skill invocation, progress comment edits, and a 5/5 PR review with
a passing current-head check in the dedicated permissions-smoke
repository. These live checks did not use personal credentials as bot
execution authority.

## Risks

- Deploy the merged Cloud gateway protocol before the stack update. Each
callback and encrypted event must retain the original instance and
tenant binding.
- Migration 0323 uses idempotent column additions for test installations
that already applied the earlier draft migration number.
- A verified connection does not prove runtime isolation or a completed
review. Runtime checks remain separate.
- Required merge checks must be configured in GitHub. A passing numeric
score does not formally approve a PR; approval and request-changes tools
remain opt-in.
- Existing-App credentials cannot silently renew an uncertain manifest
exchange. Recovery preserves the existing App, draft, connection, and
agent.
- Repository changes save immediately. Global toggles affect all
currently available repositories, including unloaded rows, without
granting new installation access.
- A failed or uncertain tool write suppresses automatic fallback text;
the governed outbox retains its evidence. Deleted or replaced response
comments are not recreated through a personal credential fallback.
- GitHub logo upload remains an optional human action in GitHub App
settings. Runtime provisioning, delegated setup, screenshot publication,
and production push delivery remain deferred.

## Model Used

OpenAI Codex, based on GPT-6, with tool use and code execution. The
exact runtime model identifier and context size are not exposed in this
session.

## 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 references)
- [x] My branch name describes the change and contains no internal
Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass (focused suites; complete
test matrix is checked in CI)
- [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-10-09 17:01:20 -05:00

1258 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", async (importOriginal) => ({
...await importOriginal<typeof import("@/hooks/useChatConnectorsEnabled")>(),
useChatConnectorsEnabled: () => ({ enabled: true, githubEnabled: 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]);
});
});