mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-02 16:58:52 +01:00
<!-- entire-trail-link-start --> https://entire.com/gh/paperclipai/-/trails/123/changes/paperclip/123 <!-- entire-trail-link-end --> ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - People save tasks, write documents, make decisions and send board messages. > - A disconnect can hide a response after the server accepts a write. > - Recovery must keep the original account, task and request key. > - The merged connection foundation in #15754 handles reads and shared outage state. > - This change adds bounded write recovery and explicit actions when recovery stops. ## Linked Issues or Issue Description **What happened?** Temporary failures could lose edits, report accepted writes as failures, or require people to copy and send input again. A retry could target a newly selected task or account. Restoring attachments could create a second task. **Expected behavior** Keep the draft, its owner and its target. Retry only operations with a server contract that prevents duplicate writes. Verify uncertain results. Show conflicts and permanent failures, with an explicit resend or cancel action. **Steps to reproduce** 1. Save a task title during an outage, then open another task before recovery. 2. Restore a task creation that needs files, selecting those files in another order. 3. Lose a document or decision response, then interrupt the verification read. 4. Switch accounts while a create, upload or connected-channel publication is pending. 5. Type and erase a new-task draft before the first account lookup completes, then reopen it. This PR carries the write layer from #15769 and its review fixes. It targets master after #15754 merged. Related test cleanup #16952 already covers the unchanged copy-link toast test; this PR does not duplicate that work. ## What Changed - Add bounded autosave and submit jobs for supported writes, with pending, conflict and manual retry states. Retain admitted autosaves after navigation and preserve newer task revisions. - Keep each job with its original account, task and operation. First account resolution adopts admitted startup work; a later account change cancels old work. Remount inline and document editors when their owner or document subject changes. - Preserve task-creation keys and immutable request snapshots through file reattachment. Restore generated document keys before comparing reselected files. Reject changed requests instead of creating a second task. - Check the original account scope before creates and each upload. Save successful upload receipts before stopping on an account change. Identify attachments by content digest and metadata. - Verify uncertain document and decision results. Replay only plain, keyed comments automatically; combined reassignment, reopen and run-setting changes require receipt reconciliation or cancel. Settle each request once when a receipt races its retry. - Scope drafts and connected-channel publication reads to their owner. Keep unowned older records unread and unreplayed, with an explicit confirmed discard action after Activity inspection. Preserve typing through the first session lookup, keep erased text erased, and report browser persistence only when storage succeeds. - Wait for the first account lookup before sending startup status changes or decisions. Retry failed required lookups with a fixed limit and surface exhaustion to the original action. Preserve uncertain comment keys on account cancellation. Check the account generation before a comment retry calls its sender and again immediately before POST after asynchronous preparation. Retire only that request’s optimistic echo on completion. - Return an ordinary comment’s accepted same-company, same-task, same-user receipt before workspace reopening, task status changes or wakeups. Reused keys with changed text still conflict. Complete reference and activity records through the same finalizer for initial sends and accepted retries. It locks the task before its comment, matching task and company deletion, comment removal and tombstoning, rejects removed or tombstoned comments, repairs references and inserts a missing activity record in one transaction, and publishes after commit. - Remove reader-only record and comment-body size caps so accepted browser writes remain readable, including JSON-escaped comment requests in local and session storage. Update four existing Storybook fixtures to use owned draft keys. - Document the write contracts and add regression and real browser recovery coverage. - Add the exact reviewed-save recovery regression for both composer implementations and reloads. Align receipt completion, both comment deletion methods and company deletion with task deletion by locking tasks first. Cover real task and company deletion races. ## Verification - The exact reviewed-unknown-save regression fails in all four cases on original commit `1ed0af4186`. It passes with this PR for both composers, before and after reload. Cancel keeps the text and uploaded receipt. The retained draft sends, and the next message also sends. Run `pnpm exec vitest run --project @paperclipai/ui ui/src/components/composer-recovery.test.tsx`. - The new real PostgreSQL task-deletion race fails with SQLSTATE `40P01` on parent commit `f3253a00c4`. The company-deletion race also fails with `40P01` on `e8cf0e02dd`. All six receipt tests pass after the final lock-order fixes. They cover company deletion, task deletion, comment removal, tombstoning, concurrent cross-task references and interrupted reference repair. Run `pnpm exec vitest run --project @paperclipai/server server/src/__tests__/issue-comment-receipt-postgres.test.ts`. - The full UI run passed 9,656 of 9,659 tests across 816 files. Three cases failed under that run: two large-tree timeouts and one plugin-panel assertion. All 67 tests in those two files passed in an isolated rerun. These failures remain recorded; this does not claim a clean full UI run. - `pnpm -r typecheck`, `pnpm build`, token gates and map checks pass on the final change. The local full repository test command was started, then stopped when the delivery moved to this existing PR. Fresh PR CI must provide the full-suite gate. - A local Storybook walkthrough used the real rich editor. Cancel kept the restored text, Send cleared it after the simulated save, and a new draft enabled Send again. Storybook simulates submission; it is not staging acceptance. - Earlier verification on `f3253a00c4` recorded five browser journeys for title saves, cached-task offline recovery, startup recovery, accepted comment replay and session lookup failure. Those results remain prior-head evidence. No new staging deployment is claimed. - On `e8cf0e02dd`, all CI checks passed after one browser-shard rerun. Its first failure copied page text instead of YAML in an unrelated agent-configuration test. On final commit `35131d4380`, Greptile is 5/5 with no unresolved review threads. The first CI attempt has two failures outside this diff: runner close-attachment suspension and scheduled-retry teardown. The scheduled-retry file passes all 14 tests in isolation; the isolated runner test still fails locally. The single standard CI rerun passed both jobs, and the aggregate verification gate passed. All CI checks are green on `35131d4380`; Apex is 5/5 on that same commit with no unresolved findings. ## Risks - Automatic replay requires server duplicate prevention or result verification. Uncertain combined mutations require receipt observation or cancel and a fresh intentional send. - Old unowned form drafts remain stored but are not assigned to an account. Unowned channel records can be retired after Activity inspection; this never cancels an accepted remote update. - Browser storage and hashing can be unavailable. Storage failure is reported honestly. Without a digest, replay can duplicate an upload rather than silently drop a selected file. - Detached autosaves remain bounded and check account ownership on each attempt. Conflicts or exhaustion retain the draft for explicit recovery. - No schema, credential or agent permission change is included. This PR does not claim staging deployment or original-task acceptance. ## Model Used Anthropic Claude Opus 5.5 (`claude-opus-5-5`) produced the original implementation with tool use. OpenAI Codex, GPT-6 family, assisted with restoration, integration, verification and review fixes. This Codex session does not expose its exact serving model ID or context window size. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: devinfoley <139239+devinfoley@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Paperclip <noreply@paperclip.ing> Co-authored-by: Amy (Opus) <claude@users.noreply.github.com> Co-authored-by: Dotta <bippadotta@protonmail.com>
1412 lines
52 KiB
TypeScript
1412 lines
52 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";
|
||
import { queryKeys } from "@/lib/queryKeys";
|
||
const mockSession = vi.hoisted(() => ({ userId: "user-1" }));
|
||
vi.mock("@/api/auth", () => ({
|
||
authApi: { getSession: vi.fn(async () => ({ user: { id: mockSession.userId } })) },
|
||
}));
|
||
|
||
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 },
|
||
}));
|
||
// Lets a test report that automatic resends stopped, without running eight
|
||
// backoff rounds; otherwise the real hook runs.
|
||
const autoResendOverride = vi.hoisted(() => ({ stalled: false }));
|
||
vi.mock("@/hooks/useDurableSubmit", async (importOriginal) => {
|
||
const actual = await importOriginal<typeof import("@/hooks/useDurableSubmit")>();
|
||
return {
|
||
...actual,
|
||
useAutoResend: (options: Parameters<typeof actual.useAutoResend>[0]) => {
|
||
const result = actual.useAutoResend(options);
|
||
return autoResendOverride.stalled ? { ...result, stalled: true } : result;
|
||
},
|
||
};
|
||
});
|
||
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 } },
|
||
});
|
||
if (!existingQueryClient) queryClient.setQueryData(queryKeys.auth.session, { user: { id: mockSession.userId } });
|
||
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();
|
||
mockSession.userId = "user-1";
|
||
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();
|
||
autoResendOverride.stalled = false;
|
||
});
|
||
|
||
it("cancels an automatic resend and hides its draft after an account change", async () => {
|
||
mockChatEndpointsApi.publishBoardMessage.mockRejectedValue(new ApiError("Bad gateway", 502, {}));
|
||
const client = await renderBanner();
|
||
await composeAndSubmit("Private account A message");
|
||
expect(mockChatEndpointsApi.publishBoardMessage).toHaveBeenCalledTimes(1);
|
||
const retainedA = [...Array(sessionStorage.length)].map((_, index) => sessionStorage.getItem(sessionStorage.key(index)!));
|
||
mockSession.userId = "user-2";
|
||
await act(() => { client.setQueryData(queryKeys.auth.session, { user: { id: "user-2" } }); });
|
||
await flushReact();
|
||
await new Promise(resolve => setTimeout(resolve, 1_100));
|
||
await flushReact();
|
||
expect(mockChatEndpointsApi.publishBoardMessage).toHaveBeenCalledTimes(1);
|
||
expect(container.querySelector("textarea")?.value ?? "").not.toContain("Private account A message");
|
||
expect(container.textContent).not.toContain("Sending when reconnected");
|
||
expect([...Array(sessionStorage.length)].map((_, index) => sessionStorage.getItem(sessionStorage.key(index)!))).toEqual(retainedA);
|
||
client.clear();
|
||
});
|
||
|
||
it("ignores an old account's late receipt after the session changes", async () => {
|
||
let finish!: (result: unknown) => void;
|
||
mockChatEndpointsApi.publishBoardMessage.mockImplementationOnce(() => new Promise(resolve => { finish = resolve; }));
|
||
const client = await renderBanner();
|
||
await composeAndSubmit("Private pending account A message");
|
||
mockSession.userId = "user-2";
|
||
await act(() => { client.setQueryData(queryKeys.auth.session, { user: { id: "user-2" } }); });
|
||
await flushReact();
|
||
await act(() => { finish({ id: "publication-old", state: "published", attempts: 1 }); });
|
||
await flushReact();
|
||
expect(pushToastMock).not.toHaveBeenCalled();
|
||
expect(container.querySelector("textarea")?.value ?? "").not.toContain("Private pending account A message");
|
||
expect(sessionStorage.length).toBe(1);
|
||
client.clear();
|
||
});
|
||
|
||
it("restores only the original account's retained send after returning to it", async () => {
|
||
mockChatEndpointsApi.publishBoardMessage.mockRejectedValue(new ApiError("Bad gateway", 502, {}));
|
||
const client = await renderBanner();
|
||
await composeAndSubmit("Account A retained request");
|
||
const originalKey = mockChatEndpointsApi.publishBoardMessage.mock.calls[0][3];
|
||
mockSession.userId = "user-2";
|
||
await act(() => { client.setQueryData(queryKeys.auth.session, { user: { id: "user-2" } }); });
|
||
await flushReact();
|
||
await act(() => findButton(container, "Send to channel").click());
|
||
expect(container.querySelector("textarea")?.value).toBe("");
|
||
mockSession.userId = "user-1";
|
||
await act(() => { client.setQueryData(queryKeys.auth.session, { user: { id: "user-1" } }); });
|
||
await flushReact();
|
||
expect(container.querySelector("textarea")?.value).toBe("Account A retained request");
|
||
expect(mockChatEndpointsApi.publishBoardMessage).toHaveBeenCalledTimes(1);
|
||
mockChatEndpointsApi.publishBoardMessage.mockResolvedValueOnce({ id: "publication-recovered", state: "published", attempts: 1 });
|
||
await act(() => findButton(container, "Retry safely").click());
|
||
await flushReact();
|
||
expect(mockChatEndpointsApi.publishBoardMessage).toHaveBeenLastCalledWith("endpoint-1", "conversation-1", "Account A retained request", originalKey, []);
|
||
});
|
||
|
||
it("does not reveal or replay an older retained send without a known owner", async () => {
|
||
const key = boardSendDraftKey("company-1", "issue-1", "endpoint-1", "conversation-1");
|
||
const saved = JSON.stringify({ body: "Unowned private message", attachmentIds: [], idempotencyKey: "legacy-request-key-1", publication: null });
|
||
sessionStorage.setItem(key, saved);
|
||
await renderBanner();
|
||
expect(container.querySelector("textarea")?.value).toBe("");
|
||
expect(container.querySelector("textarea")?.disabled).toBe(true);
|
||
expect(container.textContent).toContain("Open Activity");
|
||
expect(container.textContent).not.toContain("Unowned private message");
|
||
expect(mockChatEndpointsApi.publishBoardMessage).not.toHaveBeenCalled();
|
||
expect(sessionStorage.getItem(key)).toBe(saved);
|
||
});
|
||
|
||
it.each([false, true])("can explicitly discard an unowned receipt without replaying its message (storage failure=%s)", async (storageFailure) => {
|
||
const key = boardSendDraftKey("company-1", "issue-1", "endpoint-1", "conversation-1");
|
||
const saved = JSON.stringify({ body: "Unowned private message", attachmentIds: [], idempotencyKey: "legacy-request-key-1", publication: null });
|
||
sessionStorage.setItem(key, saved);
|
||
await renderBanner();
|
||
await act(() => findButton(container, "Discard saved delivery record").click());
|
||
await flushReact();
|
||
expect(document.body.textContent).toContain("does not cancel an update");
|
||
const dialog = document.body.querySelector<HTMLElement>('[role="alertdialog"]')!;
|
||
expect(dialog).toBeTruthy();
|
||
await act(() => findButton(dialog, "Keep record").click());
|
||
await flushReact();
|
||
expect(sessionStorage.getItem(key)).toBe(saved);
|
||
expect(container.querySelector("textarea")?.disabled).toBe(true);
|
||
if (storageFailure) {
|
||
const remove = vi.spyOn(Object.getPrototypeOf(sessionStorage), "removeItem").mockImplementation(() => { throw new Error("Storage unavailable"); });
|
||
await act(() => findButton(container, "Discard saved delivery record").click());
|
||
await flushReact();
|
||
await act(() => findButton(document.body, "Discard record").click());
|
||
await flushReact();
|
||
expect(sessionStorage.getItem(key)).toBe(saved);
|
||
expect(container.querySelector("textarea")?.disabled).toBe(true);
|
||
expect(container.textContent).toContain("could not be discarded");
|
||
expect(mockChatEndpointsApi.publishBoardMessage).not.toHaveBeenCalled();
|
||
remove.mockRestore();
|
||
}
|
||
await act(() => findButton(container, "Discard saved delivery record").click());
|
||
await flushReact();
|
||
await act(() => findButton(document.body, "Discard record").click());
|
||
await flushReact();
|
||
expect(sessionStorage.getItem(key)).toBeNull();
|
||
await act(() => findButton(container, "Send to channel").click());
|
||
await flushReact();
|
||
expect(container.querySelector("textarea")?.disabled).toBe(false);
|
||
expect(container.querySelector("textarea")?.value).toBe("");
|
||
expect(mockChatEndpointsApi.publishBoardMessage).not.toHaveBeenCalled();
|
||
await act(() => setTextareaValue(container.querySelector("textarea")!, "Fresh deliberate message"));
|
||
mockChatEndpointsApi.publishBoardMessage.mockResolvedValueOnce({ id: "fresh-publication", 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).toHaveBeenCalledWith("endpoint-1", "conversation-1", "Fresh deliberate message", expect.not.stringMatching("legacy-request-key-1"), []);
|
||
});
|
||
|
||
it("asks for Resend now once automatic resends stop", async () => {
|
||
autoResendOverride.stalled = true;
|
||
mockChatEndpointsApi.publishBoardMessage.mockRejectedValue(
|
||
new ApiError("Bad gateway", 502, { error: "Bad gateway" }),
|
||
);
|
||
await renderBanner();
|
||
await composeAndSubmit();
|
||
expect(container.textContent).toContain("Couldn’t send this update yet.");
|
||
expect(container.textContent).toContain("Automatic resends stopped; choose Resend now");
|
||
expect(container.textContent).not.toContain("It resends on its own");
|
||
expect(findButton(container, "Resend now")).toBeTruthy();
|
||
});
|
||
|
||
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",
|
||
"user-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();
|
||
// A 5xx may have committed: it waits to resend with the same identity.
|
||
expect(container.textContent).toContain(
|
||
kind === "server-error"
|
||
? "Sending when reconnected…"
|
||
: "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",
|
||
"user-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",
|
||
"user-1",
|
||
),
|
||
),
|
||
).toMatchObject({
|
||
body: "Original conversation only",
|
||
idempotencyKey: originalCall[3],
|
||
publication: { id: "old-anchor" },
|
||
});
|
||
expect(
|
||
readBoardSendDraft(
|
||
boardSendDraftKey(
|
||
"company-1",
|
||
"issue-1",
|
||
"endpoint-2",
|
||
"conversation-2",
|
||
"user-1",
|
||
),
|
||
),
|
||
).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]);
|
||
});
|
||
});
|