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>
This commit is contained in:
DottaandPaperclip authored and GitHub committed 2026-09-25 15:28:11 -07:00
1 parent 6bc830b62b
commit 96bf004a79
96 files changed
+5833 -493

No files matched your search

@@ -0,0 +1,130 @@
// @vitest-environment jsdom
import { act } from "react";
import { createRoot, type Root } from "react-dom/client";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { DispositionRecoveryNotice, DispositionRecoveryProvider, dispositionRetryUnavailableReason, readDispositionRecoverySnapshot, type DispositionRecoveryContextValue, type DispositionRecoverySnapshot } from "./DispositionRecoveryNotice";
import { TaskChatSystemNotice } from "./task-chat/TaskChatSystemNotice";
const snapshot: DispositionRecoverySnapshot = { kind: "disposition_repair_escalated", actionId: "action-1", attemptCount: 2, maxAttempts: 2, reason: "unchanged_source_state_exhausted", assigneeAgentId: "agent-1" };
function context(): DispositionRecoveryContextValue {
return {
issue: { executionRunId: null, checkoutRunId: null, status: "blocked", assigneeAgentId: "agent-1", activeRecoveryAction: { id: "action-1", status: "active", kind: "deliberate_wait_without_target", ownerType: "board", returnOwnerAgentId: "agent-1", wakePolicy: { type: "board_escalation" } } as NonNullable<DispositionRecoveryContextValue["issue"]["activeRecoveryAction"]> },
agentMap: new Map([["agent-1", { name: "Alex", status: "idle" }]]),
onRetry: vi.fn(async () => {}),
};
}
describe("disposition recovery notice", () => {
let container: HTMLDivElement;
let root: Root;
beforeEach(() => { container = document.createElement("div"); document.body.append(container); root = createRoot(container); });
afterEach(async () => { await act(async () => root.unmount()); container.remove(); });
async function render(value = context(), data = snapshot) {
await act(async () => root.render(<DispositionRecoveryProvider value={value}><DispositionRecoveryNotice snapshot={data} createdAt={new Date().toISOString()} /></DispositionRecoveryProvider>));
}
const button = (name: string) => Array.from(container.querySelectorAll("button")).find(b => b.textContent === name)!;
it("shows the explanation and action without exposing technical detail until expanded", async () => {
await render();
expect(container.textContent).toContain("Agent needs attention");
expect(container.textContent).toContain("Two automatic attempts");
expect(button("Retry agent").disabled).toBe(false);
expect(container.textContent).not.toContain(snapshot.reason);
await act(async () => button("View details").click());
expect(button("Hide details").getAttribute("aria-expanded")).toBe("true");
expect(container.querySelector(`#${CSS.escape(button("Hide details").getAttribute("aria-controls")!)}`)).not.toBeNull();
expect(container.textContent).toContain("2 of 2");
expect(container.textContent).toContain("Alex");
expect(container.textContent).toContain(snapshot.reason);
});
it("awaits the real request, blocks repeated clicks, then acknowledges the result", async () => {
let finish!: () => void;
const value = context(); value.onRetry = vi.fn(() => new Promise<void>(resolve => { finish = resolve; }));
await render(value);
await act(async () => { button("Retry agent").click(); button("Retry agent")?.click(); });
expect(value.onRetry).toHaveBeenCalledExactlyOnceWith("action-1");
expect(button("Requesting retry…").disabled).toBe(true);
await act(async () => finish());
expect(container.textContent).toContain("Retry requested");
expect(container.textContent).toContain("returned to To do for Alex");
expect(button("Retry agent")).toBeUndefined();
});
it("shows a rejected request inline and allows another attempt without promising that nothing ran", async () => {
const value = context(); value.onRetry = vi.fn().mockRejectedValueOnce(new Error("The company spending limit was reached.")).mockResolvedValueOnce(undefined);
await render(value);
await act(async () => button("Retry agent").click());
expect(container.querySelector('[role="alert"]')?.textContent).toContain("spending limit");
expect(container.textContent).not.toContain("No new run was started");
expect(button("Retry agent").disabled).toBe(false);
await act(async () => button("Retry agent").click());
expect(container.querySelector('[role="alert"]')).toBeNull();
expect(container.textContent).toContain("Retry requested");
});
it("shows the current gate next to a disabled retry action", async () => {
const value = context(); value.unavailableReason = "The task is paused.";
await render(value);
const retry = button("Retry agent");
expect(retry.disabled).toBe(true);
expect(document.getElementById(retry.getAttribute("aria-describedby")!)?.textContent).toContain("task is paused");
await act(async () => retry.click()); expect(value.onRetry).not.toHaveBeenCalled();
});
it("retires an old notice when a different recovery action replaces it", async () => {
const value = context(); await render(value);
value.issue.activeRecoveryAction = { ...value.issue.activeRecoveryAction!, id: "action-2" };
await render(value);
expect(container.textContent).toContain("Agent needed attention");
expect(container.textContent).toContain("no longer active");
expect(button("Retry agent")).toBeUndefined();
});
it.each(["owner_not_invokable", "owner_budget_blocked"])("does not invent exhausted attempts for %s", async reason => {
await render(context(), { ...snapshot, attemptCount: 0, reason });
expect(container.textContent).not.toContain("attempts to resolve this failed");
await act(async () => button("View details").click()); expect(container.textContent).toContain("0 of 2");
});
it("uses typed metadata regardless of prose and rejects prose-only lookalikes", async () => {
const value = context();
const item = { id: "notice", kind: "message" as const, author: "system" as const, text: "完全に異なる文章", metadata: { version: 1 as const, sections: [], recovery: snapshot } };
await act(async () => root.render(<DispositionRecoveryProvider value={value}><TaskChatSystemNotice item={item} /></DispositionRecoveryProvider>));
expect(button("Retry agent").disabled).toBe(false);
await act(async () => root.render(<DispositionRecoveryProvider value={value}><TaskChatSystemNotice item={{ ...item, text: "Recovery: disposition repair escalated — source owner preserved", metadata: null }} /></DispositionRecoveryProvider>));
expect(container.querySelector('[data-testid="disposition-recovery-notice"]')).toBeNull();
await act(async () => root.render(<DispositionRecoveryProvider value={value}><TaskChatSystemNotice item={{ ...item, author: "agent" }} /></DispositionRecoveryProvider>));
expect(container.querySelector('[data-testid="disposition-recovery-notice"]')).toBeNull();
});
});
describe("disposition retry affordance gates", () => {
it("allows the current exhausted action only", () => expect(dispositionRetryUnavailableReason(snapshot, context())).toBeNull());
it.each(["done", "cancelled", "backlog", "todo", "in_progress", "in_review"] as const)("does not reopen %s", status => {
const value = context(); value.issue.status = status;
expect(dispositionRetryUnavailableReason(snapshot, value)).not.toBeNull();
});
it.each(["assignee", "returnOwner", "action", "run", "checkout", "pausedAgent", "terminatedAgent", "approval", "blocker", "pause", "automaticRepair", "interaction"])("blocks %s", gate => {
const value = context();
if (gate === "assignee") value.issue.assigneeAgentId = "someone-else";
if (gate === "returnOwner") value.issue.activeRecoveryAction!.returnOwnerAgentId = "someone-else";
if (gate === "action") value.issue.activeRecoveryAction = null;
if (gate === "run") value.issue.executionRunId = "running";
if (gate === "checkout") value.issue.checkoutRunId = "checked-out";
if (gate === "pausedAgent" || gate === "terminatedAgent") value.agentMap = new Map([["agent-1", { name: "Alex", status: gate === "pausedAgent" ? "paused" : "terminated" }]]);
if (gate === "approval") value.issue.executionState = { status: "pending" } as NonNullable<DispositionRecoveryContextValue["issue"]["executionState"]>;
if (gate === "blocker") value.issue.blockedBy = [{ status: "in_progress" }] as DispositionRecoveryContextValue["issue"]["blockedBy"];
if (gate === "pause") value.unavailableReason = "Paused";
if (gate === "interaction") value.hasPendingInteraction = true;
if (gate === "automaticRepair") value.issue.activeRecoveryAction!.ownerType = "agent";
expect(dispositionRetryUnavailableReason(snapshot, value)).not.toBeNull();
});
});
describe("older structured recovery notices", () => {
it("uses exact action/run references and evidence without reading English labels or prose", () => {
const action = { ...context().issue.activeRecoveryAction!, evidence: { latestRunId: "run-1", terminalReason: snapshot.reason, sourceAttemptCount: 2, sourceMaxAttempts: 2 } };
const metadata = { version: 1 as const, sourceRunId: "run-1", sections: [{ rows: [{ type: "key_value" as const, label: "別のラベル", value: "action-1" }] }] };
expect(readDispositionRecoverySnapshot(metadata, action)).toEqual(snapshot);
expect(readDispositionRecoverySnapshot({ ...metadata, sourceRunId: "older-run" }, action)).toBeNull();
expect(readDispositionRecoverySnapshot({ ...metadata, sections: [] }, action)).toBeNull();
expect(readDispositionRecoverySnapshot(metadata, { ...action, id: "action-2" })).toBeNull();
expect(readDispositionRecoverySnapshot(metadata, { ...action, evidence: {} })).toBeNull();
expect(readDispositionRecoverySnapshot(metadata, null)).toBeNull();
});
});
@@ -0,0 +1,151 @@
import { createContext, useContext, useId, useRef, useState, type ReactNode } from "react";
import { Check, ChevronDown, Loader2, RotateCcw, TriangleAlert } from "lucide-react";
import type { Agent, Issue, IssueCommentMetadata, IssueRecoveryAction } from "@paperclipai/shared";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";
import { timeAgo } from "@/lib/timeAgo";
export type DispositionRecoverySnapshot = NonNullable<IssueCommentMetadata["recovery"]>;
export type DispositionRecoveryContextValue = {
issue: Pick<Issue, "status" | "assigneeAgentId" | "executionRunId" | "checkoutRunId" | "executionState" | "blockedBy"> & {
activeRecoveryAction?: Pick<IssueRecoveryAction, "id" | "status" | "kind" | "ownerType" | "returnOwnerAgentId" | "wakePolicy"> & { evidence?: IssueRecoveryAction["evidence"] } | null;
};
agentMap?: ReadonlyMap<string, Pick<Agent, "name" | "status">>;
hasPendingInteraction?: boolean;
unavailableReason?: string | null;
onRetry: (actionId: string) => Promise<void>;
};
const RecoveryContext = createContext<DispositionRecoveryContextValue | null>(null);
export function DispositionRecoveryProvider({ value, children }: { value: DispositionRecoveryContextValue; children: ReactNode }) {
return <RecoveryContext.Provider value={value}>{children}</RecoveryContext.Provider>;
}
/** Older notices can be identified by their stored action/run IDs, never their copy. */
export function readDispositionRecoverySnapshot(metadata: IssueCommentMetadata | null | undefined, action?: DispositionRecoveryContextValue["issue"]["activeRecoveryAction"]): DispositionRecoverySnapshot | null {
if (metadata?.recovery?.kind === "disposition_repair_escalated") return metadata.recovery;
if (!metadata || !action || action.kind !== "deliberate_wait_without_target" || action.ownerType !== "board" || action.wakePolicy?.type !== "board_escalation") return null;
const evidence = action.evidence;
if (!metadata.sourceRunId || metadata.sourceRunId !== evidence?.latestRunId) return null;
if (!metadata.sections.some(section => section.rows.some(row => row.type === "key_value" && row.value === action.id))) return null;
if (typeof evidence.terminalReason !== "string" || typeof evidence.sourceAttemptCount !== "number" || !Number.isInteger(evidence.sourceAttemptCount) || evidence.sourceAttemptCount < 0 || typeof evidence.sourceMaxAttempts !== "number" || !Number.isInteger(evidence.sourceMaxAttempts) || evidence.sourceMaxAttempts <= 0) return null;
return { kind: "disposition_repair_escalated", actionId: action.id, attemptCount: evidence.sourceAttemptCount, maxAttempts: evidence.sourceMaxAttempts, reason: evidence.terminalReason, assigneeAgentId: action.returnOwnerAgentId };
}
export function useDispositionRecoverySnapshot(metadata: IssueCommentMetadata | null | undefined) {
return readDispositionRecoverySnapshot(metadata, useContext(RecoveryContext)?.issue.activeRecoveryAction);
}
/** UI affordance only; the server rechecks the current action and all execution gates. */
export function dispositionRetryUnavailableReason(snapshot: DispositionRecoverySnapshot, context: DispositionRecoveryContextValue | null): string | null {
if (!context) return "Open the task to review its current state.";
const { issue } = context;
const action = issue.activeRecoveryAction;
if (!action || action.id !== snapshot.actionId || action.status !== "active") return "This recovery notice is no longer active.";
if (issue.status !== "blocked") return "The task’s state has changed. Review its current state before retrying.";
if (action.kind !== "deliberate_wait_without_target" || action.ownerType !== "board" || action.wakePolicy?.type !== "board_escalation") return "The task’s recovery state has changed. Refresh to see the current action.";
if (!snapshot.assigneeAgentId || issue.assigneeAgentId !== snapshot.assigneeAgentId || action.returnOwnerAgentId !== snapshot.assigneeAgentId) return "The assigned agent has changed. Review the task before retrying.";
if (context.unavailableReason) return context.unavailableReason;
if (context.hasPendingInteraction) return "Respond to the pending question or confirmation before retrying.";
if (issue.executionRunId || issue.checkoutRunId) return "The task already has an active run. Wait for it to finish.";
if (issue.executionState?.status === "pending") return "The task is waiting for a review or approval.";
if (issue.blockedBy?.some(blocker => blocker.status !== "done" && blocker.status !== "cancelled")) return "Resolve the task’s blockers before retrying.";
const agent = context.agentMap?.get(snapshot.assigneeAgentId);
if (agent?.status === "paused") return "The assigned agent is paused. Resume the agent before retrying.";
if (agent?.status === "terminated") return "The assigned agent is no longer available.";
return null;
}
function descriptionFor(snapshot: DispositionRecoverySnapshot) {
const start = "The agent stopped without recording an outcome or a next step.";
if (snapshot.reason === "owner_budget_blocked") return `${start} Automatic recovery stopped because a spending or pause limit prevents the agent from running.`;
if (snapshot.reason === "owner_not_invokable") return `${start} Automatic recovery stopped because the assigned agent is unavailable.`;
if (snapshot.reason === "unchanged_source_state_exhausted") {
const attempts = snapshot.attemptCount === 2 ? "Two" : String(snapshot.attemptCount);
return `${start} ${attempts} automatic ${snapshot.attemptCount === 1 ? "attempt" : "attempts"} to resolve this failed.`;
}
return `${start} Automatic recovery stopped. Review the details before trying again.`;
}
/** Same component in both task interfaces and Storybook; no prose controls actions. */
export function DispositionRecoveryNotice({ snapshot, createdAt, defaultExpanded = false }: {
snapshot: DispositionRecoverySnapshot;
createdAt?: string;
defaultExpanded?: boolean;
}) {
const context = useContext(RecoveryContext);
const [expanded, setExpanded] = useState(defaultExpanded);
const [pending, setPending] = useState(false);
const [requested, setRequested] = useState(false);
const [error, setError] = useState<string | null>(null);
const inFlight = useRef(false);
const detailsId = useId();
const titleId = useId();
const unavailableId = useId();
const unavailableReason = dispositionRetryUnavailableReason(snapshot, context);
const historical = Boolean(context && context.issue.activeRecoveryAction?.id !== snapshot.actionId);
const agentName = (snapshot.assigneeAgentId && context?.agentMap?.get(snapshot.assigneeAgentId)?.name) || "the assigned agent";
const HeadingIcon = requested || historical ? Check : TriangleAlert;
async function retry() {
if (!context || unavailableReason || inFlight.current) return;
inFlight.current = true;
setPending(true);
setError(null);
try {
await context.onRetry(snapshot.actionId);
setRequested(true);
} catch (cause) {
setError(cause instanceof Error ? cause.message : "Refresh the task to check its current state, then try again.");
} finally {
inFlight.current = false;
setPending(false);
}
}
return (
<section aria-labelledby={titleId} className="flex min-w-0 gap-2.5 py-3" data-testid="disposition-recovery-notice">
<HeadingIcon aria-hidden="true" className={cn("mt-0.5 size-4 shrink-0", requested || historical ? "text-muted-foreground" : "text-(--status-task-icon-todo)")} />
<div className="flex min-w-0 flex-1 flex-col gap-2">
<div className="flex flex-col gap-1" role="status" aria-live="polite">
<h2 id={titleId} className="break-words text-sm font-medium text-foreground">
{requested ? "Retry requested" : historical ? "Agent needed attention" : "Agent needs attention"}
</h2>
<p className="text-sm leading-relaxed text-muted-foreground">
{requested ? `The task was returned to To do for ${agentName}.` : descriptionFor(snapshot)}
</p>
</div>
{unavailableReason && !requested ? (
<p id={unavailableId} className="text-xs leading-relaxed text-muted-foreground">
{!historical && <span className="font-medium text-foreground">Retry unavailable. </span>}{unavailableReason}
</p>
) : null}
{error ? <p role="alert" className="text-sm text-destructive">Couldn’t confirm the retry. {error}</p> : null}
<div className="flex flex-wrap items-center gap-2">
{!requested && !historical ? (
<Button size="xs" variant="outline" disabled={pending || Boolean(unavailableReason)} aria-describedby={unavailableReason ? unavailableId : undefined} onClick={() => void retry()}>
{pending ? <Loader2 aria-hidden="true" className="size-3 animate-spin motion-reduce:animate-none" /> : <RotateCcw aria-hidden="true" className="size-3" />}
{pending ? "Requesting retry…" : "Retry agent"}
</Button>
) : null}
<Button size="xs" variant="ghost" className="text-muted-foreground" aria-expanded={expanded} aria-controls={detailsId} onClick={() => setExpanded(current => !current)}>
{expanded ? "Hide details" : "View details"}
<ChevronDown aria-hidden="true" className={cn("size-3", expanded && "rotate-180")} />
</Button>
{createdAt ? <time dateTime={createdAt} className="font-mono text-xs text-muted-foreground sm:ml-auto">{timeAgo(createdAt)}</time> : null}
</div>
{expanded ? (
<div id={detailsId} className="flex flex-col gap-3 rounded-lg border border-border bg-muted/20 p-3">
<dl className="flex flex-col gap-2 text-xs">
<div className="flex flex-wrap justify-between gap-1"><dt className="text-muted-foreground">Assigned when recovery stopped</dt><dd>{agentName}</dd></div>
<div className="flex flex-wrap justify-between gap-1"><dt className="text-muted-foreground">Automatic attempts</dt><dd className="font-mono">{snapshot.attemptCount} of {snapshot.maxAttempts}</dd></div>
<div className="flex flex-wrap justify-between gap-1"><dt className="text-muted-foreground">Automatic retries for this recovery</dt><dd>Stopped</dd></div>
</dl>
<p className="text-xs leading-relaxed text-muted-foreground">Recovery asked the assigned agent to record an outcome or a next step. Retrying keeps the same task and agent, and checks the task’s current controls before continuing.</p>
<div className="flex flex-col gap-1"><span className="text-xs text-muted-foreground">Technical reason</span><code className="break-all font-mono text-xs">{snapshot.reason}</code></div>
</div>
) : null}
</div>
</section>
);
}
+6
View File
@@ -1,3 +1,4 @@
import { DispositionRecoveryNotice, useDispositionRecoverySnapshot } from "./DispositionRecoveryNotice";
import { AgentAvatar } from "@/components/AgentAvatar";
import { TaskChatPausedTakeover, type TaskComposerPause } from "./task-chat/TaskChatPausedTakeover";
import { useEmailComment } from "./EmailMessageCard";
@@ -3504,6 +3505,7 @@ function SystemNoticeCommentContent({
const commentMetadata = isIssueCommentMetadata(custom.commentMetadata)
? custom.commentMetadata
: null;
const recoverySnapshot = useDispositionRecoverySnapshot(commentMetadata);
const runAgentId =
typeof custom.runAgentId === "string" ? custom.runAgentId : null;
const runId = typeof custom.runId === "string" ? custom.runId : null;
@@ -3600,6 +3602,10 @@ function SystemNoticeCommentContent({
});
};
if (authorType === "system" && recoverySnapshot) {
return <div id={anchorId}><DispositionRecoveryNotice snapshot={recoverySnapshot} createdAt={toValidIsoString(message.createdAt)} defaultExpanded={presentation?.detailsDefaultOpen} /></div>;
}
if (staleSuccessfulRunHandoffNotice) {
return (
<StaleDispositionWarningRow
@@ -106,6 +106,18 @@ const baseTimestamps = {
};
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",
+12
View File
@@ -246,6 +246,18 @@ describe.each(["legacy", "native"] as const)("%s task history readiness", (runti
);
});
it("preserves the typed disposition notice through the task-chat adapter", () => {
render(<TaskChatThread comments={[{
id: "typed-recovery", companyId: "company", issueId: "issue", authorType: "system", authorAgentId: null, authorUserId: null,
body: "Unrelated prose", createdAt: new Date(), updatedAt: new Date(),
presentation: { kind: "system_notice", title: "Different wording", tone: "warning", detailsDefaultOpen: false, density: "compact" },
metadata: { version: 1, sections: [], recovery: { kind: "disposition_repair_escalated", actionId: "action", assigneeAgentId: "agent", attemptCount: 2, maxAttempts: 2, reason: "unchanged_source_state_exhausted" } },
}]} onAdd={async () => {}} issueStatus="blocked" />);
expect(container.querySelector('[data-testid="disposition-recovery-notice"]')).not.toBeNull();
expect(container.textContent).toContain("Two automatic attempts");
expect(container.textContent).not.toContain("Unrelated prose");
});
it("keeps an acknowledged optimistic bubble mounted with its canonical comment target", () => {
const comment = {
companyId: "company",
@@ -37,7 +37,7 @@ export function TaskChatRichInput({
ariaLabelledBy,
testId = "task-chat-rich-input",
attachAriaLabel = "Attach image",
showImageAttachControls = true,
showImageAttachControls = false,
}: TaskChatRichInputProps) {
const editorRef = useRef<MarkdownEditorRef>(null);
const fileInputRef = useRef<HTMLInputElement>(null);
@@ -1,3 +1,4 @@
import { DispositionRecoveryNotice, useDispositionRecoverySnapshot } from "@/components/DispositionRecoveryNotice";
import { useId, useState } from "react";
import {
ChevronDown,
@@ -54,6 +55,7 @@ export function TaskChatSystemNotice({
onTryAgainNoLiveExecutionPath?: () => Promise<void> | void;
tryAgainNoLiveExecutionPathPending?: boolean;
}) {
const recoverySnapshot = useDispositionRecoverySnapshot(item.metadata);
const streamlined = useStreamlinedTaskChatPresentation();
const [open, setOpen] = useState(Boolean(item.presentation?.detailsDefaultOpen));
const detailsId = useId();
@@ -82,6 +84,10 @@ export function TaskChatSystemNotice({
.catch(() => undefined);
};
if (item.author === "system" && recoverySnapshot) {
return <DispositionRecoveryNotice snapshot={recoverySnapshot} createdAt={item.createdAtIso} defaultExpanded={item.presentation?.detailsDefaultOpen} />;
}
return (
<div
className={cn("tc-enter-bubble flex flex-col items-start", streamlined ? "py-0.5" : "py-1")}
+12 -2
View File
@@ -3,13 +3,14 @@ import { readFileSync } from "node:fs";
import vm from "node:vm";
import { describe, expect, it, vi } from "vitest";
function worker() {
function worker(development = false) {
const handlers = new Map<string, (event: unknown) => void>();
const put = vi.fn();
const match = vi.fn();
const remove = vi.fn().mockResolvedValue(true);
const fetch = vi.fn().mockResolvedValue(new Response("public asset"));
vm.runInNewContext(readFileSync(new URL("../../public/sw.js", import.meta.url), "utf8"), {
const source = readFileSync(new URL("../../public/sw.js", import.meta.url), "utf8");
vm.runInNewContext(development ? source : source.replace("__PAPERCLIP_BUILD_ID__", "fixture-production"), {
self: { location: { origin: "https://example.test" }, addEventListener: (type: string, fn: (event: unknown) => void) => handlers.set(type, fn) },
URL, Response, fetch, caches: { keys: async () => ["paperclip-old", "paperclip-current"], open: async () => ({ put, delete: remove, match }), match },
});
@@ -22,6 +23,15 @@ function worker() {
}
describe("service worker privacy boundaries", () => {
it("leaves development navigation and module revalidation to the browser", () => {
const w = worker(true);
for (const path of ["/RUN/issues/RUN-1", "/src/main.tsx", "/@fs/vite-cache/deps/react.js?v=1"]) {
expect(w.request("default", path)).not.toHaveBeenCalled();
}
expect(w.fetch).not.toHaveBeenCalled();
expect(w.put).not.toHaveBeenCalled();
expect(w.match).not.toHaveBeenCalled();
});
it("bypasses both caching and offline fallback for a no-store request outside /api", () => {
const w = worker();
expect(w.request("no-store")).not.toHaveBeenCalled();
+4 -1
View File
@@ -29,7 +29,10 @@ function loadServiceWorkerFetchListener(overrides: {
keys: vi.fn(async () => []),
delete: vi.fn(async () => true),
};
const code = readFileSync(resolve(uiRoot, "public/sw.js"), "utf8");
// Offline fallback belongs to a stamped production build. Development
// leaves Vite requests to the browser instead of intercepting them.
const code = readFileSync(resolve(uiRoot, "public/sw.js"), "utf8")
.replace("__PAPERCLIP_BUILD_ID__", "fixture-production");
new Function("self", "caches", "fetch", "Response", "URL", code)(
swSelf,
caches,
+8
View File
@@ -1,3 +1,4 @@
import { DispositionRecoveryNotice } from "../components/DispositionRecoveryNotice";
import { SetupPrompt } from "./apps/chat/SetupPrompt";
import { MediaArtifactCard } from "@/components/artifacts/MediaArtifactCard";
import { WebhookUrlWarning } from "@/components/routine-triggers/WebhookUrlWarning";
@@ -2189,6 +2190,13 @@ export function DesignGuide() {
</SubSection>
</Section>
<Section title="Disposition recovery notice">
<SubSection title="Needs attention, with inspectable details">
<DispositionRecoveryNotice snapshot={{ kind: "disposition_repair_escalated", actionId: "design-recovery", attemptCount: 2, maxAttempts: 2, reason: "unchanged_source_state_exhausted", assigneeAgentId: null }} defaultExpanded />
</SubSection>
<p className="text-sm text-muted-foreground">Storybook’s Recovery notice stories show the actionable, pending, acknowledged, unavailable, failed, and mobile states using this production component.</p>
</Section>
<Section title="Execution recovery">
<p className="text-sm text-muted-foreground">
Recovery runs in the background. Task lists keep their ordinary status without
+39
View File
@@ -1,6 +1,7 @@
import { TaskChatPausedTakeover, type TaskComposerPause } from "../components/task-chat/TaskChatPausedTakeover";
// @vitest-environment jsdom
import { DispositionRecoveryNotice, type DispositionRecoverySnapshot } from "../components/DispositionRecoveryNotice";
import { RichWorkProductCard } from "../components/task-chat/RichWorkProductCard";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import type {
@@ -393,6 +394,7 @@ vi.mock("../components/IssueChatThread", () => ({
// the IssueChatThread stub above.
vi.mock("../components/TaskChatThread", () => ({
TaskChatThread: (props: {
comments?: Array<{ metadata?: { recovery?: DispositionRecoverySnapshot } | null }>;
workProducts?: IssueWorkProduct[];
threadHeader?: ReactNode;
onStopRun?: (runId: string) => Promise<void>;
@@ -415,6 +417,7 @@ vi.mock("../components/TaskChatThread", () => ({
<div data-testid="task-chat-thread">
{props.threadHeader}
Task chat thread
{props.comments?.map((comment, index) => comment.metadata?.recovery ? <DispositionRecoveryNotice key={index} snapshot={comment.metadata.recovery} /> : null)}
{props.workProducts?.map((workProduct) => (
<RichWorkProductCard
key={workProduct.id}
@@ -2542,6 +2545,42 @@ describe("IssueDetail", () => {
mockIssuesApi.resolveRecoveryAction.mockReset();
});
it.each(["success", "failure", "pending question"])("connects the inline disposition retry to current state (%s)", async outcome => {
const fail = outcome === "failure";
const actionId = "recovery-action-inline";
const snapshot: DispositionRecoverySnapshot = { kind: "disposition_repair_escalated", actionId, attemptCount: 2, maxAttempts: 2, reason: "unchanged_source_state_exhausted", assigneeAgentId: "agent-1" };
const issue = createIssue({ status: "blocked", assigneeAgentId: "agent-1", activeRecoveryAction: {
id: actionId, status: "active", kind: "deliberate_wait_without_target", ownerType: "board", returnOwnerAgentId: "agent-1", wakePolicy: { type: "board_escalation" },
companyId: "company-1", sourceIssueId: "issue-1", recoveryIssueId: null, ownerAgentId: null, ownerUserId: null,
previousOwnerAgentId: "agent-1", cause: "deliberate_wait_without_target", fingerprint: "fixture", evidence: {}, nextAction: "Retry", monitorPolicy: null,
attemptCount: 2, maxAttempts: 2, timeoutAt: null, lastAttemptAt: null, outcome: null, resolutionNote: null, resolvedAt: null, createdAt: new Date(), updatedAt: new Date(),
} });
mockIssuesApi.get.mockResolvedValue(issue);
mockIssuesApi.listComments.mockResolvedValue([{ id: "notice-inline", companyId: issue.companyId, issueId: issue.id, authorType: "system", body: "Unrelated prose", createdAt: new Date(), updatedAt: new Date(), metadata: { version: 1, sections: [], recovery: snapshot } }]);
if (outcome === "pending question") mockIssuesApi.listInteractions.mockResolvedValue([{ id: "question-1", kind: "ask_user_questions", status: "pending", payload: { version: 1, questions: [] } }]);
if (fail) mockIssuesApi.resolveRecoveryAction.mockRejectedValue(new Error("The task is now paused."));
else mockIssuesApi.resolveRecoveryAction.mockResolvedValue({ issue: { ...issue, status: "todo", activeRecoveryAction: null }, recoveryAction: { ...issue.activeRecoveryAction, status: "resolved" } });
await act(async () => root.render(<QueryClientProvider client={queryClient}><IssueDetail /></QueryClientProvider>));
await flushReact(); await flushReact();
const retry = Array.from(container.querySelectorAll("button")).find(b => b.textContent === "Retry agent");
expect(retry).toBeDefined();
if (outcome === "pending question") {
expect(retry!.disabled).toBe(true);
expect(container.textContent).toContain("Respond to the pending question or confirmation before retrying.");
await act(async () => retry!.click());
expect(mockIssuesApi.resolveRecoveryAction).not.toHaveBeenCalled();
mockIssuesApi.resolveRecoveryAction.mockReset();
return;
}
expect(retry!.disabled).toBe(false);
await act(async () => retry!.click());
await waitForAssertion(() => {
expect(mockIssuesApi.resolveRecoveryAction).toHaveBeenCalledExactlyOnceWith(issue.identifier, { actionId, outcome: "restored", sourceIssueStatus: "todo" });
expect(container.textContent).toContain(fail ? "Couldn’t confirm the retry. The task is now paused." : "Retry requested");
});
mockIssuesApi.resolveRecoveryAction.mockReset();
});
it("removes an inbox-origin archived issue and restores it when the toast Undo action is pressed", async () => {
const issue = createIssue({
id: "issue-1",
+50
View File
@@ -1,3 +1,4 @@
import { DispositionRecoveryProvider } from "../components/DispositionRecoveryNotice";
import { AgentAvatar } from "@/components/AgentAvatar";
import { AgentIdentity } from "@/components/AgentIdentity";
import { clearLegacyChatMessageRequests } from "@/lib/chat-message-request";
@@ -4102,6 +4103,39 @@ export function TaskDetailSurface({ conversation, tasksTab }: { tasksTab?: TaskS
}
},
});
// The inline notice owns feedback; do not also emit a global error toast.
const retryDispositionRecovery = useMutation({
mutationFn: async (actionId: string) => {
const result = await issuesApi.resolveRecoveryAction(issueId!, {
actionId,
outcome: "restored",
sourceIssueStatus: "todo",
});
if (
result.issue.status !== "todo" ||
result.issue.assigneeAgentId !== result.recoveryAction.returnOwnerAgentId
) {
throw new Error("The task’s state has changed. Refresh to see its current state.");
}
return result;
},
onSuccess: ({ issue: nextIssue }) => {
const issueRefs = new Set<string>([issueId!, nextIssue.id]);
if (nextIssue.identifier) issueRefs.add(nextIssue.identifier);
mergeIssueResponseIntoCaches(issueRefs, nextIssue);
invalidateIssueCollections();
},
onSettled: () => {
for (const queryKey of [
queryKeys.issues.detail(issueId!),
queryKeys.issues.activity(issueId!),
queryKeys.issues.runs(issueId!),
queryKeys.issues.liveRuns(issueId!),
]) {
void queryClient.invalidateQueries({ queryKey });
}
},
});
const executeTreeControl = useMutation({
onMutate: () => setTreeControlWakeWarning(null),
mutationFn: async ({
@@ -7694,6 +7728,21 @@ export function TaskDetailSurface({ conversation, tasksTab }: { tasksTab?: TaskS
<ExecutionBlockerNotice companyId={issue.companyId} issueId={issue.id} blocker={issue.executionBlocker} onRetried={invalidateIssueDetail} />
)}
{resolvedDetailTab === "chat" ? (
<DispositionRecoveryProvider value={{
issue,
agentMap,
hasPendingInteraction: interactions.some((interaction) => interaction.status === "pending"),
unavailableReason: boardAccess && !canResolveBoardRecoveryAction
? "You don’t have permission to retry this recovery action."
: treeControlStateError
? "Couldn’t check whether this task is paused. Refresh to try again."
: activePauseHold
? "The task is paused. Resume it before retrying."
: issue.project?.pausedAt
? "The project is paused. Resume it before retrying."
: null,
onRetry: (actionId) => retryDispositionRecovery.mutateAsync(actionId).then(() => undefined),
}}>
<IssueDetailChatTab
onOpenSkill={handleOpenSkill}
threadHeader={<>{taskChatThreadHeader}{instanceExperimentalSettings?.enableChatConnectors && <EmailTaskActivity key={issue.id} companyId={issue.companyId} issueId={issue.id} />}</>}
@@ -7943,6 +7992,7 @@ export function TaskDetailSurface({ conversation, tasksTab }: { tasksTab?: TaskS
}
linkCaseReferences={casesChipsEnabled}
/>
</DispositionRecoveryProvider>
) : null}
</TabsContent>
+31 -2
View File
@@ -30,6 +30,7 @@ const mockResourceMembershipsApi = vi.hoisted(() => ({
updateProject: vi.fn(),
}));
const mockNavigate = vi.hoisted(() => vi.fn());
const mockParams = vi.hoisted(() => ({ projectId: "project-1" }));
const mockSetBreadcrumbs = vi.hoisted(() => vi.fn());
const mockIssuesList = vi.hoisted(() => vi.fn());
const mockSummarySlotCard = vi.hoisted(() => vi.fn());
@@ -59,7 +60,7 @@ vi.mock("@/lib/router", () => ({
Navigate: ({ to }: { to: string }) => <div data-testid="navigate">{to}</div>,
useLocation: () => ({ pathname: mockLocation.pathname, search: mockLocation.search, hash: "", state: null }),
useNavigate: () => mockNavigate,
useParams: () => ({ projectId: "project-1" }),
useParams: () => mockParams,
}));
vi.mock("../context/CompanyContext", () => ({
@@ -82,7 +83,7 @@ vi.mock("@/plugins/slots", () => ({
}));
vi.mock("@/plugins/launchers", () => ({ PluginLauncherOutlet: () => null }));
vi.mock("../components/ProjectProperties", () => ({
ProjectProperties: () => <div data-testid="project-properties" />,
ProjectProperties: () => <div data-testid="project-properties"><input aria-label="Unsaved project field" /></div>,
}));
vi.mock("../components/BudgetPolicyCard", () => ({
BudgetPolicyCard: () => <div data-testid="budget-policy-card" />,
@@ -181,6 +182,7 @@ describe("ProjectDetail", () => {
document.body.appendChild(container);
mockLocation.pathname = "/projects/project-1/plugin-operations";
mockLocation.search = "";
mockParams.projectId = "project-1";
mockCompanyContext.companies = [{ id: "company-1", issuePrefix: "PAP" }];
mockCompanyContext.selectedCompanyId = "company-1";
mockUsePluginSlots.mockReturnValue({ slots: [], isLoading: false });
@@ -212,6 +214,33 @@ describe("ProjectDetail", () => {
vi.clearAllMocks();
});
it.each(["alias", "other project", "other company"])("preserves a draft only for a same-project route alias (%s)", async target => {
const loaded = project({ urlKey: "managed-project" });
mockLocation.pathname = "/projects/project-1/configuration";
mockProjectsApi.get.mockResolvedValueOnce(loaded);
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 0 } } });
const render = () => root!.render(<QueryClientProvider client={queryClient}><ProjectDetail /></QueryClientProvider>);
root = createRoot(container);
await act(render);
await act(async () => { await new Promise(resolve => setTimeout(resolve, 0)); await new Promise(resolve => setTimeout(resolve, 0)); });
const draft = container.querySelector<HTMLInputElement>('input[aria-label="Unsaved project field"]');
expect(draft).not.toBeNull();
draft!.value = "Unsaved repository removal";
mockProjectsApi.get.mockImplementation(() => new Promise(() => {}));
mockParams.projectId = target === "other project" ? "different-project" : "managed-project";
if (target === "other company") mockCompanyContext.selectedCompanyId = "company-2";
mockLocation.pathname = `/projects/${mockParams.projectId}/configuration`;
await act(render);
const after = container.querySelector<HTMLInputElement>('input[aria-label="Unsaved project field"]');
if (target === "alias") {
expect(after).toBe(draft);
expect(after!.value).toBe("Unsaved repository removal");
} else {
expect(after).toBeNull();
}
await act(() => queryClient.clear());
});
it("shows managed plugin affordances and filters the operations tab by plugin origin", async () => {
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+7
View File
@@ -357,6 +357,13 @@ export function ProjectDetail() {
queryKey: [...queryKeys.projects.detail(routeProjectRef), lookupCompanyId ?? null],
queryFn: () => projectsApi.get(routeProjectRef, lookupCompanyId),
enabled: canFetchProject,
// Canonicalizing the same project's URL must not unmount its edit form
// while the alias query loads. Never carry data into another company or project.
placeholderData: (previous) => previous &&
previous.companyId === lookupCompanyId &&
(previous.id === routeProjectRef || projectRouteRef(previous) === routeProjectRef)
? previous
: undefined,
});
const canonicalProjectRef = project ? projectRouteRef(project) : routeProjectRef;
const projectLookupRef = project?.id ?? routeProjectRef;