diff --git a/ui/src/components/AgentRateLimitGauge.test.tsx b/ui/src/components/AgentRateLimitGauge.test.tsx new file mode 100644 index 00000000000..8ec89dadc13 --- /dev/null +++ b/ui/src/components/AgentRateLimitGauge.test.tsx @@ -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 }) =>
{children}
, +})); +vi.mock("@/lib/router", () => ({ Link: ({ to, children }: { to: string; children: ReactNode }) => {children} })); + +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()); + 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()); + 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()); + expect(vi.getTimerCount()).toBe(0); + flushSync(() => vi.advanceTimersByTime(60 * 60_000)); + expect(container.textContent).toContain("in 44 minutes ("); + }); +}); diff --git a/ui/src/components/AgentRateLimitGauge.tsx b/ui/src/components/AgentRateLimitGauge.tsx index 4bddb2de2a5..b8c6c195a59 100644 --- a/ui/src/components/AgentRateLimitGauge.tsx +++ b/ui/src/components/AgentRateLimitGauge.tsx @@ -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 = { 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 }: { {window.label} {Math.round(pct)}% - {window.resetsAt && ( - · resets {formatRateLimitClock(window.resetsAt, now)} - )} + {window.resetsAt &&
Resets {formatProviderLimitTime(window.resetsAt, now)}
} ); @@ -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 ( @@ -118,6 +114,7 @@ export function AgentRateLimitPropertyValue({ snapshot, now = Date.now(), defaul className, )} aria-label={`Provider usage limit: ${label}`} + title={label} > {summary.limited ? @@ -129,9 +126,9 @@ export function AgentRateLimitPropertyValue({ snapshot, now = Date.now(), defaul
{snapshot.provider === "openai" ? "Codex" : "Claude"} usage limits
-
- Reported {formatRateLimitClock(snapshot.observedAt, now)} - {detailsHref && View agent} +
+ Reported {formatDateTime(snapshot.observedAt, { includeTimeZone: true })} + {detailsHref && View agent}
diff --git a/ui/src/components/IssueRecoveryActionCard.tsx b/ui/src/components/IssueRecoveryActionCard.tsx index e02af9c234d..b8833fb349c 100644 --- a/ui/src/components/IssueRecoveryActionCard.tsx +++ b/ui/src/components/IssueRecoveryActionCard.tsx @@ -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({ )} - {action.nextAction ? {action.nextAction} : } + {action.nextAction ? {action.nextAction} : } diff --git a/ui/src/components/IssueRunLedger.tsx b/ui/src/components/IssueRunLedger.tsx index aa8e465449b..2388921d754 100644 --- a/ui/src/components/IssueRunLedger.tsx +++ b/ui/src/components/IssueRunLedger.tsx @@ -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:{" "} - {nextAction} + {nextAction}
) : null} diff --git a/ui/src/components/ProviderLimitMessage.test.tsx b/ui/src/components/ProviderLimitMessage.test.tsx new file mode 100644 index 00000000000..a8ffae73c96 --- /dev/null +++ b/ui/src/components/ProviderLimitMessage.test.tsx @@ -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 {message}; + } + flushSync(() => root.render()); + 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(<>{message}{message})); + 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({message})); + 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({message})); + 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({text})); + expect(vi.getTimerCount()).toBe(0); + } + }); +}); diff --git a/ui/src/components/ProviderLimitMessage.tsx b/ui/src/components/ProviderLimitMessage.tsx new file mode 100644 index 00000000000..c6a0e5d6022 --- /dev/null +++ b/ui/src/components/ProviderLimitMessage.tsx @@ -0,0 +1,5 @@ +import { useProviderLimitMessage } from "@/hooks/useProviderLimitMessage"; + +export function ProviderLimitMessage({ children }: { children: string }) { + return useProviderLimitMessage(children); +} diff --git a/ui/src/components/StalledDependencyNotice.tsx b/ui/src/components/StalledDependencyNotice.tsx index 26ee0484c65..97d0a2137cc 100644 --- a/ui/src/components/StalledDependencyNotice.tsx +++ b/ui/src/components/StalledDependencyNotice.tsx @@ -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 }: {entry.stalledIssueTitle} {entry.recoveryAction.nextAction ? ( - {entry.recoveryAction.nextAction} + {entry.recoveryAction.nextAction} ) : null} {readError && !child ? ( diff --git a/ui/src/components/run-log/LogViewer.tsx b/ui/src/components/run-log/LogViewer.tsx index 45a3b8e1b11..fdde87dedfe 100644 --- a/ui/src/components/run-log/LogViewer.tsx +++ b/ui/src/components/run-log/LogViewer.tsx @@ -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 && (
Error: - {redactPathText(run.error, censorUsernameInLogs)} + {redactPathText(run.error, censorUsernameInLogs)}
)} {run.stderrExcerpt && run.stderrExcerpt.trim() && ( @@ -619,7 +620,7 @@ export function LogViewer({ run, adapterType }: { run: HeartbeatRun; adapterType
{evt.message - ? redactPathText(evt.message, censorUsernameInLogs) + ? {redactPathText(evt.message, censorUsernameInLogs)} : evt.payload ? JSON.stringify(redactPathValue(evt.payload, censorUsernameInLogs)) : ""} diff --git a/ui/src/components/task-chat/TaskChatMarker.test.tsx b/ui/src/components/task-chat/TaskChatMarker.test.tsx index 73d0adfba1d..61609d7e086 100644 --- a/ui/src/components/task-chat/TaskChatMarker.test.tsx +++ b/ui/src/components/task-chat/TaskChatMarker.test.tsx @@ -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( + + + + + , + )); + flushSync(() => container.querySelector('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( diff --git a/ui/src/components/task-chat/TaskChatMarker.tsx b/ui/src/components/task-chat/TaskChatMarker.tsx index 4fbf83a6a37..fc264fa5bc0 100644 --- a/ui/src/components/task-chat/TaskChatMarker.tsx +++ b/ui/src/components/task-chat/TaskChatMarker.tsx @@ -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({ )} > - {item.label} + {label} {relative ? ( · {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 ? (
- {item.detail} + {detail}
) : null} {item.runHref || item.planHref || onTryAgain ? ( @@ -156,7 +159,7 @@ export function TaskChatMarker({
{item.variant !== "interrupted" ? : null} - {item.label} - {item.detail ? ( - · {item.detail} + {label} + {detail ? ( + · {detail} ) : null} {onTryAgain ? (