Files
PaperClipAI/ui/src/components/IssueChatThreadSystemNotice.test.tsx
T
DottaandPaperclip 96bf004a79 fix: use persisted state for lifecycle continuation and retry budgets (#13888)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Its control plane decides when a task can continue, wait, stop, or
complete.
> - Legacy continuation could change when an agent changed its wording
without changing task state.
> - Shared attempt counts also let repair and infrastructure retries
affect each other's limits.
> - This pull request uses persisted state and separate, bounded
allowances for these decisions.
> - If automatic repair stops, the task explains what happened and
offers a guarded retry.
> - Paired tests and real-provider evaluations verify that Stop,
approvals, ownership, and spending limits remain authoritative.

## Linked Issues or Issue Description

Related work: Refs #13761, Refs #11126, Refs #13610. These cover
obsolete continuation dispatch and retry storms. Open and closed issues
and PRs were searched for related lifecycle, continuation, and retry
work.

**What happened?**
Legacy continuation depended on English wording and progress heuristics.
Repair, failure retry, and productive continuation could consume shared
counts. When bounded repair stopped, the task showed a technical
recovery message without a clear next action.

**Expected behavior**
Persisted disposition and owned execution paths determine the next
action. Missing disposition prompts bounded agent repair. Explicit work
mode determines planning mode. Narrative changes and raw activity counts
cannot replenish allowances. An exhausted repair shows a readable
notice. An explicit retry checks current controls and preserves the
assigned agent.

**Steps to reproduce**
Run `pnpm test:lifecycle-baseline`. The paired probes keep structured
state constant while varying completion, planning, blocker, and progress
prose. Run the explicit `lifecycle-baseline` and
`continuation-accounting` Product E2E suites for real-provider coverage.
In Storybook, open **Design previews / Recovery notice** to inspect the
production component's normal, pending, acknowledged, unavailable,
failure, and mobile states.

## What Changed

- Hide the image attachment button, icon, and drop/paste hint in answer
composers. Image paste and drop support remains available.
- Merge current master and retain both browser regression sets. Use a
production-stamped service worker in the offline recovery browser
fixture.
- Share one state-based legacy continuation decision across immediate,
delayed, and recovered dispatch. Bind bounded repairs to their source
run and episode.
- Remove title and description wording from work-mode authority. Agents
can still write requested plans in execution mode.
- Persist separate failure-retry and productive-continuation counters.
Disposition repair and resource waits cannot consume or reset those
allowances.
- Validate delayed repair identity, then recheck current gates before
provider dispatch. Fence native startup cancellation.
- Show **Agent needs attention**, a plain-language explanation, **Retry
agent**, and expandable details in both task interfaces. Report request
progress, acknowledgement, and errors inline.
- Store typed recovery notice metadata. Recognize older active notices
only through exact stored action and run IDs. Notice text never grants
retry authority.
- Use the existing recovery-action endpoint for retry. Recheck current
action, status, owner, agent availability, dependencies, active runs,
pending questions and confirmations, approvals, pause controls, and
budget. Duplicate requests do not wake twice.
- Add component, page, route, database, contract, and Storybook
coverage. Keep the scenario inventory and executable evals here.
Historical reports and snapshots live in the [commit-pinned
paperclip-evals
archive](https://github.com/paperclipai/paperclip-evals/blob/ce3e5afcd4a1184650f586a2b5b8be5874c66c8b/experiments/2026-09-lifecycle-authority/README.md).
- Preserve unsaved project fields while the same project URL changes to
its canonical alias. Do not reuse data across projects or companies.
This separate fix addresses the repeated repository-editor browser
failure without changing the browser test.
- Keep the development service worker from intercepting Vite module
reloads. Update the connection-intent browser fixture to record progress
and completion through the agent API.

## Verification

Merge preparation on September 25, commit
`c1e8e4b7ddd9fbc4913ed55ce21b8e12906c2f97`:

- Merged master `bd2030932` and resolved the browser test-list conflict
by keeping both sets of regressions.
- Deterministic lifecycle baseline: 1,090/1,090 assertions passed; no
failures, skips, or missing selected evidence. Unit 423, runner 184,
database integration 397, grading 86.
- Browser support: 17/17 passed. The offline recovery test first failed
with an unstamped development worker, then passed with the production
stamp. Its assertions are unchanged.
- Focused interaction UI and offline fallback tests: 19/19 passed.
Verified the custom-answer composer in Storybook: no attachment controls
or hint; entering an answer enables Next.
- Recursive typecheck, production build, token gates, and diff checks
passed. The worktree is clean. No new real-provider campaign was run.
- Current CI and review: [Current PR CI
passed](https://github.com/paperclipai/paperclip/actions/runs/36166011243):
55 successful checks and two optional Storybook skips. Greptile scored
this exact commit 5/5. Hiding the question attachment controls is an
intentional UI change; paste/drop remains available.

Earlier recovery UI verification, commit
`21be0fec0e90e86b6d662b8ee4831847cd041cdb`:

- Recursive typecheck, production build, token gates, and diff checks
passed.
- Focused UI coverage: 338 tests passed across six suites (336 before
the interaction guard, with the two affected suites rerun at 149 passed
after it). Covers both task interfaces, the real page mutation,
pending/error acknowledgement, stale state, and unavailable controls.
- Recovery database integration: 352 tests passed before the interaction
guard. The complete recovery-action and mutation-route suites passed 181
tests after it. The two new pending question/confirmation regressions
failed before the fix and passed afterward, including
resolved-interaction controls. Shared validator suite: 31 passed. E2E
catalog suites: 34 passed.
- Browser inspection passed for light/dark themes, mobile layout,
expandable details, pending retry, acknowledgement, failure, and
disabled retry. Storybook renders the production component; its request
is simulated.
- The broad local run hit two chat callback-order wait failures and was
stopped after all CI unit/database/runner shards passed. Both local
failures passed when rerun without the competing full-suite process.
- CI exposed a repeated project-repository draft-loss race during
canonical redirects. A new unit regression failed before the fix; all
nine project-page tests now pass, including controls for other projects
and companies. Both unchanged repository browser tests passed against a
fresh local server. UI typecheck, production UI build, and token gates
passed after this fix.
- [Earlier PR CI
passed](https://github.com/paperclipai/paperclip/actions/runs/36072486798)
on `21be0fec0e90e86b6d662b8ee4831847cd041cdb`: 55 successful checks, two
optional Storybook skips, and no failed or pending checks. The
repository browser shard passed with the production fix. Greptile is 5/5
on this exact commit with no unresolved review threads. The PR is
mergeable.

Historical, source-qualified lifecycle evidence:

- Lifecycle baseline: 1,074 assertions. Native session coverage: 447
tests. Product E2E support: 515 tests. Browser support: 11 tests. Full
earlier verification is retained in the archive.
- [Real-provider campaign: 8/8 passed, zero
retries](https://d1p6rlowie26tp.cloudfront.net/runner-e2e/campaigns/gha-35881382080-1/index.html),
source `e88d210417280140b44a36449027290adcb1aeaa`. Evidence and cleanup
checks passed. This includes deliberately exhausted repair cases that
correctly remain blocked; it does not mean every task finished Done.
This campaign predates the recovery UI change.
- Archive migration verified all 16 original JSON files byte-for-byte
and all 24 checksum entries. App tests do not need private archive
access. [Archive PR
#27](https://github.com/paperclipai/paperclip-evals/pull/27) is merged.

## Risks

- Agents that omit durable disposition receive at most two repair
attempts by default. Prose-only completion exposes missing state rather
than silently changing scheduling.
- A retry is an explicit board action. The server rechecks current
controls. A successful response confirms the task returned to To do; it
does not claim that the provider has already started.
- Existing notice metadata remains valid. Only older active notices with
matching structured evidence receive the new UI. Historical notices
without that evidence keep their existing rendering. No schema migration
is required.
- Old run records require conservative retry accounting. Tests cover old
counters, alternating retry lanes, restarts, and exhausted repairs.
- Historical snapshots require private `paperclip-evals` access. The app
index retains public campaign links. Live campaigns qualify specific
sources and scenarios; no new real-provider campaign has run for the
recovery UI commit.

> This fixes existing lifecycle and recovery behavior and does not
duplicate planned core work.

## Model Used

OpenAI GPT-6 through Codex assisted implementation, reasoning, code
execution, and review. The exact serving model ID and context window are
not exposed in this task. Historical real-provider evaluations used
Codex model `gpt-5.6-sol`, separately from the implementation assistant.

## 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 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-25 15:28:11 -07:00

846 lines
29 KiB
TypeScript

// @vitest-environment jsdom
import { act } from "react";
import type { ReactNode } from "react";
import { createRoot } from "react-dom/client";
import { MemoryRouter } from "react-router-dom";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { IssueChatThread } from "./IssueChatThread";
import type { IssueChatComment } from "../lib/issue-chat-messages";
import type { LiveRunForIssue } from "../api/heartbeats";
import type { Agent, SuccessfulRunHandoffState } from "@paperclipai/shared";
vi.mock("@assistant-ui/react", () => ({
AssistantRuntimeProvider: ({ children }: { children: ReactNode }) => <div>{children}</div>,
useAui: () => ({ thread: () => ({ append: async () => undefined }) }),
}));
vi.mock("./transcript/useLiveRunTranscripts", () => ({
useLiveRunTranscripts: () => ({
transcriptByRun: new Map(),
hasOutputForRun: () => false,
}),
}));
vi.mock("./MarkdownBody", () => ({
MarkdownBody: ({ children }: { children: ReactNode }) => <div>{children}</div>,
}));
vi.mock("./MarkdownEditor", () => ({
MarkdownEditor: () => <textarea aria-label="Issue chat editor" />,
}));
vi.mock("./InlineEntitySelector", () => ({ InlineEntitySelector: () => null }));
vi.mock("./Identity", () => ({ Identity: ({ name }: { name: string }) => <span>{name}</span> }));
vi.mock("./OutputFeedbackButtons", () => ({ OutputFeedbackButtons: () => null }));
vi.mock("@/components/ui/tooltip", () => ({
Tooltip: ({ children }: { children: ReactNode }) => <>{children}</>,
TooltipContent: ({ children }: { children: ReactNode }) => <div>{children}</div>,
TooltipTrigger: ({ children }: { children: ReactNode }) => <>{children}</>,
}));
vi.mock("./AgentIconPicker", () => ({ AgentIcon: () => null }));
vi.mock("./StatusBadge", () => ({ StatusBadge: ({ status }: { status: string }) => <span>{status}</span> }));
vi.mock("./IssueLinkQuicklook", () => ({
IssueLinkQuicklook: ({
children,
to,
}: {
children: ReactNode;
to: string;
}) => <a href={to}>{children}</a>,
}));
vi.mock("../hooks/usePaperclipIssueRuntime", () => ({
usePaperclipIssueRuntime: () => ({}),
}));
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
let container: HTMLDivElement;
let root: ReturnType<typeof createRoot>;
beforeEach(() => {
container = document.createElement("div");
document.body.appendChild(container);
window.scrollTo = vi.fn();
root = createRoot(container);
});
afterEach(() => {
act(() => root?.unmount());
container.remove();
});
function renderThread(
comments: IssueChatComment[],
options: {
agentMap?: Map<string, Agent>;
issueStatus?: string;
successfulRunHandoff?: SuccessfulRunHandoffState | null;
liveRuns?: LiveRunForIssue[];
} = {},
) {
act(() => {
root.render(
<MemoryRouter>
<IssueChatThread
comments={comments}
linkedRuns={[]}
timelineEvents={[]}
liveRuns={options.liveRuns ?? []}
onAdd={async () => {}}
showComposer={false}
enableLiveTranscriptPolling={false}
agentMap={options.agentMap}
issueStatus={options.issueStatus}
successfulRunHandoff={options.successfulRunHandoff}
/>
</MemoryRouter>,
);
});
}
const baseTimestamps = {
createdAt: new Date("2026-05-04T16:32:00.000Z"),
updatedAt: new Date("2026-05-04T16:32:00.000Z"),
};
describe("IssueChatThread system notice routing", () => {
it("renders the typed disposition notice in the classic thread without reading its prose", () => {
const comment: IssueChatComment = {
id: "typed-recovery", companyId: "company-1", issueId: "issue-1", authorType: "system", authorAgentId: null, authorUserId: null,
body: "Unrelated wording", presentation: { kind: "system_notice", tone: "warning", title: "Different title", detailsDefaultOpen: false, density: "compact" },
metadata: { version: 1, sections: [], recovery: { kind: "disposition_repair_escalated", actionId: "action", assigneeAgentId: "agent", attemptCount: 3, maxAttempts: 3, reason: "unchanged_source_state_exhausted" } }, ...baseTimestamps,
};
renderThread([comment]);
expect(container.querySelector('[data-testid="disposition-recovery-notice"]')).not.toBeNull();
expect(container.textContent).toContain("3 automatic attempts");
expect(container.textContent).not.toContain("Unrelated wording");
});
it("renders authorType=system comments as a SystemNotice rather than a user bubble", () => {
const comment: IssueChatComment = {
id: "comment-system",
companyId: "company-1",
issueId: "issue-1",
authorType: "system",
authorAgentId: null,
authorUserId: null,
body: "Paperclip needs a disposition before this issue can continue.",
presentation: {
kind: "system_notice",
tone: "warning",
title: "Missing issue disposition",
detailsDefaultOpen: false,
},
metadata: {
version: 1,
sections: [
{
title: "Required action",
rows: [
{ type: "issue_link", label: "Source issue", issueId: "i1", identifier: "PAP-3440", title: "Recovery" },
{ type: "key_value", label: "Status before", value: "in_progress" },
],
},
],
},
...baseTimestamps,
};
renderThread([comment]);
const row = container.querySelector('[data-message-role="system"]');
expect(row).not.toBeNull();
const status = row?.querySelector('[role="status"]');
expect(status?.getAttribute("aria-label")).toBe("Missing issue disposition");
expect(container.textContent).toContain("Paperclip needs a disposition");
// collapsed by default — metadata identifier should not be visible
expect(container.textContent).not.toContain("PAP-3440");
const toggle = row?.querySelector("button[aria-expanded]") as HTMLButtonElement | null;
expect(toggle?.getAttribute("aria-expanded")).toBe("false");
expect(container.querySelectorAll('[data-message-role="user"]').length).toBe(0);
});
it("renders a system notice with a malformed createdAt without tripping the error boundary (PAP-16607)", () => {
const comment: IssueChatComment = {
id: "comment-system-bad-date",
companyId: "company-1",
issueId: "issue-1",
authorType: "system",
authorAgentId: null,
authorUserId: null,
body: "Workspace ready.",
presentation: {
kind: "system_notice",
tone: "info",
title: "Workspace ready",
detailsDefaultOpen: false,
},
metadata: { version: 1, sections: [] },
// A server serialization bug (Dates collapsed to `{}` by secret
// redaction) shipped comments whose timestamps parse to Invalid Date.
createdAt: {} as unknown as Date,
updatedAt: {} as unknown as Date,
};
renderThread([comment]);
expect(container.textContent).not.toContain("Chat renderer hit an internal state error.");
expect(container.textContent).toContain("Workspace ready");
});
it("expands metadata when detailsDefaultOpen is true", () => {
const comment: IssueChatComment = {
id: "comment-system-open",
companyId: "company-1",
issueId: "issue-1",
authorType: "system",
authorAgentId: null,
authorUserId: null,
body: "Recovery escalated.",
presentation: {
kind: "system_notice",
tone: "danger",
title: null,
detailsDefaultOpen: true,
},
metadata: {
version: 1,
sections: [
{
rows: [
{ type: "agent_link", label: "Owner", agentId: "agent-cto", name: "CTO" },
],
},
],
},
...baseTimestamps,
};
renderThread([comment]);
const status = container.querySelector('[role="status"]');
expect(status?.getAttribute("aria-label")).toBe("System alert");
expect(container.textContent).toContain("CTO");
const toggle = container.querySelector("button[aria-expanded]");
expect(toggle?.getAttribute("aria-expanded")).toBe("true");
});
it("falls back to legacy user bubble + handoff callout for old text-only comments", () => {
const comment: IssueChatComment = {
id: "comment-legacy",
companyId: "company-1",
issueId: "issue-1",
authorType: "user",
authorAgentId: null,
authorUserId: "user-1",
body: "## Successful run missing issue disposition\n\nFix this.",
presentation: null,
metadata: null,
...baseTimestamps,
};
renderThread([comment]);
expect(container.querySelector('[role="status"]')).toBeNull();
const userRow = container.querySelector('[data-message-role="user"]');
expect(userRow).not.toBeNull();
expect(container.textContent).toContain("Successful run missing issue disposition");
});
it("keeps regular user comments rendering as user bubbles", () => {
const comment: IssueChatComment = {
id: "comment-user",
companyId: "company-1",
issueId: "issue-1",
authorType: "user",
authorAgentId: null,
authorUserId: "user-1",
body: "Standard user message.",
presentation: null,
metadata: null,
...baseTimestamps,
};
renderThread([comment]);
expect(container.querySelector('[role="status"]')).toBeNull();
expect(container.querySelector('[data-message-role="user"]')).not.toBeNull();
expect(container.textContent).toContain("Standard user message.");
});
it("keeps agent-authored comments rendering as assistant bubbles even with system_notice presentation absent", () => {
const comment: IssueChatComment = {
id: "comment-agent",
companyId: "company-1",
issueId: "issue-1",
authorType: "agent",
authorAgentId: "agent-1",
authorUserId: null,
body: "Agent reply",
presentation: null,
metadata: null,
...baseTimestamps,
};
renderThread([comment]);
expect(container.querySelector('[role="status"]')).toBeNull();
expect(container.querySelector('[data-message-role="assistant"]')).not.toBeNull();
});
it("labels system notice source as the originating run agent name when runAgentId is available", () => {
const codexAgent = {
id: "agent-codex",
name: "CodexCoder",
} as unknown as Agent;
const agentMap = new Map<string, Agent>([[codexAgent.id, codexAgent]]);
const comment: IssueChatComment = {
id: "comment-system-runagent",
companyId: "company-1",
issueId: "issue-1",
authorType: "system",
authorAgentId: null,
authorUserId: null,
runId: "run-issue-chat-01",
runAgentId: "agent-codex",
body: "Paperclip needs a disposition before this issue can continue.",
presentation: {
kind: "system_notice",
tone: "warning",
title: "Missing issue disposition",
detailsDefaultOpen: false,
},
metadata: null,
...baseTimestamps,
};
renderThread([comment], { agentMap });
const status = container.querySelector('[role="status"]');
expect(status).not.toBeNull();
const sourceLink = status?.querySelector('a[href^="/agents/"]') as HTMLAnchorElement | null;
expect(sourceLink?.getAttribute("href")).toBe("/agents/agent-codex/runs/run-issue-chat-01");
expect(sourceLink?.textContent).toBe("CodexCoder");
expect(sourceLink?.textContent).not.toBe("You");
});
it("shows copy-link feedback on the link button only", async () => {
const writeText = vi.fn(async () => undefined);
const originalSecureContext = Object.getOwnPropertyDescriptor(window, "isSecureContext");
Object.defineProperty(window, "isSecureContext", {
configurable: true,
value: true,
});
Object.defineProperty(navigator, "clipboard", {
configurable: true,
value: { writeText },
});
const comment: IssueChatComment = {
id: "comment-copy-link",
companyId: "company-1",
issueId: "issue-1",
authorType: "system",
authorAgentId: null,
authorUserId: null,
body: "System recovery completed.",
presentation: {
kind: "system_notice",
tone: "success",
title: null,
detailsDefaultOpen: false,
},
metadata: null,
...baseTimestamps,
};
renderThread([comment]);
const copyLink = container.querySelector('button[aria-label="Copy link to system notice"]') as HTMLButtonElement;
const copyText = container.querySelector('button[aria-label="Copy system notice"]') as HTMLButtonElement;
await act(async () => {
copyLink.click();
await Promise.resolve();
});
expect(writeText).toHaveBeenCalledWith(expect.stringContaining("#comment-comment-copy-link"));
expect(copyLink.querySelector(".lucide-check")).not.toBeNull();
expect(copyText.querySelector(".lucide-check")).toBeNull();
if (originalSecureContext) {
Object.defineProperty(window, "isSecureContext", originalSecureContext);
} else {
// @ts-expect-error test cleanup for optional browser API
delete window.isSecureContext;
}
});
it("labels system notice source as Paperclip when no run agent can be resolved", () => {
const comment: IssueChatComment = {
id: "comment-system-no-author",
companyId: "company-1",
issueId: "issue-1",
authorType: "system",
authorAgentId: null,
authorUserId: null,
runId: null,
runAgentId: null,
body: "System recovery completed.",
presentation: {
kind: "system_notice",
tone: "info",
title: null,
detailsDefaultOpen: false,
},
metadata: null,
...baseTimestamps,
};
renderThread([comment]);
const status = container.querySelector('[role="status"]');
expect(status).not.toBeNull();
expect(status?.textContent).toContain("Paperclip");
expect(status?.textContent).not.toContain("You");
});
it("falls back to Paperclip in the system notice header when run agent is unknown to agentMap", () => {
const comment: IssueChatComment = {
id: "comment-system-unknown-agent",
companyId: "company-1",
issueId: "issue-1",
authorType: "system",
authorAgentId: null,
authorUserId: null,
runId: "run-xyz",
runAgentId: "agent-unknown",
body: "Disposition required.",
presentation: {
kind: "system_notice",
tone: "warning",
title: null,
detailsDefaultOpen: false,
},
metadata: null,
...baseTimestamps,
};
renderThread([comment]);
const status = container.querySelector('[role="status"]');
const sourceLink = status?.querySelector('a[href^="/agents/"]') as HTMLAnchorElement | null;
expect(sourceLink?.getAttribute("href")).toBe("/agents/agent-unknown/runs/run-xyz");
expect(sourceLink?.textContent).toBe("Paperclip");
});
it("routes agent-authored comments to the notice renderer when presentation requests system_notice", () => {
const owner = { id: "agent-1", name: "ClaudeCoder" } as unknown as Agent;
const agentMap = new Map<string, Agent>([[owner.id, owner]]);
const comment: IssueChatComment = {
id: "comment-agent-system",
companyId: "company-1",
issueId: "issue-1",
authorType: "agent",
authorAgentId: "agent-1",
authorUserId: null,
runId: "run-owner",
runAgentId: "agent-1",
body: "Reassigned to ClaudeFixer.",
presentation: {
kind: "system_notice",
tone: "neutral",
title: "Recovery reassignment",
detailsDefaultOpen: false,
},
metadata: null,
...baseTimestamps,
};
renderThread([comment], { agentMap });
// No longer an assistant bubble — it collapses like a system notice.
expect(container.querySelector('[data-message-role="assistant"]')).toBeNull();
const row = container.querySelector('[data-message-role="system"]');
expect(row).not.toBeNull();
const status = row?.querySelector('[role="status"]');
expect(status?.getAttribute("aria-label")).toBe("Recovery reassignment");
// The real author's name + run link stay visible on the notice.
const sourceLink = status?.querySelector('a[href^="/agents/"]') as HTMLAnchorElement | null;
expect(sourceLink?.getAttribute("href")).toBe("/agents/agent-1/runs/run-owner");
expect(sourceLink?.textContent).toBe("ClaudeCoder");
});
it("collapses compact system notices to a single quiet row and expands to the full card", () => {
const comment: IssueChatComment = {
id: "comment-compact",
companyId: "company-1",
issueId: "issue-1",
authorType: "system",
authorAgentId: null,
authorUserId: null,
runId: "run-recovery",
runAgentId: "agent-codex",
body: "Recovery escalated to the CTO after repeated stalls.",
presentation: {
kind: "system_notice",
tone: "warning",
title: "Recovery escalated",
detailsDefaultOpen: false,
density: "compact",
},
metadata: {
version: 1,
sections: [
{
title: "Escalation",
rows: [{ type: "agent_link", label: "Owner", agentId: "agent-cto", name: "CTO" }],
},
],
},
...baseTimestamps,
};
renderThread([comment]);
const row = container.querySelector('[data-testid="compact-system-notice"]');
expect(row).not.toBeNull();
// Collapsed: title + timestamp + chevron visible, but body/card hidden.
expect(row?.textContent).toContain("Recovery escalated");
expect(row?.querySelector('[data-testid="compact-system-notice-time"]')).not.toBeNull();
expect(row?.querySelector(".lucide-chevron-down")).not.toBeNull();
const toggle = row?.querySelector("button[aria-expanded]") as HTMLButtonElement;
expect(toggle.getAttribute("aria-expanded")).toBe("false");
const detailsId = toggle.getAttribute("aria-controls");
const details = detailsId ? container.ownerDocument.getElementById(detailsId) : null;
expect(details).not.toBeNull();
expect(details).toHaveProperty("hidden", true);
// The full SystemNotice card lives inside the collapsed region.
expect(details?.querySelector('[role="status"]')).not.toBeNull();
act(() => {
toggle.click();
});
expect(toggle.getAttribute("aria-expanded")).toBe("true");
expect(details).toHaveProperty("hidden", false);
expect(details?.textContent).toContain("Recovery escalated to the CTO");
});
it("renders a compact notice already expanded when detailsDefaultOpen is true", () => {
const comment: IssueChatComment = {
id: "comment-compact-open",
companyId: "company-1",
issueId: "issue-1",
authorType: "system",
authorAgentId: null,
authorUserId: null,
body: "Recovery escalated to the CTO.",
presentation: {
kind: "system_notice",
tone: "danger",
title: "Recovery escalated",
detailsDefaultOpen: true,
density: "compact",
},
metadata: null,
...baseTimestamps,
};
renderThread([comment]);
const row = container.querySelector('[data-testid="compact-system-notice"]');
expect(row).not.toBeNull();
const toggle = row?.querySelector("button[aria-expanded]") as HTMLButtonElement;
expect(toggle.getAttribute("aria-expanded")).toBe("true");
const detailsId = toggle.getAttribute("aria-controls");
const details = detailsId ? container.ownerDocument.getElementById(detailsId) : null;
expect(details).toHaveProperty("hidden", false);
expect(details?.querySelector('[role="status"]')).not.toBeNull();
expect(details?.textContent).toContain("Recovery escalated to the CTO.");
});
it("keeps the author visible on a compact agent-authored notice row", () => {
const owner = { id: "agent-1", name: "ClaudeCoder" } as unknown as Agent;
const agentMap = new Map<string, Agent>([[owner.id, owner]]);
const comment: IssueChatComment = {
id: "comment-compact-agent",
companyId: "company-1",
issueId: "issue-1",
authorType: "agent",
authorAgentId: "agent-1",
authorUserId: null,
body: "Picked this back up after the wake.",
presentation: {
kind: "system_notice",
tone: "neutral",
title: "Recovery owner update",
detailsDefaultOpen: false,
density: "compact",
},
metadata: null,
...baseTimestamps,
};
renderThread([comment], { agentMap });
const row = container.querySelector('[data-testid="compact-system-notice"]');
expect(row).not.toBeNull();
expect(row?.textContent).toContain("Recovery owner update");
// Author name shows on the collapsed row itself.
expect(row?.querySelector("button[aria-expanded]")?.textContent).toContain("ClaudeCoder");
});
it("keeps notices without density rendering as the full card (graceful fallback)", () => {
const comment: IssueChatComment = {
id: "comment-no-density",
companyId: "company-1",
issueId: "issue-1",
authorType: "system",
authorAgentId: null,
authorUserId: null,
body: "Recovery completed.",
presentation: {
kind: "system_notice",
tone: "success",
title: "Recovery completed",
detailsDefaultOpen: false,
},
metadata: null,
...baseTimestamps,
};
renderThread([comment]);
expect(container.querySelector('[data-testid="compact-system-notice"]')).toBeNull();
const status = container.querySelector('[role="status"]');
expect(status?.getAttribute("aria-label")).toBe("Recovery completed");
// Body is visible immediately on the full card.
expect(status?.textContent).toContain("Recovery completed.");
});
it("folds stale successful-run disposition warnings into the activity log disclosure style", () => {
const comment: IssueChatComment = {
id: "comment-stale-disposition-warning",
companyId: "company-1",
issueId: "issue-1",
authorType: "system",
authorAgentId: null,
authorUserId: null,
runId: "run-stale",
runAgentId: "agent-codex",
body: "Paperclip needs a disposition before this issue can continue.",
presentation: {
kind: "system_notice",
tone: "warning",
title: "Missing issue disposition",
detailsDefaultOpen: false,
},
metadata: {
version: 1,
sourceRunId: "run-stale",
sections: [
{
title: "Run evidence",
rows: [
{ type: "run_link", label: "Completed run", runId: "run-stale", title: "succeeded" },
{ type: "key_value", label: "Normalized cause", value: "successful_run_missing_state" },
],
},
],
},
...baseTimestamps,
};
renderThread([comment], {
issueStatus: "done",
successfulRunHandoff: {
state: "resolved",
required: false,
hasLiveContinuation: false,
sourceRunId: "run-stale",
correctiveRunId: "run-corrective",
assigneeAgentId: "agent-codex",
detectedProgressSummary: null,
createdAt: new Date("2026-05-04T17:00:00.000Z"),
},
});
const row = container.querySelector('[data-testid="stale-disposition-warning"]');
expect(row).not.toBeNull();
expect(row?.querySelector('span[aria-hidden="true"]')?.className).toContain("size-6");
const toggle = row?.querySelector("button[aria-expanded]") as HTMLButtonElement;
expect(toggle.className).toContain("w-full");
expect(toggle.className).toContain("py-0.5");
expect(row?.querySelector('[role="status"]')).toBeNull();
expect(row?.querySelector(".lucide-triangle-alert")).toBeNull();
expect(row?.querySelector(".lucide-chevron-down")).not.toBeNull();
expect(row?.querySelector('[data-testid="stale-disposition-warning-time"]')?.parentElement?.className).toContain("ml-auto");
expect(row?.textContent).toContain("Stale disposition warning");
expect(row?.textContent).not.toContain("This disposition warning is stale because the issue now has a newer disposition.");
expect(row?.textContent).not.toContain("Paperclip needs a disposition before this issue can continue.");
expect(toggle.getAttribute("aria-expanded")).toBe("false");
const detailsId = toggle.getAttribute("aria-controls");
expect(detailsId).toBeTruthy();
const details = detailsId ? container.ownerDocument.getElementById(detailsId) : null;
expect(details).not.toBeNull();
expect(details?.textContent).toContain("run-stale");
expect(details).toHaveProperty("hidden", true);
act(() => {
toggle.click();
});
expect(toggle.getAttribute("aria-expanded")).toBe("true");
expect(details).toHaveProperty("hidden", false);
expect(container.textContent).toContain("run-stale");
});
it("folds a required disposition warning while a live continuation is running the issue", () => {
const comment: IssueChatComment = {
id: "comment-live-disposition-warning",
companyId: "company-1",
issueId: "issue-1",
authorType: "system",
authorAgentId: null,
authorUserId: null,
runId: "run-source",
runAgentId: "agent-codex",
body: "Paperclip needs a disposition before this issue can continue.",
presentation: {
kind: "system_notice",
tone: "warning",
title: "Missing issue disposition",
detailsDefaultOpen: false,
},
metadata: {
version: 1,
sourceRunId: "run-source",
sections: [],
},
...baseTimestamps,
};
renderThread([comment], {
issueStatus: "in_progress",
successfulRunHandoff: {
state: "required",
required: true,
hasLiveContinuation: true,
liveRunId: "run-live",
sourceRunId: "run-source",
correctiveRunId: null,
assigneeAgentId: "agent-codex",
detectedProgressSummary: null,
createdAt: new Date("2026-05-04T17:00:00.000Z"),
},
});
const row = container.querySelector('[data-testid="stale-disposition-warning"]');
expect(row).not.toBeNull();
expect(row?.textContent).not.toContain("Paperclip needs a disposition before this issue can continue.");
});
it("keeps the required disposition warning loud when no live continuation exists", () => {
const comment: IssueChatComment = {
id: "comment-stuck-disposition-warning",
companyId: "company-1",
issueId: "issue-1",
authorType: "system",
authorAgentId: null,
authorUserId: null,
runId: "run-source",
runAgentId: "agent-codex",
body: "Paperclip needs a disposition before this issue can continue.",
presentation: {
kind: "system_notice",
tone: "warning",
title: "Missing issue disposition",
detailsDefaultOpen: false,
},
metadata: {
version: 1,
sourceRunId: "run-source",
sections: [],
},
...baseTimestamps,
};
renderThread([comment], {
issueStatus: "in_progress",
successfulRunHandoff: {
state: "required",
required: true,
hasLiveContinuation: false,
sourceRunId: "run-source",
correctiveRunId: null,
assigneeAgentId: "agent-codex",
detectedProgressSummary: null,
createdAt: new Date("2026-05-04T17:00:00.000Z"),
},
});
expect(container.querySelector('[data-testid="stale-disposition-warning"]')).toBeNull();
expect(container.textContent).toContain("Paperclip needs a disposition before this issue can continue.");
});
it("folds a required disposition warning when a live run starts after the issue payload was fetched", () => {
const comment: IssueChatComment = {
id: "comment-realtime-disposition-warning",
companyId: "company-1",
issueId: "issue-1",
authorType: "system",
authorAgentId: null,
authorUserId: null,
runId: "run-source",
runAgentId: "agent-codex",
body: "Paperclip needs a disposition before this issue can continue.",
presentation: {
kind: "system_notice",
tone: "warning",
title: "Missing issue disposition",
detailsDefaultOpen: false,
},
metadata: {
version: 1,
sourceRunId: "run-source",
sections: [],
},
...baseTimestamps,
};
renderThread([comment], {
issueStatus: "in_progress",
liveRuns: [
{
id: "run-live",
status: "running",
invocationSource: "wakeup",
triggerDetail: null,
startedAt: "2026-05-04T17:05:00.000Z",
finishedAt: null,
createdAt: "2026-05-04T17:05:00.000Z",
agentId: "agent-codex",
agentName: "CodexCoder",
adapterType: "codex_local",
issueId: "issue-1",
},
],
successfulRunHandoff: {
state: "required",
required: true,
// Stale server view: the payload was fetched before run-live started.
hasLiveContinuation: false,
sourceRunId: "run-source",
correctiveRunId: null,
assigneeAgentId: "agent-codex",
detectedProgressSummary: null,
createdAt: new Date("2026-05-04T17:00:00.000Z"),
},
});
const row = container.querySelector('[data-testid="stale-disposition-warning"]');
expect(row).not.toBeNull();
expect(row?.textContent).not.toContain("Paperclip needs a disposition before this issue can continue.");
});
});