mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-19 07:42:38 +01:00
Show live provider reset countdowns in the viewer's timezone (#22225)
## Thinking Path > - Paperclip manages agents and their assigned work. > - Provider usage limits can hold that work until a reset deadline. > - Saved wait messages expose raw timestamps, and the usage popover shows a short weekday clock. > - People need the remaining wait and the exact deadline in their current timezone. > - This pull request formats both views in the browser and updates the countdown live. > - The browser uses its timezone while stored messages and retry deadlines stay unchanged. ## Linked Issues or Issue Description **What existing behavior does this improve?** Provider usage limit messages and the agent usage-limit property and popover. **Subsystem affected** UI presentation of provider usage limits, task notices, run details, log events, and recovery actions. **Current behavior** Wait messages print `2026-11-18T20:17:34.353Z`. The usage popover shows a short clock such as `Thu 23:00`. Neither gives a live relative countdown. If the provider did not report a reset, the scheduler uses the recorded failure time plus one hour. **Proposed behavior** A Pacific-time viewer sees `in 44 minutes (Nov 18, 2026, 12:17 PM PST)`. The relative part counts down while the tab is visible. The usage property and popover show the same local deadline. Expired usage windows clear through the existing summary rules. **Reason and benefit** People can see how long remains without converting a timestamp or refreshing the page. The date conversion handles daylight saving time and local date changes. **Breaking changes** Displayed text and popover layout change. Stored messages, API payloads, error codes, provider checks, and retry deadlines keep their contracts. ## What Changed - Add an optional timezone label to the existing `formatDateTime` helper. Existing callers keep their output. - Share relative and exact local time formatting between provider-limit messages and the usage popover. Unrelated text and invalid timestamps stay intact. - Reuse the existing shared one-second ticker. Countdown updates pause in hidden tabs, catch up when shown, and stop at the deadline or on unmount. No API polling is added. - Keep timer-driven message rendering separate from large parent pages. Hidden task-marker details do not subscribe until opened. - Update task notices, agent run errors in both UI shells, log events, and provider-limit next actions. - Update the usage-limit trigger and every window in its popover. Reset details wrap below the percentage row. The reported timestamp includes its timezone. Explicit clocks remain fixed for stories. ## Verification Tested source: `ef79ce40b170db89a6b831162c72d6446cd9492d`. Local checks ran with the same file contents on macOS arm64, Node 25.6.1, and pnpm 9.15.4. - From `ui/`: `pnpm exec vitest run src/lib/provider-limit-message.test.ts src/lib/utils.date-time.test.ts src/components/ProviderLimitMessage.test.tsx src/hooks/useSecondTick.test.tsx src/components/AgentRateLimitGauge.test.tsx src/components/task-chat/TaskChatMarker.test.tsx src/components/task-chat/TaskChatSystemNotice.test.tsx src/components/IssueRunLedger.test.tsx src/components/IssueRecoveryActionCard.test.tsx src/components/StalledDependencyNotice.test.tsx src/pages/AgentDetail.log-visibility.test.tsx src/pages/AgentDetail.log-resilience.test.tsx` — 176 tests passed across 12 files. - From `ui/`: `pnpm run typecheck` — passed, including Storybook catalog generation. - From the repository root: `pnpm check:token-gates` and `git diff --check` — passed. - Regression proof: four live-message cases failed against static rendering. Four usage-popover cases failed against the old clock. Both suites passed after the changes. - Fake-clock tests prove `44 minutes` becomes `43 minutes` without a page refresh or parent render. Other cases cover seconds near the deadline, one shared timer, hidden-tab pause and catch-up, expiry, and cleanup. - Timezone cases cover Pacific, India, and New Zealand timezones, a local date rollover, and daylight saving time. Task notice cases cover both presentations. Usage-popover cases cover Claude and Codex. - Local setup required a non-frozen install because the base lockfile lacked two AWS SDK dependencies from the server manifest. No dependency or lockfile change is included. - Final CI: [workflow attempt 4](https://github.com/paperclipai/paperclip/actions/runs/44384225521/attempts/4) succeeded on `ef79ce40b170db89a6b831162c72d6446cd9492d`. All 54 successful checks are green, including the applicable typecheck, build, server tests, Runner checks, and all eight end-to-end shards. Optional jobs skipped by the CI plan remain skipped. - Recovery record: [Canary attempt 1](https://github.com/paperclipai/paperclip/actions/runs/44384225521/job/135085343566), [attempt 2](https://github.com/paperclipai/paperclip/actions/runs/44384225521/job/135097010510), and [attempt 3](https://github.com/paperclipai/paperclip/actions/runs/44384225521/job/135100921795) ended with runner shutdown signals at 19:56:15, 20:12:55, and 20:19:18 UTC. The aggregate verification failures reflected that canary result. No source changed between attempts. The [fourth Canary Dry Run](https://github.com/paperclipai/paperclip/actions/runs/44384225521/job/135105826026) and [aggregate verification](https://github.com/paperclipai/paperclip/actions/runs/44384225521/job/135110708013) passed. - Greptile reviewed the final commit at 5/5 with no actionable findings and no unresolved review threads. GitHub reports the branch mergeable with a clean merge state. - Full local repository checks and manual browser acceptance were not run. CI supplied broad coverage on the final revision. The local popover tests exercise its content and clock with mocked popover primitives. ## Risks - Low risk. This changes UI presentation only. No migration or scheduler change is required. - The ticker updates visible future countdowns once per second. It makes no provider request and does not certify that provider capacity has returned. - Message recognition uses the existing provider-limit wording and ISO timestamps. Unrecognized messages retain their text. - Local timezone abbreviations can differ by browser locale data. Time conversion uses the browser's timezone rules. ## Model Used - OpenAI Codex, `gpt-6.1-sol`, with xhigh reasoning effort, repository inspection, code edits, and test execution. ## 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 - [x] I have described the issue in-PR with the enhancement template fields - [x] I have not referenced internal or instance-local Paperclip issues or links - [x] My branch name describes the change and contains no internal ticket id - [x] I have run the focused tests locally and they pass - [x] I have added or updated tests where applicable - [x] The code, tests, and this description document the changed output - [x] I have considered and documented the risks - [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:
1 parent
d668eeb660
commit
e4b119440e
18 files changed
+368
-41
No files matched your search
@@ -0,0 +1,74 @@
|
||||
// @vitest-environment jsdom
|
||||
import type { ReactNode } from "react";
|
||||
import { flushSync } from "react-dom";
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { ProviderRateLimitSnapshot } from "@paperclipai/shared";
|
||||
import { AgentRateLimitPropertyValue } from "./AgentRateLimitGauge";
|
||||
|
||||
vi.mock("@/components/ui/popover", () => ({
|
||||
Popover: ({ children }: { children: ReactNode }) => <>{children}</>,
|
||||
PopoverTrigger: ({ children }: { children: ReactNode }) => <>{children}</>,
|
||||
PopoverContent: ({ children }: { children: ReactNode }) => <div data-testid="usage-popover">{children}</div>,
|
||||
}));
|
||||
vi.mock("@/lib/router", () => ({ Link: ({ to, children }: { to: string; children: ReactNode }) => <a href={to}>{children}</a> }));
|
||||
|
||||
describe("usage limit property and popover", () => {
|
||||
const now = Date.parse("2099-11-18T19:33:34.353Z");
|
||||
const resetAt = "2099-11-18T20:17:34.353Z";
|
||||
let container: HTMLDivElement;
|
||||
let root: Root;
|
||||
const snapshot: ProviderRateLimitSnapshot = {
|
||||
schema: "paperclip.provider.rate_limits.v1", provider: "anthropic",
|
||||
windows: [{ id: "weekly", label: "Weekly", shortLabel: "7d", windowMinutes: 10080, usedPercent: 100, resetsAt: resetAt, status: "rejected" }],
|
||||
credits: null, limitReached: { windowId: "weekly", reason: "rate_limit_reached", resetsAt: resetAt },
|
||||
observedAt: "2099-11-18T19:28:34.353Z",
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.stubEnv("TZ", "America/Los_Angeles");
|
||||
vi.useFakeTimers();
|
||||
vi.setSystemTime(now);
|
||||
vi.spyOn(document, "visibilityState", "get").mockReturnValue("visible");
|
||||
container = document.createElement("div");
|
||||
document.body.append(container);
|
||||
root = createRoot(container);
|
||||
});
|
||||
afterEach(() => {
|
||||
flushSync(() => root.unmount());
|
||||
container.remove();
|
||||
vi.useRealTimers();
|
||||
vi.restoreAllMocks();
|
||||
vi.unstubAllEnvs();
|
||||
});
|
||||
|
||||
it.each(["anthropic", "openai"] as const)("shows a live countdown and exact local deadline for %s", provider => {
|
||||
flushSync(() => root.render(<AgentRateLimitPropertyValue snapshot={{ ...snapshot, provider }} detailsHref="/agents/test-agent" defaultOpen />));
|
||||
const trigger = container.querySelector("button")!;
|
||||
const panel = container.querySelector('[data-testid="usage-popover"]')!;
|
||||
expect(trigger.textContent).toContain("resets in 44 minutes (Nov 18, 2099, 12:17 PM PST)");
|
||||
expect(panel.textContent).toContain(`${provider === "openai" ? "Codex" : "Claude"} usage limits`);
|
||||
expect(panel.textContent).toContain("Weekly100%");
|
||||
expect(panel.textContent).toContain("Resets in 44 minutes (Nov 18, 2099, 12:17 PM PST)");
|
||||
expect(panel.textContent).toContain("Reported Nov 18, 2099, 11:28 AM PST");
|
||||
expect(panel.querySelector("a")?.getAttribute("href")).toBe("/agents/test-agent");
|
||||
flushSync(() => vi.advanceTimersByTime(60_000));
|
||||
expect(trigger.textContent).toContain("resets in 43 minutes (");
|
||||
expect(panel.textContent).toContain("Resets in 43 minutes (");
|
||||
});
|
||||
|
||||
it("clears stale exhausted usage when the reset passes", () => {
|
||||
flushSync(() => root.render(<AgentRateLimitPropertyValue snapshot={snapshot} defaultOpen />));
|
||||
expect(container.textContent).toContain("Limited");
|
||||
flushSync(() => vi.advanceTimersByTime(44 * 60_000));
|
||||
expect(container.textContent).toBe("");
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
});
|
||||
|
||||
it("keeps an explicitly supplied clock fixed for stories and previews", () => {
|
||||
flushSync(() => root.render(<AgentRateLimitPropertyValue snapshot={snapshot} now={now} defaultOpen />));
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
flushSync(() => vi.advanceTimersByTime(60 * 60_000));
|
||||
expect(container.textContent).toContain("in 44 minutes (");
|
||||
});
|
||||
});
|
||||
@@ -1,3 +1,4 @@
|
||||
import { useMemo } from "react";
|
||||
import { ChevronRight, Clock } from "lucide-react";
|
||||
import {
|
||||
summarizeProviderRateLimits,
|
||||
@@ -6,7 +7,9 @@ import {
|
||||
} from "@paperclipai/shared";
|
||||
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
|
||||
import { Link } from "@/lib/router";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { cn, formatDateTime } from "@/lib/utils";
|
||||
import { formatProviderLimitTime } from "@/lib/provider-limit-message";
|
||||
import { useProviderLimitClock } from "@/hooks/useProviderLimitMessage";
|
||||
|
||||
type Tone = ProviderRateLimitSummary["tone"];
|
||||
|
||||
@@ -22,14 +25,6 @@ const textClass: Record<Tone, string> = {
|
||||
reached: "text-destructive",
|
||||
};
|
||||
|
||||
export function formatRateLimitClock(iso: string, now: number): string {
|
||||
const at = new Date(iso);
|
||||
const time = at.toLocaleTimeString("en-US", { hour: "2-digit", minute: "2-digit", hour12: false });
|
||||
if (new Date(now).toDateString() === at.toDateString()) return time;
|
||||
if (Math.abs(at.getTime() - now) < 6 * 86_400_000) return `${at.toLocaleDateString("en-US", { weekday: "short" })} ${time}`;
|
||||
return `${at.toLocaleDateString("en-US", { month: "short", day: "numeric" })} ${time}`;
|
||||
}
|
||||
|
||||
function Bar({ pct, tone, className }: { pct: number; tone: Tone; className?: string }) {
|
||||
const clamped = Math.min(100, Math.max(0, pct));
|
||||
return (
|
||||
@@ -64,11 +59,9 @@ export function AgentRateLimitPanel({ snapshot, summary, now }: {
|
||||
<span className="truncate text-muted-foreground">{window.label}</span>
|
||||
<span className={cn("shrink-0 tabular-nums", textClass[tone])}>
|
||||
{Math.round(pct)}%
|
||||
{window.resetsAt && (
|
||||
<span className="text-muted-foreground"> · resets {formatRateLimitClock(window.resetsAt, now)}</span>
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
{window.resetsAt && <div className="text-xs tabular-nums text-muted-foreground">Resets {formatProviderLimitTime(window.resetsAt, now)}</div>}
|
||||
<Bar pct={pct} tone={tone} className="w-full" />
|
||||
</div>
|
||||
);
|
||||
@@ -85,13 +78,7 @@ export function AgentRateLimitPanel({ snapshot, summary, now }: {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* One-line "Usage limit" property value: "5h 78% · resets 15:40", amber above
|
||||
* 80%, "Limited until 15:40" while the provider refuses work, "using credits"
|
||||
* when a used-up window falls back to account credits. Click opens the
|
||||
* full window breakdown. Renders nothing when no current limit data exists.
|
||||
*/
|
||||
export function AgentRateLimitPropertyValue({ snapshot, now = Date.now(), defaultOpen, detailsHref, className }: {
|
||||
export function AgentRateLimitPropertyValue({ snapshot, now: fixedNow, defaultOpen, detailsHref, className }: {
|
||||
snapshot: ProviderRateLimitSnapshot | null;
|
||||
now?: number;
|
||||
defaultOpen?: boolean;
|
||||
@@ -99,14 +86,23 @@ export function AgentRateLimitPropertyValue({ snapshot, now = Date.now(), defaul
|
||||
detailsHref?: string;
|
||||
className?: string;
|
||||
}) {
|
||||
const resetAt = useMemo(() => {
|
||||
let latest: number | null = null;
|
||||
for (const iso of [...(snapshot?.windows.map(window => window.resetsAt) ?? []), snapshot?.limitReached?.resetsAt]) {
|
||||
const time = iso ? Date.parse(iso) : Number.NaN;
|
||||
if (Number.isFinite(time)) latest = Math.max(latest ?? time, time);
|
||||
}
|
||||
return latest;
|
||||
}, [snapshot]);
|
||||
const now = useProviderLimitClock(resetAt, fixedNow);
|
||||
const summary = summarizeProviderRateLimits(snapshot, now);
|
||||
if (!snapshot || !summary) return null;
|
||||
const { window, tone } = summary;
|
||||
const label = summary.limited
|
||||
? `Limited${summary.limitedUntil ? ` until ${formatRateLimitClock(summary.limitedUntil, now)}` : ""}`
|
||||
? `Limited${summary.limitedUntil ? ` · resets ${formatProviderLimitTime(summary.limitedUntil, now)}` : ""}`
|
||||
: summary.usingCredits
|
||||
? `${window!.shortLabel} ${Math.round(window!.usedPercent ?? 0)}% · using credits`
|
||||
: `${window!.shortLabel} ${Math.round(window!.usedPercent ?? 0)}%${window!.resetsAt ? ` · resets ${formatRateLimitClock(window!.resetsAt, now)}` : ""}`;
|
||||
: `${window!.shortLabel} ${Math.round(window!.usedPercent ?? 0)}%${window!.resetsAt ? ` · resets ${formatProviderLimitTime(window!.resetsAt, now)}` : ""}`;
|
||||
return (
|
||||
<Popover defaultOpen={defaultOpen}>
|
||||
<PopoverTrigger asChild>
|
||||
@@ -118,6 +114,7 @@ export function AgentRateLimitPropertyValue({ snapshot, now = Date.now(), defaul
|
||||
className,
|
||||
)}
|
||||
aria-label={`Provider usage limit: ${label}`}
|
||||
title={label}
|
||||
>
|
||||
{summary.limited
|
||||
? <Clock className="h-3.5 w-3.5 shrink-0" aria-hidden />
|
||||
@@ -129,9 +126,9 @@ export function AgentRateLimitPropertyValue({ snapshot, now = Date.now(), defaul
|
||||
<PopoverContent align="start" className="w-72 space-y-3 p-3">
|
||||
<div className="text-xs font-medium">{snapshot.provider === "openai" ? "Codex" : "Claude"} usage limits</div>
|
||||
<AgentRateLimitPanel snapshot={snapshot} summary={summary} now={now} />
|
||||
<div className="flex items-center justify-between gap-3 text-(length:--text-micro) text-muted-foreground">
|
||||
<span>Reported {formatRateLimitClock(snapshot.observedAt, now)}</span>
|
||||
{detailsHref && <Link to={detailsHref} className="hover:text-foreground hover:underline">View agent</Link>}
|
||||
<div className="flex flex-wrap items-center justify-between gap-3 text-(length:--text-micro) text-muted-foreground">
|
||||
<span>Reported {formatDateTime(snapshot.observedAt, { includeTimeZone: true })}</span>
|
||||
{detailsHref && <Link to={detailsHref} className="shrink-0 hover:text-foreground hover:underline">View agent</Link>}
|
||||
</div>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
|
||||
@@ -40,6 +40,7 @@ import {
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { agentUrl } from "@/lib/utils";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { ProviderLimitMessage } from "./ProviderLimitMessage";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import {
|
||||
deriveRecoveryDisplayState,
|
||||
@@ -1318,7 +1319,7 @@ export function IssueRecoveryActionCard({
|
||||
)}
|
||||
</MetadataRow>
|
||||
<MetadataRow label="Next action">
|
||||
{action.nextAction ? <span>{action.nextAction}</span> : <MissingValue />}
|
||||
{action.nextAction ? <span><ProviderLimitMessage>{action.nextAction}</ProviderLimitMessage></span> : <MissingValue />}
|
||||
</MetadataRow>
|
||||
<MetadataRow label="Follow-up">
|
||||
<span className="inline-flex flex-wrap items-center gap-1.5">
|
||||
|
||||
@@ -27,6 +27,7 @@ import { cn, relativeTime } from "../lib/utils";
|
||||
import { queryKeys } from "../lib/queryKeys";
|
||||
import { keepPreviousDataForSameQueryTail } from "../lib/query-placeholder-data";
|
||||
import { describeRunRetryState } from "../lib/runRetryState";
|
||||
import { ProviderLimitMessage } from "./ProviderLimitMessage";
|
||||
import { readSourceResolvedWatchdogFold } from "../lib/source-resolved-watchdog-fold";
|
||||
import { SourceResolvedFoldBadge } from "./SourceResolvedFoldBadge";
|
||||
import { ResponsibleUserDenialNotice } from "./ResponsibleUserDenialNotice";
|
||||
@@ -1018,7 +1019,7 @@ export function IssueRunLedgerContent({
|
||||
Next action:{" "}
|
||||
</span>
|
||||
<span className="break-words text-muted-foreground">
|
||||
{nextAction}
|
||||
<ProviderLimitMessage>{nextAction}</ProviderLimitMessage>
|
||||
</span>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
// @vitest-environment jsdom
|
||||
import { flushSync } from "react-dom";
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { ProviderLimitMessage } from "./ProviderLimitMessage";
|
||||
|
||||
describe("live provider reset messages", () => {
|
||||
let container: HTMLDivElement;
|
||||
let root: Root;
|
||||
let visibility: DocumentVisibilityState;
|
||||
const resetAt = new Date(2099, 10, 18, 12, 17, 34, 353);
|
||||
const message = `The provider usage limit for this agent is expected to reset at ${resetAt.toISOString()}. Paperclip will start this work then.`;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
vi.setSystemTime(new Date(resetAt.getTime() - 44 * 60_000));
|
||||
visibility = "visible";
|
||||
vi.spyOn(document, "visibilityState", "get").mockImplementation(() => visibility);
|
||||
container = document.createElement("div");
|
||||
document.body.append(container);
|
||||
root = createRoot(container);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
flushSync(() => root.unmount());
|
||||
container.remove();
|
||||
vi.useRealTimers();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it("counts down without refreshing or rendering its parent again", () => {
|
||||
let parentRenders = 0;
|
||||
function Parent() {
|
||||
parentRenders += 1;
|
||||
return <ProviderLimitMessage>{message}</ProviderLimitMessage>;
|
||||
}
|
||||
flushSync(() => root.render(<Parent />));
|
||||
expect(container.textContent).toContain("in 44 minutes (Nov 18, 2099, 12:17 PM");
|
||||
flushSync(() => vi.advanceTimersByTime(60_000));
|
||||
expect(container.textContent).toContain("in 43 minutes (Nov 18, 2099, 12:17 PM");
|
||||
expect(parentRenders).toBe(1);
|
||||
});
|
||||
|
||||
it("shares one timer across messages and stops it on unmount", () => {
|
||||
flushSync(() => root.render(<><ProviderLimitMessage>{message}</ProviderLimitMessage><ProviderLimitMessage>{message}</ProviderLimitMessage></>));
|
||||
expect(vi.getTimerCount()).toBe(1);
|
||||
flushSync(() => root.render(null));
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
});
|
||||
|
||||
it("pauses in a hidden tab and immediately catches up when shown", () => {
|
||||
flushSync(() => root.render(<ProviderLimitMessage>{message}</ProviderLimitMessage>));
|
||||
flushSync(() => {
|
||||
visibility = "hidden";
|
||||
document.dispatchEvent(new Event("visibilitychange"));
|
||||
});
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
flushSync(() => vi.advanceTimersByTime(5 * 60_000));
|
||||
flushSync(() => {
|
||||
visibility = "visible";
|
||||
document.dispatchEvent(new Event("visibilitychange"));
|
||||
});
|
||||
expect(container.textContent).toContain("in 39 minutes (");
|
||||
expect(vi.getTimerCount()).toBe(1);
|
||||
});
|
||||
|
||||
it("updates the final seconds and stops ticking at the deadline", () => {
|
||||
vi.setSystemTime(new Date(resetAt.getTime() - 3000));
|
||||
flushSync(() => root.render(<ProviderLimitMessage>{message}</ProviderLimitMessage>));
|
||||
expect(container.textContent).toContain("in 3 seconds (");
|
||||
flushSync(() => vi.advanceTimersByTime(1000));
|
||||
expect(container.textContent).toContain("in 2 seconds (");
|
||||
flushSync(() => vi.advanceTimersByTime(2000));
|
||||
expect(container.textContent).toContain("reset now (");
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
});
|
||||
|
||||
it("does not tick for unrelated messages, invalid timestamps, or past deadlines", () => {
|
||||
for (const text of ["Run failed", "The provider usage limit resets at an unknown time.",
|
||||
"The provider usage limit resets at 2099-99-99T99:99:99.999Z.",
|
||||
"The provider usage limit resets at 2000-01-01T00:00:00Z."]) {
|
||||
flushSync(() => root.render(<ProviderLimitMessage>{text}</ProviderLimitMessage>));
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,5 @@
|
||||
import { useProviderLimitMessage } from "@/hooks/useProviderLimitMessage";
|
||||
|
||||
export function ProviderLimitMessage({ children }: { children: string }) {
|
||||
return useProviderLimitMessage(children);
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import { queryKeys } from "../lib/queryKeys";
|
||||
import { createIssueDetailPath } from "../lib/issueDetailBreadcrumb";
|
||||
import { useTaskRetry } from "../hooks/useTaskRetry";
|
||||
import { describeError } from "../api/errors";
|
||||
import { ProviderLimitMessage } from "./ProviderLimitMessage";
|
||||
|
||||
/**
|
||||
* Children and blockers of this task that stopped on a recovery action that
|
||||
@@ -73,7 +74,7 @@ function StalledDependencyRow({ entry, child, readError, isFetching, refetch }:
|
||||
</Link>
|
||||
<span className="min-w-0 flex-1 truncate">{entry.stalledIssueTitle}</span>
|
||||
{entry.recoveryAction.nextAction ? (
|
||||
<span className="basis-full text-xs text-amber-800 dark:text-amber-200">{entry.recoveryAction.nextAction}</span>
|
||||
<span className="basis-full text-xs text-amber-800 dark:text-amber-200"><ProviderLimitMessage>{entry.recoveryAction.nextAction}</ProviderLimitMessage></span>
|
||||
) : null}
|
||||
{readError && !child ? (
|
||||
<span role="alert" className="flex basis-full items-center gap-2 text-xs text-destructive">
|
||||
|
||||
@@ -17,6 +17,7 @@ import { queryKeys } from "../../lib/queryKeys";
|
||||
import { toolsApi } from "../../api/tools";
|
||||
import { getUIAdapter, buildTranscript, onAdapterChange } from "../../adapters";
|
||||
import { cn } from "../../lib/utils";
|
||||
import { ProviderLimitMessage } from "../ProviderLimitMessage";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { RunTranscriptView, type TranscriptMode } from "../transcript/RunTranscriptView";
|
||||
import { LIVE_TRANSCRIPT_RENDER_LIMIT, MAX_LIVE_EVENTS, MAX_LIVE_LOG_LINES } from "../../lib/live-log-buffer";
|
||||
@@ -563,7 +564,7 @@ export function LogViewer({ run, adapterType }: { run: HeartbeatRun; adapterType
|
||||
{run.error && (
|
||||
<div className="text-xs text-red-600 dark:text-red-200">
|
||||
<span className="text-red-700 dark:text-red-300">Error: </span>
|
||||
{redactPathText(run.error, censorUsernameInLogs)}
|
||||
<ProviderLimitMessage>{redactPathText(run.error, censorUsernameInLogs)}</ProviderLimitMessage>
|
||||
</div>
|
||||
)}
|
||||
{run.stderrExcerpt && run.stderrExcerpt.trim() && (
|
||||
@@ -619,7 +620,7 @@ export function LogViewer({ run, adapterType }: { run: HeartbeatRun; adapterType
|
||||
</span>
|
||||
<span className={cn("break-all", color)}>
|
||||
{evt.message
|
||||
? redactPathText(evt.message, censorUsernameInLogs)
|
||||
? <ProviderLimitMessage>{redactPathText(evt.message, censorUsernameInLogs)}</ProviderLimitMessage>
|
||||
: evt.payload
|
||||
? JSON.stringify(redactPathValue(evt.payload, censorUsernameInLogs))
|
||||
: ""}
|
||||
|
||||
@@ -33,6 +33,25 @@ describe("TaskChatMarker", () => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it.each(["production", "streamlined"] as const)("shows provider reset details in the viewer's timezone in %s mode", (mode) => {
|
||||
const resetAt = new Date(2099, 10, 18, 12, 17, 34, 353);
|
||||
vi.setSystemTime(new Date(resetAt.getTime() - 44 * 60_000));
|
||||
flushSync(() => root!.render(
|
||||
<ThemeProvider>
|
||||
<TaskChatPresentationProvider mode={mode}>
|
||||
<TaskChatMarker item={{ id: "limit", kind: "marker", variant: "interrupted", label: "Waiting for usage limit reset", collapsible: true,
|
||||
detail: `The provider usage limit for this agent is expected to reset at ${resetAt.toISOString()}. Paperclip will start this work then.` }} />
|
||||
</TaskChatPresentationProvider>
|
||||
</ThemeProvider>,
|
||||
));
|
||||
flushSync(() => container.querySelector<HTMLButtonElement>('button[aria-expanded]')!.click());
|
||||
const details = container.querySelector('[data-testid="task-chat-collapsible-marker-details"]');
|
||||
expect(details?.textContent).toContain("in 44 minutes (Nov 18, 2099, 12:17 PM");
|
||||
expect(details?.textContent).not.toContain(resetAt.toISOString());
|
||||
flushSync(() => vi.advanceTimersByTime(60_000));
|
||||
expect(details?.textContent).toContain("in 43 minutes (Nov 18, 2099, 12:17 PM");
|
||||
});
|
||||
|
||||
it.each(["production", "streamlined"] as const)("renders old failure markers without divider rules in %s mode", (mode) => {
|
||||
flushSync(() => root!.render(
|
||||
<ThemeProvider>
|
||||
|
||||
@@ -6,6 +6,7 @@ import type { TaskChatMarkerItem } from "./task-chat-model";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Link } from "@/lib/router";
|
||||
import { timeAgo } from "@/lib/timeAgo";
|
||||
import { useProviderLimitMessage } from "@/hooks/useProviderLimitMessage";
|
||||
|
||||
const VARIANT_ICON = {
|
||||
session_start: CircleDot,
|
||||
@@ -34,6 +35,8 @@ export function TaskChatMarker({
|
||||
const Icon = item.tone === "neutral" ? Square : VARIANT_ICON[item.variant];
|
||||
const interrupted = item.variant === "interrupted" && item.tone !== "neutral";
|
||||
const relative = item.createdAtIso ? timeAgo(item.createdAtIso) : undefined;
|
||||
const label = useProviderLimitMessage(item.label);
|
||||
const detail = useProviderLimitMessage(item.detail ?? "", !item.collapsible || open);
|
||||
const handleTryAgain = () => {
|
||||
void Promise.resolve()
|
||||
.then(() => onTryAgain?.())
|
||||
@@ -83,7 +86,7 @@ export function TaskChatMarker({
|
||||
)}
|
||||
>
|
||||
<Icon className="h-3.5 w-3.5 shrink-0" aria-hidden />
|
||||
<span className="truncate font-medium">{item.label}</span>
|
||||
<span className="truncate font-medium">{label}</span>
|
||||
{relative ? (
|
||||
<span className="shrink-0 text-muted-foreground">
|
||||
· {relative}
|
||||
@@ -116,9 +119,9 @@ export function TaskChatMarker({
|
||||
data-testid="task-chat-collapsible-marker-details"
|
||||
className="mt-1 w-full max-w-(--pct-85) overflow-hidden rounded-lg border border-border bg-muted/25 text-left text-sm dark:bg-muted/15"
|
||||
>
|
||||
{item.detail ? (
|
||||
{detail ? (
|
||||
<div className="px-3 py-2.5 text-foreground/90">
|
||||
{item.detail}
|
||||
{detail}
|
||||
</div>
|
||||
) : null}
|
||||
{item.runHref || item.planHref || onTryAgain ? (
|
||||
@@ -156,7 +159,7 @@ export function TaskChatMarker({
|
||||
<div
|
||||
className="tc-enter-marker flex items-center gap-2 py-1 text-xs text-muted-foreground"
|
||||
role={streamlined && item.variant !== "interrupted" ? "separator" : undefined}
|
||||
aria-label={streamlined && item.variant !== "interrupted" ? item.label : undefined}
|
||||
aria-label={streamlined && item.variant !== "interrupted" ? label : undefined}
|
||||
>
|
||||
{item.variant !== "interrupted" ? <span className="h-px flex-1 bg-border" /> : null}
|
||||
<span
|
||||
@@ -166,9 +169,9 @@ export function TaskChatMarker({
|
||||
)}
|
||||
>
|
||||
<Icon className="h-3.5 w-3.5" />
|
||||
<span className="font-medium">{item.label}</span>
|
||||
{item.detail ? (
|
||||
<span className="text-muted-foreground">· {item.detail}</span>
|
||||
<span className="font-medium">{label}</span>
|
||||
{detail ? (
|
||||
<span className="text-muted-foreground">· {detail}</span>
|
||||
) : null}
|
||||
{onTryAgain ? (
|
||||
<Button
|
||||
|
||||
@@ -21,6 +21,7 @@ describe("TaskChatSystemNotice (PAP-443)", () => {
|
||||
flushSync(() => root?.unmount());
|
||||
root = null;
|
||||
container.remove();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
const recoveryBody =
|
||||
@@ -57,6 +58,19 @@ describe("TaskChatSystemNotice (PAP-443)", () => {
|
||||
)!;
|
||||
}
|
||||
|
||||
it("shows a provider reset in the viewer's timezone when its saved notice is opened", () => {
|
||||
const resetAt = new Date(2099, 10, 18, 12, 17, 34, 353);
|
||||
vi.useFakeTimers();
|
||||
vi.setSystemTime(new Date(resetAt.getTime() - 44 * 60_000));
|
||||
renderNotice({ text: `The provider usage limit for this agent is expected to reset at ${resetAt.toISOString()}. Paperclip will start this work then.` });
|
||||
flushSync(() => toggleButton().click());
|
||||
const details = container.querySelector('[data-testid="task-chat-system-notice-details"]');
|
||||
expect(details?.textContent).toContain("in 44 minutes (Nov 18, 2099, 12:17 PM");
|
||||
expect(details?.textContent).not.toContain(resetAt.toISOString());
|
||||
flushSync(() => vi.advanceTimersByTime(60_000));
|
||||
expect(details?.textContent).toContain("in 43 minutes (Nov 18, 2099, 12:17 PM");
|
||||
});
|
||||
|
||||
it("collapses to a humanized one-liner with relative time and hides the raw body", () => {
|
||||
renderNotice();
|
||||
const button = toggleButton();
|
||||
|
||||
@@ -2,6 +2,7 @@ import { useWorkspaceBaseRefRecovery, useWorkspaceRetry } from "@/components/Wor
|
||||
import { WorkspaceBaseRefRecoveryNotice } from "@/components/WorkspaceBaseRefRecoveryNotice";
|
||||
import { DispositionRecoveryNotice, useDispositionRecoverySnapshot } from "@/components/DispositionRecoveryNotice";
|
||||
import { useId, useState } from "react";
|
||||
import { useProviderLimitMessage } from "@/hooks/useProviderLimitMessage";
|
||||
import {
|
||||
ChevronDown,
|
||||
CircleCheck,
|
||||
@@ -64,8 +65,9 @@ export function TaskChatSystemNotice({
|
||||
const streamlined = useStreamlinedTaskChatPresentation();
|
||||
const [open, setOpen] = useState(Boolean(item.presentation?.detailsDefaultOpen));
|
||||
const detailsId = useId();
|
||||
const body = useProviderLimitMessage(item.text);
|
||||
const { title, tone, detail } = humanizeSystemNotice({
|
||||
body: item.text,
|
||||
body,
|
||||
presentation: item.presentation,
|
||||
});
|
||||
const sections = mapCommentMetadataToSystemNoticeSections(item.metadata, {
|
||||
@@ -146,7 +148,7 @@ export function TaskChatSystemNotice({
|
||||
{showBody ? (
|
||||
<div className="px-3 py-2.5 text-foreground/90">
|
||||
<MarkdownBody softBreaks linkIssueReferences>
|
||||
{item.text}
|
||||
{body}
|
||||
</MarkdownBody>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
import { useMemo } from "react";
|
||||
import { usePageVisibility } from "@/lib/page-visibility";
|
||||
import { formatProviderLimitMessage, providerLimitMessageResetAt } from "@/lib/provider-limit-message";
|
||||
import { useSecondTick } from "./useSecondTick";
|
||||
|
||||
export function useProviderLimitClock(resetAt: number | null, fixedNow?: number, active = true): number {
|
||||
const now = fixedNow ?? Date.now();
|
||||
const { visible } = usePageVisibility();
|
||||
useSecondTick(active && visible && fixedNow === undefined && resetAt !== null && resetAt > now);
|
||||
return now;
|
||||
}
|
||||
|
||||
export function useProviderLimitMessage(message: string, active = true): string {
|
||||
const resetAt = useMemo(() => providerLimitMessageResetAt(message), [message]);
|
||||
const now = useProviderLimitClock(resetAt, undefined, active);
|
||||
return formatProviderLimitMessage(message, now);
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { formatProviderLimitMessage } from "./provider-limit-message";
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
vi.unstubAllEnvs();
|
||||
});
|
||||
|
||||
describe("provider limit messages", () => {
|
||||
const resetAt = "2099-11-18T20:17:34.353Z";
|
||||
const message = `The provider usage limit for this agent is expected to reset at ${resetAt} (no reset time was reported, so Paperclip waits one hour). Paperclip will start this work then.`;
|
||||
|
||||
it.each([
|
||||
{ zone: "America/Los_Angeles", date: "Nov 18, 2099, 12:17 PM PST" },
|
||||
{ zone: "Asia/Kolkata", date: "Nov 19, 2099, 1:47 AM GMT+5:30" },
|
||||
{ zone: "Pacific/Auckland", date: "Nov 19, 2099, 9:17 AM GMT+13" },
|
||||
])("uses the viewer's current timezone: $zone", ({ zone, date }) => {
|
||||
vi.stubEnv("TZ", zone);
|
||||
vi.useFakeTimers();
|
||||
vi.setSystemTime(new Date("2099-11-18T19:33:34.353Z"));
|
||||
expect(formatProviderLimitMessage(message)).toBe(`The provider usage limit for this agent is expected to reset in 44 minutes (${date}) (no reset time was reported, so Paperclip waits one hour). Paperclip will start this work then.`);
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ now: "2099-11-18T19:17:34.353Z", relative: "in 1 hour" },
|
||||
{ now: "2099-11-18T18:17:34.353Z", relative: "in 2 hours" },
|
||||
{ now: "2099-11-18T20:17:33.353Z", relative: "in 1 second" },
|
||||
{ now: "2099-11-18T20:22:34.353Z", relative: "5 minutes ago" },
|
||||
])("computes relative time when viewed: $relative", ({ now, relative }) => {
|
||||
vi.useFakeTimers();
|
||||
vi.setSystemTime(new Date(now));
|
||||
expect(formatProviderLimitMessage(message)).toContain(`reset ${relative} (`);
|
||||
});
|
||||
|
||||
it("formats lifecycle events and scheduled retry actions", () => {
|
||||
vi.useFakeTimers();
|
||||
vi.setSystemTime(new Date("2099-11-18T19:17:34.353Z"));
|
||||
for (const text of [
|
||||
`Waiting for the provider usage limit to reset at ${resetAt} before starting work`,
|
||||
`The provider usage limit resets at ${resetAt}; this wake could not schedule its retry and released the task`,
|
||||
`Waiting for the agent's provider usage limit to reset; the work starts at ${resetAt}.`,
|
||||
]) {
|
||||
expect(formatProviderLimitMessage(text)).toContain("in 1 hour (");
|
||||
expect(formatProviderLimitMessage(text)).not.toContain(resetAt);
|
||||
}
|
||||
});
|
||||
|
||||
it("uses daylight saving time at the reset date", () => {
|
||||
vi.stubEnv("TZ", "America/Los_Angeles");
|
||||
vi.useFakeTimers();
|
||||
vi.setSystemTime(new Date("2099-07-18T19:33:00Z"));
|
||||
expect(formatProviderLimitMessage("The provider usage limit resets at 2099-07-18T20:17:00Z."))
|
||||
.toBe("The provider usage limit resets in 44 minutes (Jul 18, 2099, 1:17 PM PDT).");
|
||||
});
|
||||
|
||||
it("leaves unrelated messages and invalid reset timestamps intact", () => {
|
||||
for (const text of [
|
||||
`The task starts at ${resetAt}.`,
|
||||
`The provider usage limit was observed at ${resetAt}.`,
|
||||
"The provider usage limit resets at an unknown time.",
|
||||
"The provider usage limit resets at 2099-99-99T99:99:99.999Z.",
|
||||
"",
|
||||
]) expect(formatProviderLimitMessage(text)).toBe(text);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,38 @@
|
||||
import { formatDateTime } from "./utils";
|
||||
|
||||
const relativeTimeFormatter = new Intl.RelativeTimeFormat("en-US", { numeric: "always" });
|
||||
const relativeUnits = [
|
||||
[86_400_000, "day"], [3_600_000, "hour"], [60_000, "minute"], [1000, "second"],
|
||||
] as const;
|
||||
const resetTimestampPattern = /\b(resets?|starts) at (\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?Z)\b/g;
|
||||
|
||||
export function providerLimitMessageResetAt(message: string): number | null {
|
||||
if (!message.includes("provider usage limit")) return null;
|
||||
let latest: number | null = null;
|
||||
for (const match of message.matchAll(resetTimestampPattern)) {
|
||||
const resetAt = Date.parse(match[2]);
|
||||
if (Number.isFinite(resetAt)) latest = Math.max(latest ?? resetAt, resetAt);
|
||||
}
|
||||
return latest;
|
||||
}
|
||||
|
||||
export function formatProviderLimitTime(timestamp: string, now = Date.now()): string {
|
||||
const at = new Date(timestamp);
|
||||
const remainingMs = at.getTime() - now;
|
||||
if (!Number.isFinite(remainingMs)) return timestamp;
|
||||
const [unitMs, unit] = relativeUnits.find(([size]) => Math.abs(remainingMs) >= size) ?? relativeUnits[3];
|
||||
const amount = Math.round(remainingMs / unitMs);
|
||||
const relative = amount === 0 ? "now" : relativeTimeFormatter.format(amount, unit);
|
||||
return `${relative} (${formatDateTime(at, { includeTimeZone: true })})`;
|
||||
}
|
||||
|
||||
export function formatProviderLimitMessage(message: string, now = Date.now()): string {
|
||||
if (!message.includes("provider usage limit")) return message;
|
||||
return message.replace(
|
||||
resetTimestampPattern,
|
||||
(match: string, verb: string, timestamp: string) => {
|
||||
if (!Number.isFinite(Date.parse(timestamp))) return match;
|
||||
return `${verb} ${formatProviderLimitTime(timestamp, now)}`;
|
||||
},
|
||||
);
|
||||
}
|
||||
+2
-1
@@ -53,7 +53,7 @@ export function formatDate(date: Date | string): string {
|
||||
|
||||
export function formatDateTime(
|
||||
date: Date | string,
|
||||
options: { includeSeconds?: boolean; includeYear?: boolean } = {},
|
||||
options: { includeSeconds?: boolean; includeYear?: boolean; includeTimeZone?: boolean } = {},
|
||||
): string {
|
||||
return new Date(date).toLocaleString("en-US", {
|
||||
month: "short",
|
||||
@@ -62,6 +62,7 @@ export function formatDateTime(
|
||||
hour: "numeric",
|
||||
minute: "2-digit",
|
||||
...(options.includeSeconds ? { second: "2-digit" as const } : {}),
|
||||
...(options.includeTimeZone ? { timeZoneName: "short" as const } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -65,6 +65,7 @@ import { SourceResolvedFoldBadge } from "../components/SourceResolvedFoldBadge";
|
||||
import { readSourceResolvedWatchdogFold } from "../lib/source-resolved-watchdog-fold";
|
||||
import { formatCents, formatDate, relativeTime, formatTokens, visibleRunCostUsd, visibleRunTokenTotal } from "../lib/utils";
|
||||
import { cn } from "../lib/utils";
|
||||
import { ProviderLimitMessage } from "../components/ProviderLimitMessage";
|
||||
import { describeRunRetryState } from "../lib/runRetryState";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
@@ -3040,7 +3041,7 @@ function RunDetail({ run: initialRun, agentRouteId, adapterType, adapterConfig }
|
||||
)}
|
||||
{run.error && (
|
||||
<div className="text-xs">
|
||||
<span className="text-red-600 dark:text-red-400">{run.error}</span>
|
||||
<span className="text-red-600 dark:text-red-400"><ProviderLimitMessage>{run.error}</ProviderLimitMessage></span>
|
||||
{run.errorCode && <span className="text-muted-foreground ml-1">({run.errorCode})</span>}
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -73,6 +73,7 @@ import { SourceResolvedFoldBadge } from "../components/SourceResolvedFoldBadge";
|
||||
import { readSourceResolvedWatchdogFold } from "../lib/source-resolved-watchdog-fold";
|
||||
import { formatCents, formatDate, relativeTime, formatTokens, visibleRunCostUsd, visibleRunTokenTotal, hasUnavailableProviderAccounting, supportsRawProviderTrace } from "../lib/utils";
|
||||
import { cn } from "../lib/utils";
|
||||
import { ProviderLimitMessage } from "../components/ProviderLimitMessage";
|
||||
import { RunRetryDetails } from "../components/RunRetryDetails";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Tabs } from "@/components/ui/tabs";
|
||||
@@ -3365,7 +3366,7 @@ function RunDetail({ run: initialRun, agentRouteId, adapterType, adapterConfig }
|
||||
<ProviderFailureNotice failure={readProviderFailure(run.resultJson?.providerFailure)!} />
|
||||
) : run.error && (
|
||||
<div className="text-xs">
|
||||
<span className="text-red-600 dark:text-red-400">{run.error}</span>
|
||||
<span className="text-red-600 dark:text-red-400"><ProviderLimitMessage>{run.error}</ProviderLimitMessage></span>
|
||||
{run.errorCode && <span className="text-muted-foreground ml-1">({run.errorCode})</span>}
|
||||
</div>
|
||||
)}
|
||||
|
||||
Reference in new issue
Block a user