Files
PaperClipAI/ui/src/components/task-chat/TaskChatBubble.test.tsx
T
DottaandPaperclip 889947c238 feat: add experimental native chat connectors (#13038)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - People also ask agents for work in their existing chat tools.
> - Each external conversation needs one task and a current authorized
source.
> - Retries, Stop, and provider failures must not duplicate work or
expose private data.
> - The first chat PR establishes the opt-in provider and data
contracts.
> - This PR adds experimental channel integration and its durable
control plane.
> - Users can request work from connected channels and inspect delivery
in Paperclip.

## Linked Issues or Issue Description

Refs #13100 and #13092. This is the second of exactly two chat PRs.
Foundation #13100 is merged and changed 143 files. Runner prerequisite
#13092 is also merged. This PR changes 400 files against master, below
the 500-file review limit. It contains no wireframe images or HTML
galleries.

## What Changed

- Add native Slack, GitHub, Microsoft Teams, Telegram, and Discord chat
connections. Keep chat disabled unless the operator enables experimental
chat connectors. Preserve the production GitHub tool connection and its
normal setup path.
- Bind each provider bot identity to one immutable Paperclip agent. Bind
each admitted external conversation to one task. Paperclip owns tasks,
runs, permissions, and audit records.
- Add durable admission, per-conversation queues, questions, task
controls, progress, final replies, images, files, and delivery receipts.
Board comments remain internal unless explicitly sent to the channel.
- Check current identity, provider reach, resource access, credentials,
runtime generation, and exact source before provider effects. Keep
private responses private. Never send raw reasoning, private logs,
credentials, or tool arguments.
- Hold uncertain sends for explicit audited resolution. Make Board
Send-to-channel atomic and idempotent. Keep reconnect and setup
credentials in Paperclip secret storage.
- Preserve current native-runner authority across retries, lost
acknowledgements, and recovery. Keep immutable input and completion
contracts separate from newer user input. Receipt reconciliation cannot
launch a provider.
- Reconcile chat close/new ordering and provider-effect lock order.
Audit resource access changes in the same transaction. Submit only the
selected resource from each UI toggle so stale pages cannot undo
unrelated access changes.
- Drain Codex stdout before certifying process exit. Bound the drain
with the existing shutdown grace. Preserve observed terminal authority
without treating an undrained process as successful or reusable.
- Incorporate master `018ca5da` with its ACP Stop, mobile task layout,
runner packaging, and official lock changes. Preserve dedicated
chat-answer continuations in both directions when ordinary queued
comments are adopted after Stop.
- Fence late adapter readiness behind an earlier Stop for the same run.
Preserve verified cleanup for registered adapters. Handle single Stop,
agent pause, duplicate Stops, and failure release without creating a
false cancellation receipt.
- Incorporate master's `6dd48cad4` wake-queue extraction. Preserve exact
failed-chat retry authorization and lineage, retired question-source
suppression, and the block on generic recovery that would discard the
admitted source. Fresh deferred input retains its separate promotion
path.
- Incorporate master `2a05b5ed3` and its queue-admission extraction,
simplified transaction ports, and separate runner CI job. Preserve exact
durable receipts, actor separation, and dedicated-answer isolation
through the new module. A failed receipt insert rolls back the
accompanying deferred-wake merge.

## Verification

Current head: `afe19299d06253cb628eb398e91d1200ea9f412a`, incorporating
master `2a05b5ed3457ea33efd6895520447d1d97fe98d8`. The conflicts are
resolved. This successor fixes two test-harness boundaries exposed by
CI: per-case route-module preparation and actual durable-save completion
before intentional runner termination. Production code and all existing
test/turn deadlines are unchanged. [Exact-head Greptile
review](https://github.com/paperclipai/paperclip/pull/13038#issuecomment-5587250594)
is **5/5**, completed September 10 at 13:20:55 UTC, with no actionable
findings or open review threads. [Fresh exact-head
CI](https://github.com/paperclipai/paperclip/actions/runs/34481724341)
passes **all 24 jobs**, including Build and both required aggregates.
Normal exact-head guarded merge was attempted and rejected by the
remaining branch approval policy: CODEOWNER review is required and no
human approval is present. Normal **squash auto-merge is enabled** as of
September 10 at 13:36:26 UTC. Requested CODEOWNERS have been notified;
no approval bypass or self-approval was used. Earlier-head results below
remain historical evidence, not qualification of this successor.

- Final exact-head Linux evidence: 995/995 chat integration cases; 36/36
agent-skills routes; 35/35 runner live-session cases, including real
process kill/resume; 1948 runner Vitest cases with three existing
benchmark/platform guards; 870/870 API-authority cases; and 104 browser
cases with four existing optional skips. Rust, conformance/replay, full
repository build, typecheck, canary, all server/workspace shards, and
both required aggregates pass with normal CI concurrency. Earlier failed
attempts remain recorded below.

- Latest test-only qualification: 141/141
route/permissions/authentication cases pass in separate cold forks, with
plain server types and independent review clear. The real-runner suite
passes 35/35, with plain runner types and independent review clear. A
controlled premature-save acknowledgement fails as expected; matching
ownership/effect/process evidence, rejected saves, real turn outcome,
test abort, and pre-kill liveness are covered. No local reproduction of
the original CI scheduling failure is claimed. The preceding [CI
run](https://github.com/paperclipai/paperclip/actions/runs/34479680858)
passes 21/24 jobs, including all 995 Linux chat cases and browser
aggregate (104 passed, four existing optional skips); only Build, the
skills serialized shard, and the required verification aggregate fail.
Its exact-head Greptile review was 5/5. Both failed job logs are
retained.

- Final fixture qualification: all eight focused Discord cases and all
995 chat integration cases pass. The exact modal statement/PID is
observed before taking the real connection lock; the test then proves
its actual blocking relationship before mutation. Original SQL
execution, provider behavior, negative assertions, and 1s/15s timeouts
remain unchanged. Independent review is clear and test/production hashes
remain frozen. The preceding [CI
attempt](https://github.com/paperclipai/paperclip/actions/runs/34477184777)
passed 22 jobs, including Build/runner, typecheck, canary, all other
test shards, and browser aggregate (104 passed, four existing optional
skips); the two fixture failures and failed verification aggregate
remain recorded, not relabeled as a pass.

- Current queue-module composition: 308/308 recovery/batching/queue/Stop
tests; 995/995 full chat integration; 89/89 module tests, including real
PostgreSQL receipt-insert rollback; 24/24 workflow/module-boundary
tests; plain server and UI types. All four actual local process/ACP
browser paths pass in 1.4 minutes. Fresh databases, no skips or retries,
stable reviewed source hashes. The initial boundary failure is retained;
its no-op service wrapper was removed without changing recovery context
or weakening the check. An exploratory standalone test-directory
typecheck fails because its new upstream transformation config is not a
standalone typechecking project; standard CI/build does not invoke it,
and no configuration was weakened to suppress those diagnostics.

- The preceding head `e02a63d462ce5d47433b0aeb632bb6fd20aab1ba` passed
[all 24 CI
jobs](https://github.com/paperclipai/paperclip/actions/runs/34436462958)
and exact-head Greptile review at 5/5. Required CODEOWNER review
prevented its normal merge before master advanced again.

- Final extracted-module composition: 307/307 recovery, batching, queue
and Stop-control tests; 995/995 full chat integration; 49/49 module
tests including eight PostgreSQL adapter cases; and 19/19 issue-update
tests. Plain server types pass. All four actual local process/ACP
browser paths pass in 1.3 minutes. Fresh databases, no skips or retries
in these cohorts, frozen source hashes, and independent review clear.

- The preceding head `3e4e1c1c` passes [all PR CI
jobs](https://github.com/paperclipai/paperclip/actions/runs/34415826820),
including Build and required `ci / verify` and `ci / e2e`. Both the
original Rust failure and the previously load-sensitive lineage fixture
pass with unchanged Linux concurrency. Master advanced afterward and
required this reconciliation.
- Final master composition: 448/448 focused UI tests, 186/186 adapter
tests, 24/24 queue/control tests, and 11/11 packaging tests. Plain UI,
server, shared, and adapter types pass. Token gates and diff checks
pass. Independent server and UI reviews are clear.
- Stop-registration regression: both real-service cases fail against
exact `a95` source and pass with the fix. The full corrected
recovery/control suite passes 265/265. Duplicate-owner and failed-Stop
controls also pass. Plain server types pass. The readiness barrier
prevents provider startup without adding an acknowledgment to an already
terminal run.
- Final qualification strengthens terminal-field equality and repeats
both affected cases successfully on a fresh database. All four actual
local process/ACP browser paths pass again in 1.3 minutes, without skips
or retries. The final screenshot shows Cancelled, a paused subtree,
retained input, and no error toast.
- Two new actual-service regressions fail before the merge fix. They
prove that queued-comment adoption could consume a dedicated chat answer
or add unrelated input to that answer. The fixed four-case cohort
passes, including ordinary upstream continuation and adapter Stop
controls. Full recovery passes 257/257. All four actual local
process/ACP Stop browser flows pass in 1.4 minutes, without skips or
retries, on a fresh database.
- The unchanged runner artifact was qualified with 171/171 transport
tests, 870/870 API-authority tests, conformance 1/1, and replay 11/11.
Six controlled reader tests prove the exit/drain repair. Its local
serial Rust workspace passed 546 top-level cases plus two invoked
helpers; the later passing Linux CI supplies default-concurrency
evidence.
- Prior exact-source full chat integration passes 995/995. Settings
regressions cover concurrent stale pages, 501 destinations, pending
state, rejected updates, and explicit retry. These deterministic tests
do not prove live provider behavior.
- Retained failed attempts and their causes are in the [qualification
log](https://github.com/paperclipai/paperclip/blob/afe19299d06253cb628eb398e91d1200ea9f412a/doc/plans/chat-adapters/2026-09-08-chat-queue-and-webhook-repair.md).
The first merge adapter run timed out while macOS slept for 290 seconds.
Its unchanged repeat passed with a temporary sleep guard. No assertion,
deadline, or CI gate was weakened.

Review commands include `pnpm --filter @paperclipai/server exec vitest
run src/__tests__/heartbeat-process-recovery.test.ts
src/__tests__/issue-queued-comments-routes.test.ts` and `pnpm exec
playwright test --config tests/e2e/playwright.config.ts
tests/e2e/acp-stop-continuation.spec.ts`. Database suites require fresh
disposable databases. See the [browser
runbook](https://github.com/paperclipai/paperclip/blob/afe19299d06253cb628eb398e91d1200ea9f412a/doc/plans/chat-adapters/2026-09-04-chat-adapters-browser-e2e-runbook.md)
for provider setup and separate live acceptance steps.

## Risks

- This remains experimental. Deterministic tests and bounded live
evidence do not establish every provider feature, tenant, permission
layout, or media shape. Teams work-tenant qualification is still open.
- Failed and uncertain provider effects remain visible and can require
operator action. A transport receipt does not prove recipient
visibility.
- Native controller and runner artifacts must remain compatible.
Preserve lease ownership, terminal authority, source binding, and
quarantine during future changes.
- Access and audit rows commit together, but activity notifications
remain best-effort. This is not a new durable event outbox.
- The PR operation does not deploy a live server, replace its runner, or
change provider permissions. Remaining live qualification is documented
in the [temporary
handoff](https://github.com/paperclipai/paperclip/blob/afe19299d06253cb628eb398e91d1200ea9f412a/doc/plans/chat-adapters/2026-09-08-open-qualification-followups.md).

## Model Used

OpenAI Codex assisted with implementation, tool execution, testing, and
review. The work records `gpt-6-astra` assistance. The environment does
not report a context-window size. No private reasoning traces are
included.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-09-10 10:06:45 -05:00

501 lines
17 KiB
TypeScript

// @vitest-environment jsdom
import type { ReactNode } from "react";
import type { IssueAttachment } from "@paperclipai/shared";
import { flushSync } from "react-dom";
import { createRoot, type Root } from "react-dom/client";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { ThemeProvider } from "@/context/ThemeContext";
import { IssueGalleryContext } from "@/context/IssueGalleryContext";
import { TaskChatBubble } from "./TaskChatBubble";
import type { TaskChatMessageItem } from "./task-chat-model";
describe("TaskChatBubble attachment chips", () => {
let container: HTMLDivElement;
let root: Root | null = null;
beforeEach(() => {
container = document.createElement("div");
document.body.appendChild(container);
root = createRoot(container);
});
afterEach(() => {
flushSync(() => root?.unmount());
root = null;
container.remove();
});
function renderMessage(
text: string,
author: TaskChatMessageItem["author"] = "human",
attachments: IssueAttachment[] = [],
) {
const item: TaskChatMessageItem = { id: "m1", kind: "message", author, text };
flushSync(() =>
root!.render(
<ThemeProvider>
<TaskChatBubble item={item} attachments={attachments} />
</ThemeProvider>,
),
);
}
it("opens attachment images in the shared task gallery", () => {
const openGallery = vi.fn(() => true);
const contentPath = "/api/attachments/shared-image/content";
flushSync(() => root!.render(
<ThemeProvider>
<IssueGalleryContext.Provider value={openGallery}>
<TaskChatBubble item={{ id: "m1", kind: "message", author: "agent", text: `![Proof](${contentPath})` }} />
</IssueGalleryContext.Provider>
</ThemeProvider>,
));
const image = container.querySelector<HTMLImageElement>(`img[src="${contentPath}"]`);
expect(image).not.toBeNull();
flushSync(() => image!.click());
expect(openGallery).toHaveBeenCalledWith(contentPath);
expect(document.querySelector('[role="dialog"]')).toBeNull();
});
it("renders a file reference as an attachment chip linking to the file", () => {
renderMessage("Here you go.\n\n[notes.txt](/api/attachments/abc/content) ");
const group = container.querySelector('[data-testid="task-chat-bubble-attachments"]');
expect(group).not.toBeNull();
expect(group?.textContent).toContain("notes.txt");
expect(group?.textContent).toContain("Text");
const link = group?.querySelector<HTMLAnchorElement>("a[href='/api/attachments/abc/content']");
expect(link).not.toBeNull();
// The link-only line left the rendered body; the prose stayed.
expect(container.textContent).toContain("Here you go.");
expect(container.textContent).not.toContain("(/api/attachments/abc/content)");
});
it("renders a chip-only row when the message body is just the file link", () => {
renderMessage("[report.pdf](/api/attachments/r1/content)", "agent");
expect(container.querySelector('[data-testid="task-chat-bubble-attachments"]')).not.toBeNull();
// No empty bubble is left behind once the only line is chipped.
expect(container.textContent).toContain("report.pdf");
expect(container.textContent).toContain("PDF");
});
it("leaves messages without file references untouched", () => {
renderMessage("Just words and a [normal link](https://example.com).");
expect(container.querySelector('[data-testid="task-chat-bubble-attachments"]')).toBeNull();
expect(container.textContent).toContain("Just words");
});
it("renders an extensionless PNG attachment as a thumbnail", () => {
renderMessage(
"Done.\n\n[desktop Default](/api/attachments/img/content)",
"agent",
[
attachment({
id: "img",
originalFilename: "desktop Default",
contentType: "image/png",
byteSize: 4096,
}),
],
);
const media = container.querySelector('[data-testid="task-chat-bubble-media"]');
expect(media).not.toBeNull();
expect(media?.querySelector("img")?.getAttribute("alt")).toBe("desktop Default");
expect(container.querySelector('[data-testid="task-chat-bubble-attachments"]')).toBeNull();
});
it("shows three thumbnails and an overflow tile for five images", () => {
const links = Array.from(
{ length: 5 },
(_, index) => `[shot ${index + 1}](/api/attachments/img${index + 1}/content)`,
).join("\n");
const attachments = Array.from({ length: 5 }, (_, index) =>
attachment({
id: `img${index + 1}`,
originalFilename: `shot ${index + 1}`,
contentType: "image/png",
}),
);
renderMessage(links, "agent", attachments);
const media = container.querySelector('[data-testid="task-chat-bubble-media"]');
expect(media?.querySelectorAll("img")).toHaveLength(3);
expect(media?.textContent).toContain("+2");
const secondThumbnail = media?.querySelectorAll("button")[1];
flushSync(() => secondThumbnail?.click());
expect(document.body.textContent).toContain("2 / 5");
});
it("shows a typed file chip with its stored size", () => {
renderMessage(
"[verification.log](/api/attachments/log/content)",
"agent",
[
attachment({
id: "log",
originalFilename: "verification.log",
contentType: "text/plain",
byteSize: 14 * 1024,
}),
],
);
const group = container.querySelector('[data-testid="task-chat-bubble-attachments"]');
expect(group?.textContent).toContain("Log · 14.0 KB");
});
it("renders only the provider attachments bound to this comment without Markdown refs", () => {
renderMessage("Please inspect both files.", "human", [
attachment({
id: "photo",
originalFilename: "evidence.png",
contentType: "image/png",
byteSize: 4096,
}),
attachment({
id: "notes",
originalFilename: "notes.txt",
contentType: "text/plain",
byteSize: 128,
}),
attachment({
id: "other-comment",
issueCommentId: "m2",
originalFilename: "unrelated.txt",
contentType: "text/plain",
}),
]);
expect(
container.querySelector('[data-testid="task-chat-bubble-media"] img')
?.getAttribute("alt"),
).toBe("evidence.png");
expect(container.textContent).toContain("Images · 1");
const group = container.querySelector(
'[data-testid="task-chat-bubble-attachments"]',
);
expect(group?.textContent).toContain("notes.txt");
expect(group?.textContent).not.toContain("unrelated.txt");
});
it("does not duplicate a bound attachment already referenced in the comment", () => {
renderMessage(
"[notes.txt](/api/attachments/notes/content)",
"human",
[
attachment({
id: "notes",
originalFilename: "notes.txt",
contentType: "text/plain",
}),
],
);
const group = container.querySelector(
'[data-testid="task-chat-bubble-attachments"]',
);
expect(group?.querySelectorAll("a")).toHaveLength(1);
expect(container.textContent).toContain("Files · 1");
});
});
function attachment(overrides: Partial<IssueAttachment>): IssueAttachment {
const id = overrides.id ?? "attachment";
return {
id,
companyId: "company",
issueId: "issue",
issueCommentId: "m1",
assetId: `asset-${id}`,
provider: "paperclip",
objectKey: id,
contentType: "application/octet-stream",
byteSize: 1,
sha256: id,
originalFilename: id,
createdByAgentId: "agent",
createdByUserId: null,
createdAt: new Date("2026-09-02T00:00:00Z"),
updatedAt: new Date("2026-09-02T00:00:00Z"),
contentPath: `/api/attachments/${id}/content`,
openPath: `/api/attachments/${id}/content`,
downloadPath: `/api/attachments/${id}/content?download=1`,
...overrides,
};
}
describe("TaskChatBubble accent-bubble text color", () => {
let container: HTMLDivElement;
let root: Root | null = null;
beforeEach(() => {
container = document.createElement("div");
document.body.appendChild(container);
root = createRoot(container);
});
afterEach(() => {
flushSync(() => root?.unmount());
root = null;
container.remove();
});
function render(item: TaskChatMessageItem) {
flushSync(() =>
root!.render(
<ThemeProvider>
<TaskChatBubble item={item} />
</ThemeProvider>,
),
);
}
it("marks the human bubble's markdown as on-accent so prose text follows text-white", () => {
render({ id: "m1", kind: "message", author: "human", text: "when a new task is created…" });
const body = container.querySelector(".paperclip-markdown");
expect(body).not.toBeNull();
// Without this class the light-mode prose body color reads as black on blue.
expect(body?.className).toContain("paperclip-markdown-on-accent");
});
it("leaves the neutral agent bubble on default prose colors", () => {
render({ id: "m1", kind: "message", author: "agent", authorName: "CEO", text: "Final reply." });
const body = container.querySelector(".paperclip-markdown");
expect(body).not.toBeNull();
expect(body?.className).not.toContain("paperclip-markdown-on-accent");
});
});
describe("TaskChatBubble agent page-surface treatment", () => {
it("renders agent prose without a card background or constrained width", () => {
const container = document.createElement("div");
document.body.appendChild(container);
const root = createRoot(container);
flushSync(() =>
root.render(
<ThemeProvider>
<TaskChatBubble
item={{ id: "agent-message", kind: "message", author: "agent", authorName: "Codex", text: "A long-form agent response" }}
/>
</ThemeProvider>,
),
);
const bubble = container.querySelector('[data-testid="task-chat-agent-bubble"]');
expect(bubble).not.toBeNull();
expect(bubble?.className).toContain("w-full");
expect(bubble?.className).toContain("bg-transparent");
expect(bubble?.className).toContain("px-1");
expect(bubble?.className).not.toContain("rounded-2xl");
expect(bubble?.className).not.toContain("bg-(--bubble-agent)");
expect(bubble?.className).not.toContain("max-w-(--pct-85)");
flushSync(() => root.unmount());
container.remove();
});
});
describe("TaskChatBubble verification caveats", () => {
it("renders non-blocking not-run verification beneath the durable agent reply", () => {
const container = document.createElement("div");
document.body.appendChild(container);
const root = createRoot(container);
flushSync(() => root.render(
<ThemeProvider>
<TaskChatBubble item={{
id: "agent-message",
kind: "message",
author: "agent",
authorName: "Runner",
text: "The implementation is complete.",
verificationCaveats: [{
commandOrCheck: "Run npm test",
reasonCode: "tool_unavailable",
detail: "Node and npm are unavailable in this environment.",
}],
}} />
</ThemeProvider>,
));
const caveat = container.querySelector('[data-testid="task-chat-verification-caveats"]');
expect(caveat?.textContent).toContain("Verification caveat");
expect(caveat?.textContent).toContain("Run npm test");
expect(caveat?.textContent).toContain("tool unavailable");
expect(caveat?.textContent).toContain("Node and npm are unavailable");
flushSync(() => root.unmount());
container.remove();
});
});
describe("TaskChatBubble interstitial self-talk (PAP-357)", () => {
let container: HTMLDivElement;
let root: Root | null = null;
beforeEach(() => {
container = document.createElement("div");
document.body.appendChild(container);
root = createRoot(container);
});
afterEach(() => {
flushSync(() => root?.unmount());
root = null;
container.remove();
});
function renderItem(item: TaskChatMessageItem) {
flushSync(() =>
root!.render(
<ThemeProvider>
<TaskChatBubble item={item} />
</ThemeProvider>,
),
);
}
it("renders nothing — self-talk is ambient signal, suppressed in this view", () => {
renderItem({
id: "m1",
kind: "message",
author: "agent",
authorName: "CEO",
text: "Let me check the **adapter** first.",
interstitial: true,
streaming: true,
});
expect(container.textContent).toBe("");
expect(container.querySelector('[data-testid="task-chat-agent-avatar"]')).toBeNull();
});
it("keeps the bubble and avatar header for non-interstitial agent replies", () => {
renderItem({
id: "m1",
kind: "message",
author: "agent",
authorName: "CEO",
text: "Final reply.",
});
expect(container.querySelector('[data-testid="task-chat-interstitial"]')).toBeNull();
expect(container.querySelector('[data-testid="task-chat-agent-avatar"]')).not.toBeNull();
expect(container.textContent).toContain("CEO");
});
});
describe("TaskChatBubble footer line (round 9)", () => {
let container: HTMLDivElement;
let root: Root | null = null;
beforeEach(() => {
container = document.createElement("div");
document.body.appendChild(container);
root = createRoot(container);
});
afterEach(() => {
flushSync(() => root?.unmount());
root = null;
container.remove();
});
function renderBubble(item: TaskChatMessageItem, attachedTurn?: ReactNode) {
flushSync(() =>
root!.render(
<ThemeProvider>
<TaskChatBubble item={item} attachedTurn={attachedTurn} />
</ThemeProvider>,
),
);
}
it("shows the timestamp always — not only on hover", () => {
renderBubble({ id: "m1", kind: "message", author: "agent", authorName: "CEO", text: "Done.", timestamp: "2:34 PM" });
const stamp = [...container.querySelectorAll("span")].find((el) => el.textContent === "2:34 PM");
expect(stamp).not.toBeNull();
expect(stamp?.className).not.toContain("opacity-0");
expect(stamp?.className).not.toContain("group-hover");
});
it("renders the attached turn in place of the plain timestamp footer", () => {
renderBubble(
{ id: "m1", kind: "message", author: "agent", authorName: "CEO", text: "Done.", timestamp: "2:34 PM" },
<div data-testid="fake-attached-turn">2:34 PM · Worked</div>,
);
const slot = container.querySelector('[data-testid="task-chat-bubble-attached-turn"]');
expect(slot).not.toBeNull();
expect(slot?.querySelector('[data-testid="fake-attached-turn"]')).not.toBeNull();
// The plain footer timestamp is replaced (the attached line carries it).
const plain = [...container.querySelectorAll("span")].filter((el) => el.textContent === "2:34 PM");
expect(plain).toHaveLength(0);
});
});
describe("TaskChatBubble footer actions (PAP-413)", () => {
let container: HTMLDivElement;
let root: Root | null = null;
beforeEach(() => {
container = document.createElement("div");
document.body.appendChild(container);
root = createRoot(container);
});
afterEach(() => {
flushSync(() => root?.unmount());
root = null;
container.remove();
});
function render(item: TaskChatMessageItem, opts?: { attachedTurn?: ReactNode; actions?: ReactNode }) {
flushSync(() =>
root!.render(
<ThemeProvider>
<TaskChatBubble item={item} attachedTurn={opts?.attachedTurn} actions={opts?.actions} />
</ThemeProvider>,
),
);
}
const actions = <div data-testid="fake-actions">actions</div>;
it("hands actions to the attached turn (not this wrapper) so they ride the summary row", () => {
render(
{ id: "m1", kind: "message", author: "agent", authorName: "CEO", text: "Done.", timestamp: "2:34 PM" },
{ attachedTurn: <div data-testid="fake-attached-turn">2:34 PM · Worked</div>, actions },
);
const slot = container.querySelector('[data-testid="task-chat-bubble-attached-turn"]');
expect(slot).not.toBeNull();
// The turn owns the footer line; the bubble no longer places actions beside
// it (they ride the turn's `leading` slot, anchored to the summary line).
expect(slot?.querySelector('[data-testid="fake-attached-turn"]')).not.toBeNull();
expect(slot?.querySelector('[data-testid="fake-actions"]')).toBeNull();
});
it("keeps runless timestamp left and actions at the stable right edge", () => {
render(
{ id: "m1", kind: "message", author: "agent", authorName: "CEO", text: "Done.", timestamp: "2:34 PM" },
{ actions },
);
expect(container.querySelector('[data-testid="fake-actions"]')).not.toBeNull();
const stamp = [...container.querySelectorAll("span")].find((el) => el.textContent === "2:34 PM");
expect(stamp).not.toBeNull();
const actionNode = container.querySelector('[data-testid="fake-actions"]')!;
expect(stamp!.compareDocumentPosition(actionNode) & Node.DOCUMENT_POSITION_FOLLOWING).not.toBe(0);
expect(actionNode.parentElement?.className).toContain("justify-between");
});
it("omits the actions row entirely when none are supplied (human bubble)", () => {
render({ id: "m1", kind: "message", author: "human", text: "Hi", timestamp: "2:34 PM" });
expect(container.querySelector('[data-testid="fake-actions"]')).toBeNull();
const stamp = [...container.querySelectorAll("span")].find((el) => el.textContent === "2:34 PM");
expect(stamp).not.toBeNull();
});
});