TypeScript
fix(chat): show one usage-limit recovery notice (#29292)
shivamc7537d026492
diff --git a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx b/apps/mobile/src/features/threads/ThreadDetailScreen.tsxindex 4841c5f76dc..f8d2e3b5c76 100644--- a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx+++ b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx@@ -62,6 +62,7 @@ import {BACKGROUND_WORK_STOP_RETRY_AFTER_MS,type BackgroundWorkStopRequest,isBackgroundWorkStopPending,+ limitRecoveryOwnsSnooze,presentPendingBackgroundWork,presentProviderGoal,} from "@t3tools/client-runtime/state/thread-execution";@@ -642,6 +643,19 @@ function ThreadDetailBody(return () => clearTimeout(timer);// oxlint-disable-next-line react/exhaustive-effect-dependencies -- Re-arm if timer clamping fires before the wake time.}, [snoozed, snoozedUntil, lifecycleNow]);+ // The usage-limit recovery card shows this snooze and its Wake now.+ const lifecycleSnoozed =+ snoozed &&+ !limitRecoveryOwnsSnooze({+ runId:+ props.selectedThread.runtime?.status === "failed" &&+ props.selectedThread.runtime.lastErrorClass === "usage_limit"+ ? props.selectedThread.latestRun?.runId+ : null,+ resetAt: props.selectedThread.runtime?.usageLimitResetAt,+ recovery: props.selectedThread.limitRecovery,+ snoozedUntil,+ });const settled = configLoaded && props.selectedThread.settledOverride === "settled";const wokeAt = configLoaded ? threadWokeAt(props.selectedThread, { now: lifecycleNow }) : null;const woke = isThreadWokeUnseen({@@ -809,22 +823,22 @@ function ThreadDetailBody(},};}- if (contentPresentationKind === "ready" && (snoozed || settled || woke)) {- const state = snoozed ? "snoozed" : settled ? "settled" : "woke";+ if (contentPresentationKind === "ready" && (lifecycleSnoozed || settled || woke)) {+ const state = lifecycleSnoozed ? "snoozed" : settled ? "settled" : "woke";const label =- snoozed && snoozedUntil !== null+ lifecycleSnoozed && snoozedUntil !== null? `Snoozed, wakes in ${snoozeWakeLabel(snoozedUntil, { now: lifecycleNow })}`: settled? "Settled": "Woke from snooze";- const actionLabel = snoozed ? "Wake now" : settled ? "Un-settle" : "Dismiss";+ const actionLabel = lifecycleSnoozed ? "Wake now" : settled ? "Un-settle" : "Dismiss";return {kind: "lifecycle",state,label,action: {label: statusPending- ? snoozed+ ? lifecycleSnoozed? "Waking...": settled? "Un-settling..."@@ -832,7 +846,8 @@ function ThreadDetailBody(: actionLabel,accessibilityLabel: actionLabel,disabled: !props.canOperateThread || statusPending,- onPress: () => void runStatusAction(snoozed ? "wake" : settled ? "unsettle" : "dismiss"),+ onPress: () =>+ void runStatusAction(lifecycleSnoozed ? "wake" : settled ? "unsettle" : "dismiss"),},};}diff --git a/apps/mobile/src/features/threads/UsageLimitRecoveryCard.tsx b/apps/mobile/src/features/threads/UsageLimitRecoveryCard.tsxindex 27fece0272b..201fc78234f 100644--- a/apps/mobile/src/features/threads/UsageLimitRecoveryCard.tsx+++ b/apps/mobile/src/features/threads/UsageLimitRecoveryCard.tsx@@ -1,7 +1,7 @@-import { Button } from "../../components/ui/Button";import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";import { AsyncResult } from "effect/reactivity";import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";+import { limitRecoveryOwnsSnooze } from "@t3tools/client-runtime/state/thread-execution";import type { EnvironmentId } from "@t3tools/contracts";import {CHATGPT_USAGE_LIMIT_CODE,@@ -9,7 +9,6 @@ import {CHATGPT_WORKSPACE_ADMIN_REQUEST,CHATGPT_WORKSPACE_USAGE_LIMIT_CODE,} from "@t3tools/shared/usageLimits";-import * as DateTime from "effect/DateTime";import * as Clipboard from "expo-clipboard";import { useState } from "react";import { Linking, Pressable, View } from "react-native";@@ -31,6 +30,7 @@ export function UsageLimitRecoveryCard({const [error, setError] = useState<string | null>(null);const resetAt = thread.runtime?.usageLimitResetAt ?? null;const canSchedule =+ thread.settledOverride !== "settled" &&resetAt !== null &&Date.parse(resetAt) > Date.parse(thread.latestRun?.completedAt ?? thread.updatedAt);const resetPassed = useDeadlinePassed(resetAt === null ? null : Date.parse(resetAt));@@ -38,6 +38,14 @@ export function UsageLimitRecoveryCard({const recovery = thread.limitRecovery;const scheduled =recovery?.runId === runId && recovery?.resetAt === resetAt && recovery?.autoResume;+ const displayAt =+ canSchedule &&+ scheduled &&+ resetAt &&+ thread.snoozedUntil &&+ Date.parse(thread.snoozedUntil) > Date.parse(resetAt)+ ? thread.snoozedUntil+ : resetAt;const [copied, setCopied] = useState(false);const [actionPending, setActionPending] = useState(false);const code = thread.runtime?.lastErrorCode;@@ -51,16 +59,19 @@ export function UsageLimitRecoveryCard({!runId)return null;- const resetText = resetAt- ? `Usage limit resets ${DateTime.toDateUtc(DateTime.makeUnsafe(resetAt)).toLocaleString()}.`+ const resetText = displayAt+ ? `${canSchedule && scheduled ? "Resumes" : "Resets"} ${new Date(displayAt).toLocaleString(+ undefined,+ { month: "short", day: "numeric", hour: "numeric", minute: "2-digit" },+ )}.`: null;const snoozed =- recovery?.snooze === true &&- recovery.runId === runId &&- recovery.resetAt === resetAt &&- resetAt !== null &&- thread.snoozedUntil !== null &&- Date.parse(thread.snoozedUntil) === Date.parse(resetAt);+ limitRecoveryOwnsSnooze({+ runId,+ resetAt,+ recovery,+ snoozedUntil: thread.snoozedUntil,+ }) && !resetPassed;async function toggle(action: "resume" | "snooze") {if (!resetAt || !runId || !canSchedule) return;if (action === "snooze" && !snoozed && Date.parse(resetAt) <= Date.now()) {@@ -123,50 +134,52 @@ export function UsageLimitRecoveryCard({<ProviderIcon provider="codex" size={16} /></View>) : null}- <View className="min-w-0 flex-1 gap-2">+ <View className="min-w-0 flex-1 gap-1">{chatGptLimit ? (- <View className="gap-1">- <Text className="text-sm font-t3-medium text-foreground">- ChatGPT usage limit reached- </Text>- <Text className="text-sm text-foreground-muted">- {workspaceLimit- ? copied- ? "Request copied. Send it to your workspace admin."- : "You've reached your workspace's limit for using your ChatGPT plan in other apps. Copy a request to ask your workspace admin for increased usage limits."- : (resetText ?? "Review your usage settings in ChatGPT.")}- </Text>- <Pressable- accessibilityRole={action.role}- accessibilityState={{ disabled: actionPending }}- disabled={actionPending}- hitSlop={14}- className="mt-1 self-start active:opacity-70"- onPress={action.run}- >- <Text className="text-sm font-t3-medium text-primary">{action.label}</Text>- </Pressable>- </View>- ) : (- <Text className="text-sm text-warning-foreground">- {resetText ??- "The provider did not report a reset time. Retry manually when your limit is available."}+ <Text className="text-sm font-t3-medium text-foreground">+ ChatGPT usage limit reached</Text>- )}- {canSchedule ? (- <View className="flex-row flex-wrap gap-2">- <Button- label={scheduled ? "Cancel auto-resume" : "Resume at reset"}- tone="secondary"- disabled={pending}- onPress={() => void toggle("resume")}- />- <Button- label={snoozed ? "Wake now" : "Snooze until reset"}- tone="secondary"- disabled={pending || (!snoozed && resetPassed)}- onPress={() => void toggle("snooze")}- />+ ) : null}+ <Text+ className={+ chatGptLimit ? "text-sm text-foreground-muted" : "text-sm text-warning-foreground"+ }+ >+ {workspaceLimit+ ? copied+ ? "Request copied. Send it to your workspace admin."+ : "You've reached your workspace's limit for using your ChatGPT plan in other apps. Copy a request to ask your workspace admin for increased usage limits."+ : chatGptLimit+ ? (resetText ?? "Review your usage settings in ChatGPT.")+ : resetText+ ? `Usage limit reached. ${resetText}`+ : "Usage limit reached. The provider did not report a reset time. Retry manually when your limit is available."}+ </Text>+ {chatGptLimit || canSchedule ? (+ // The margins cancel the 44pt touch height so the links sit 8pt under the text.+ <View className="-mb-3 -mt-2 flex-row flex-wrap gap-x-4">+ {chatGptLimit ? (+ <RecoveryAction+ label={action.label}+ role={action.role}+ disabled={actionPending}+ onPress={action.run}+ />+ ) : null}+ {canSchedule ? (+ <>+ <RecoveryAction+ label={scheduled ? "Cancel auto-resume" : "Resume at reset"}+ disabled={pending}+ onPress={() => void toggle("resume")}+ />+ <RecoveryAction+ label={snoozed ? "Wake now" : "Snooze until reset"}+ disabled={pending || (!snoozed && resetPassed)}+ onPress={() => void toggle("snooze")}+ />+ </>+ ) : null}</View>) : null}{error ? (@@ -178,3 +191,31 @@ export function UsageLimitRecoveryCard({</View>);}++function RecoveryAction(props: {+ readonly label: string;+ readonly role?: "button" | "link";+ readonly disabled: boolean;+ readonly onPress: () => void;+}) {+ return (+ <Pressable+ accessibilityRole={props.role ?? "button"}+ accessibilityState={{ disabled: props.disabled }}+ disabled={props.disabled}+ hitSlop={{ left: 8, right: 8 }}+ onPress={props.onPress}+ className="min-h-11 justify-center active:opacity-70"+ >+ <Text+ className={+ props.disabled+ ? "text-sm font-t3-medium text-foreground-muted"+ : "text-sm font-t3-medium text-primary"+ }+ >+ {props.label}+ </Text>+ </Pressable>+ );+}diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsxindex 8e418324448..d49030e6f88 100644--- a/apps/web/src/components/ChatView.tsx+++ b/apps/web/src/components/ChatView.tsx@@ -82,6 +82,7 @@ import {deriveThreadActivityRun,deriveLatestThreadRun,deriveThreadStructureRuntime,+ limitRecoveryOwnsSnooze,} from "@t3tools/client-runtime/state/thread-execution";import {resolveWorkflowOpening,@@ -983,11 +984,19 @@ export default function ChatView(props: ChatViewProps) {);const browserAvailable = isPreviewSupportedInRuntime() || activeEnvironmentServerBrowser;const activeThreadShell = serverThread;+ const limitRecoveryRun =+ serverRuntime?.status === "failed" && serverRuntime.lastErrorClass === "usage_limit"+ ? (activeThreadShell?.latestRun ?? null)+ : null;+ // The recovery banner offers Wake now for a snooze it set.+ const limitRecoveryHoldsSnooze = limitRecoveryOwnsSnooze({+ runId: limitRecoveryRun?.runId,+ resetAt: serverRuntime?.usageLimitResetAt,+ recovery: activeThreadShell?.limitRecovery,+ snoozedUntil: activeThreadShell?.snoozedUntil,+ });const timelineThreadError =- serverRuntime?.status === "failed" &&- serverRuntime.lastErrorClass === "usage_limit" &&- activeThreadShell?.latestRun &&- visibleThreadError === serverRuntime.lastError+ limitRecoveryRun !== null && visibleThreadError === serverRuntime?.lastError? null: visibleThreadError;@@ -2414,6 +2423,7 @@ export default function ChatView(props: ChatViewProps) {activeThreadKey,activeThreadShell,activeLatestRun,+ limitRecoveryHoldsSnooze,activeProjectCwd,serverConfig,runtimeMode,@@ -2542,14 +2552,14 @@ export default function ChatView(props: ChatViewProps) {return item ? [item] : [];});const limitRecoveryBanner =- serverRuntime?.status === "failed" &&- serverRuntime.lastErrorClass === "usage_limit" &&- activeThreadShell?.latestRun+ limitRecoveryRun !== null && activeThreadShell !== null? usageLimitRecoveryBannerItem({- runId: activeThreadShell.latestRun.runId,- errorCode: serverRuntime.lastErrorCode ?? null,- resetAt: serverRuntime.usageLimitResetAt ?? null,- stoppedAt: activeThreadShell.latestRun.completedAt ?? activeThreadShell.updatedAt,+ runId: limitRecoveryRun.runId,+ errorCode: serverRuntime?.lastErrorCode ?? null,+ resetAt: serverRuntime?.usageLimitResetAt ?? null,+ stoppedAt: limitRecoveryRun.completedAt ?? activeThreadShell.updatedAt,+ settled: activeThreadShell.settledOverride === "settled",+ requestPending: pendingApprovals.length > 0 || pendingUserInputs.length > 0,recovery: activeThreadShell.limitRecovery ?? null,snoozedUntil: activeThreadShell.snoozedUntil,timestampFormat,diff --git a/apps/web/src/components/chat/UsageLimitRecoveryBanner.test.tsx b/apps/web/src/components/chat/UsageLimitRecoveryBanner.test.tsxindex a4b534d66d1..84b71be9b62 100644--- a/apps/web/src/components/chat/UsageLimitRecoveryBanner.test.tsx+++ b/apps/web/src/components/chat/UsageLimitRecoveryBanner.test.tsx@@ -12,6 +12,8 @@ function bannerDescription(resetAt: Date, timestampFormat: TimestampFormat) {errorCode: null,resetAt: resetAt.toISOString(),stoppedAt: stoppedAt.toISOString(),+ settled: false,+ requestPending: false,snoozedUntil: null,recovery: null,timestampFormat,diff --git a/apps/web/src/components/chat/UsageLimitRecoveryBanner.tsx b/apps/web/src/components/chat/UsageLimitRecoveryBanner.tsxindex aabe7734a33..744db5ea3a1 100644--- a/apps/web/src/components/chat/UsageLimitRecoveryBanner.tsx+++ b/apps/web/src/components/chat/UsageLimitRecoveryBanner.tsx@@ -5,6 +5,7 @@ import {} from "@t3tools/contracts";import { type TimestampFormat } from "@t3tools/contracts/settings";import { deadlineStore } from "@t3tools/client-runtime/clock";+import { limitRecoveryOwnsSnooze } from "@t3tools/client-runtime/state/thread-execution";import {CHATGPT_USAGE_LIMIT_CODE,CHATGPT_WORKSPACE_USAGE_LIMIT_CODE,@@ -14,7 +15,7 @@ import { useState } from "react";import { useDeadlinePassed } from "../../hooks/useDeadline";import { OpenAI } from "../Icons";import { ChatGptUsageButton } from "../settings/ChatGptUsageButton";-import { Button } from "../ui/button";+import { Button, InlineButton } from "../ui/button";import { formatUpcomingTimestamp } from "../../timestampFormat";import { toastManager } from "../ui/toast";import type { ComposerBannerStackItem } from "./ComposerBannerStack";@@ -25,6 +26,8 @@ type RecoveryProps = {errorCode: string | null;resetAt: string | null;stoppedAt: string;+ settled: boolean;+ requestPending: boolean;snoozedUntil: string | null;recovery: OrchestrationV2LimitRecovery | null;timestampFormat: TimestampFormat;@@ -32,20 +35,39 @@ type RecoveryProps = {};export function usageLimitRecoveryBannerItem(props: RecoveryProps): ComposerBannerStackItem {- const { runId, errorCode, resetAt, stoppedAt, timestampFormat } = props;- const canSchedule = resetAt !== null && Date.parse(resetAt) > Date.parse(stoppedAt);+ const {+ runId,+ errorCode,+ resetAt,+ stoppedAt,+ settled,+ requestPending,+ recovery,+ snoozedUntil,+ timestampFormat,+ } = props;+ // The server refuses recovery changes while a request is pending.+ const canSchedule =+ !settled && !requestPending && resetAt !== null && Date.parse(resetAt) > Date.parse(stoppedAt);+ const resumes =+ canSchedule && recovery?.runId === runId && recovery.resetAt === resetAt && recovery.autoResume;const workspaceLimit = errorCode === CHATGPT_WORKSPACE_USAGE_LIMIT_CODE;const chatGptLimit = workspaceLimit || errorCode === CHATGPT_USAGE_LIMIT_CODE;const recoveryActions = canSchedule ? (<RecoveryActions key={`${runId}:${resetAt}`} {...props} />) : null;- const resetDescription = resetAt- ? `Resets ${formatUpcomingTimestamp(resetAt, timestampFormat)}`+ const displayAt =+ resumes && resetAt && snoozedUntil && Date.parse(snoozedUntil) > Date.parse(resetAt)+ ? snoozedUntil+ : resetAt;+ const resetDescription = displayAt+ ? `${resumes ? "Resumes" : "Resets"} ${formatUpcomingTimestamp(displayAt, timestampFormat)}`: "Reset time unavailable; retry manually";if (!chatGptLimit) {return {id: `usage-limit-recovery:${runId}`,variant: "warning",+ group: "environment",icon: <GaugeIcon />,title: "Usage limit reached",description: resetDescription,@@ -56,6 +78,7 @@ export function usageLimitRecoveryBannerItem(props: RecoveryProps): ComposerBannreturn {id: `usage-limit-recovery:${runId}`,variant: "warning",+ group: "environment",icon: <OpenAI aria-hidden="true" />,title: "ChatGPT usage limit reached",description: workspaceLimit@@ -85,13 +108,7 @@ function RecoveryActions({ runId, resetAt, recovery, snoozedUntil, onChange }: R// so a snooze whose reset has passed is no longer active.const resetPassed = useDeadlinePassed(resetAt === null ? null : Date.parse(resetAt));const snoozed =- recovery?.snooze === true &&- recovery.runId === runId &&- recovery.resetAt === resetAt &&- resetAt !== null &&- snoozedUntil !== null &&- Date.parse(snoozedUntil) === Date.parse(resetAt) &&- !resetPassed;+ limitRecoveryOwnsSnooze({ runId, resetAt, recovery, snoozedUntil }) && !resetPassed;async function toggle(action: "resume" | "snooze") {if (resetAt === null) return;if (action === "snooze" && !snoozed && Date.parse(resetAt) <= Date.now()) {@@ -122,18 +139,17 @@ function RecoveryActions({ runId, resetAt, recovery, snoozedUntil, onChange }: R}// Inline errors would widen the actions column and crush the title.return (- <>- <Button size="xs" variant="ghost" disabled={pending} onClick={() => void toggle("resume")}>+ <span className="flex flex-wrap items-center gap-x-3 gap-y-1 px-1">+ <InlineButton touchTarget="padded" disabled={pending} onClick={() => void toggle("resume")}>{pending ? "Saving..." : scheduled ? "Cancel auto-resume" : "Resume at reset"}- </Button>- <Button- size="xs"- variant="ghost"+ </InlineButton>+ <InlineButton+ touchTarget="padded"disabled={pending || (!snoozed && resetPassed)}onClick={() => void toggle("snooze")}>{pending ? "Saving..." : snoozed ? "Wake now" : "Snooze until reset"}- </Button>- </>+ </InlineButton>+ </span>);}diff --git a/apps/web/src/components/chat/useThreadLifecycle.browser.test.tsx b/apps/web/src/components/chat/useThreadLifecycle.browser.test.tsxindex 76f9434eedf..a60d7f24b18 100644--- a/apps/web/src/components/chat/useThreadLifecycle.browser.test.tsx+++ b/apps/web/src/components/chat/useThreadLifecycle.browser.test.tsx@@ -111,6 +111,7 @@ function RestoreBranchHarness(props: {canOperateThread: true,clientSettingsHydrated: true,activeThreadShell: null,+ limitRecoveryHoldsSnooze: false,activeLatestRun: null as never,activeProjectCwd: "/repo",serverConfig: null,diff --git a/apps/web/src/components/chat/useThreadLifecycle.tsx b/apps/web/src/components/chat/useThreadLifecycle.tsxindex b9f8a42d289..50ed46ae671 100644--- a/apps/web/src/components/chat/useThreadLifecycle.tsx+++ b/apps/web/src/components/chat/useThreadLifecycle.tsx@@ -98,6 +98,8 @@ interface ThreadLifecycleInput {readonly threadDetailRef: ScopedThreadRef | null;readonly activeThreadKey: string | null;readonly activeThreadShell: EnvironmentThreadShell | null;+ /** The usage-limit recovery banner shows this snooze and its Wake now. */+ readonly limitRecoveryHoldsSnooze: boolean;readonly activeLatestRun: EnvironmentThreadShell["latestRun"];readonly activeProjectCwd: string | null;readonly serverConfig: EnvironmentServerConfig | null;@@ -150,6 +152,7 @@ export function useThreadLifecycle(input: ThreadLifecycleInput) {activeThreadKey,activeThreadShell,activeLatestRun,+ limitRecoveryHoldsSnooze,activeProjectCwd,serverConfig,runtimeMode,@@ -610,14 +613,16 @@ export function useThreadLifecycle(input: ThreadLifecycleInput) {? snoozeWakeLabel(snoozedUntil, { now: `${nowMinute}:00.000Z` }): null;const threadStatusLine = activeThreadSnoozed ? (- <ThreadStatusLine- icon={<AlarmClockIcon />}- label={snoozeWake && snoozeWake !== "now" ? `Snoozed, ${snoozeWake} left` : "Snoozed"}- clockMinute={nowMinute}- actionLabel={isUnsnoozing ? "Waking..." : "Wake now"}- actionDisabled={!canOperateThread || isUnsnoozing}- onAction={() => void handleUnsnoozeActiveThreadStable()}- />+ limitRecoveryHoldsSnooze ? null : (+ <ThreadStatusLine+ icon={<AlarmClockIcon />}+ label={snoozeWake && snoozeWake !== "now" ? `Snoozed, ${snoozeWake} left` : "Snoozed"}+ clockMinute={nowMinute}+ actionLabel={isUnsnoozing ? "Waking..." : "Wake now"}+ actionDisabled={!canOperateThread || isUnsnoozing}+ onAction={() => void handleUnsnoozeActiveThreadStable()}+ />+ )) : activeThreadSettled ? (<ThreadStatusLineicon={<CheckCircle2Icon />}diff --git a/apps/web/src/components/ui/button.tsx b/apps/web/src/components/ui/button.tsxindex 5b36a5ae5eb..0830513e5be 100644--- a/apps/web/src/components/ui/button.tsx+++ b/apps/web/src/components/ui/button.tsx@@ -105,6 +105,9 @@ const inlineButtonVariants = cva({defaultVariants: { tone: "default" },variants: {+ touchTarget: {+ padded: "pointer-coarse:min-h-11 pointer-coarse:px-1.5",+ },tone: {default: "text-foreground",muted: "text-muted-foreground hover:text-foreground",@@ -119,11 +122,12 @@ const inlineButtonVariants = cva(export function InlineButton({className,tone,+ touchTarget,render,...props}: useRender.ComponentProps<"button"> & VariantProps<typeof inlineButtonVariants>) {const defaultProps = {- className: cn(inlineButtonVariants({ tone }), className),+ className: cn(inlineButtonVariants({ tone, touchTarget }), className),"data-slot": "inline-button",type: render ? undefined : ("button" as const),};diff --git a/packages/client-runtime/src/state/threadDetail.ts b/packages/client-runtime/src/state/threadDetail.tsindex 7a17e7326b8..9c6e497340b 100644--- a/packages/client-runtime/src/state/threadDetail.ts+++ b/packages/client-runtime/src/state/threadDetail.ts@@ -14,7 +14,13 @@ import {type ThreadQueueWorkflowState,} from "./threadWorkflows.ts";import { deriveThreadTurnSubagents, type ThreadTurnSubagents } from "./threadSubagents.ts";-import { presentRunStop, type RunStopPresentation } from "./threadExecution.ts";+import {+ deriveUsageLimitNoticeRows,+ presentRunStop,+ withoutUsageLimitNoticeRows,+ type RunStopPresentation,+ type UsageLimitNoticeRows,+} from "./threadExecution.ts";import {deriveThreadCheckpointSummaries,type ThreadCheckpointSummary,@@ -298,11 +304,37 @@ export function createEnvironmentThreadDetailAtoms<E>(}).pipe(Atom.setIdleTTL(0), Atom.withLabel(`environment-quiet-thread:${key}`));});+ // Read from the structure so streamed text does not rescan runs and turn items.+ const usageLimitNoticeRowsAtomFamily = Atom.family((key: string) => {+ let previous: EnvironmentThreadStructure | null = null;+ let value: UsageLimitNoticeRows | null = null;+ return Atom.make((get) => {+ const thread = get(quietThreadAtomFamily(key));+ if (thread !== previous) {+ previous = thread;+ value = thread === null ? null : deriveUsageLimitNoticeRows(thread.projection);+ }+ return value;+ }).pipe(Atom.setIdleTTL(0), Atom.withLabel(`environment-thread-usage-limit-notice:${key}`));+ });++ // Presentation only: the projection keeps every row for other readers.const visibleTurnItemsAtomFamily = Atom.family((key: string) => {const projectQuestionHistory = createQuestionHistoryProjector();+ let previousRows: OrchestrationV2ThreadProjection["visibleTurnItems"] | null = null;+ let previousNotice: UsageLimitNoticeRows | null = null;+ let previous = EMPTY_VISIBLE_TURN_ITEMS;return Atom.make((get): OrchestrationV2ThreadProjection["visibleTurnItems"] => {const projection = Option.getOrNull(get(threadStateValueAtomFamily(key)).data);- return projection === null ? EMPTY_VISIBLE_TURN_ITEMS : projectQuestionHistory(projection);+ if (projection === null) return EMPTY_VISIBLE_TURN_ITEMS;+ const rows = projectQuestionHistory(projection);+ const notice = get(usageLimitNoticeRowsAtomFamily(key));+ if (rows !== previousRows || notice !== previousNotice) {+ previousRows = rows;+ previousNotice = notice;+ previous = withoutUsageLimitNoticeRows(rows, notice);+ }+ return previous;}).pipe(Atom.setIdleTTL(0), Atom.withLabel(`environment-thread-visible-turn-items:${key}`));});diff --git a/packages/client-runtime/src/state/threadExecution.ts b/packages/client-runtime/src/state/threadExecution.tsindex f4335256e98..6b260d7224c 100644--- a/packages/client-runtime/src/state/threadExecution.ts+++ b/packages/client-runtime/src/state/threadExecution.ts@@ -16,6 +16,7 @@ import {type ServerProvider,type ServerProviderModel,type OrchestrationV2ExecutionNode,+ type OrchestrationV2LimitRecovery,type OrchestrationV2ThreadProjection,orchestrationV2RunWorkStartedAt,type RunId,@@ -41,6 +42,7 @@ import {type ThreadRuntimeSummary,type ThreadStructure,type ThreadStructureRuntime,+ type ThreadStructureTurnItem,} from "./models.ts";import { commandDisplayText } from "../work-log/commandLabel.ts";import { formatSubagentDisplayTitle } from "./subagentDisplay.ts";@@ -320,6 +322,100 @@ export function deriveThreadStructureRuntime(};}+export interface UsageLimitNoticeRows {+ readonly itemIds: ReadonlySet<ThreadStructureTurnItem["id"]>;+ /** Hidden only when its text reads as the provider's limit message; see PROVIDER_LIMIT_NOTICE. */+ readonly providerNoticeItemId: ThreadStructureTurnItem["id"] | null;+}++// Claude Code's own limit messages, such as "You've hit your 5-hour limit · resets 7:10am".+const PROVIDER_LIMIT_NOTICE =+ /^(?:You[’']ve hit your (?:(?:5-hour|session|weekly|usage) )?limit|You[’']re out of extra usage|Claude AI usage limit reached)(?: · resets (?:[1-9]|1[0-2])(?::[0-5]\d)?(?:am|pm)(?: \([A-Za-z0-9_+-]+(?:\/[A-Za-z0-9_+-]+)*\))?)?\.?$/i;++/**+ * The timeline rows that repeat a usage-limit pause while its recovery notice shows: the run's+ * limit failure, Claude's pause notices, and the provider's own limit message. They return to+ * history once another run executes.+ */+export function deriveUsageLimitNoticeRows(+ projection: ThreadStructure,+): UsageLimitNoticeRows | null {+ const runtime = deriveThreadStructureRuntime(projection);+ const run = presentedLatestRun(projection);+ if (runtime?.status !== "failed" || runtime.lastErrorClass !== "usage_limit" || run === null) {+ return null;+ }+ const failure = latestRootProviderFailure(run, projection.turnItems);+ const itemIds = new Set<ThreadStructureTurnItem["id"]>();+ let failedProviderTurnId: ThreadStructureTurnItem["providerTurnId"] = null;+ for (const item of projection.turnItems) {+ if (item.runId !== run.id) continue;+ if (+ item.type === "error" &&+ item.status === "failed" &&+ item.nodeId === run.rootNodeId &&+ item.failure.class === "usage_limit"+ ) {+ itemIds.add(item.id);+ if (item.failure === failure) failedProviderTurnId = item.providerTurnId;+ }+ }+ let providerNotice: ThreadStructureTurnItem | null = null;+ if (failedProviderTurnId !== null) {+ for (const item of projection.turnItems) {+ if (item.runId !== run.id || item.providerTurnId !== failedProviderTurnId) continue;+ if (+ item.type === "system_notice" &&+ item.nodeId === run.rootNodeId &&+ item.parentItemId === null &&+ item.nativeItemRef?.driver === "claudeAgent" &&+ item.nativeItemRef.nativeId?.startsWith(`usage-limit:${failedProviderTurnId}:`) === true+ ) {+ itemIds.add(item.id);+ }+ if (+ item.type === "assistant_message" &&+ item.parentItemId === null &&+ (providerNotice === null || item.ordinal > providerNotice.ordinal)+ ) {+ providerNotice = item;+ }+ }+ }+ return { itemIds, providerNoticeItemId: providerNotice?.id ?? null };+}++export function withoutUsageLimitNoticeRows<+ Row extends OrchestrationV2ThreadProjection["visibleTurnItems"][number],+>(rows: ReadonlyArray<Row>, notice: UsageLimitNoticeRows | null): ReadonlyArray<Row> {+ if (notice === null) return rows;+ const hidden = ({ item }: Row) =>+ notice.itemIds.has(item.id) ||+ (item.id === notice.providerNoticeItemId &&+ item.type === "assistant_message" &&+ PROVIDER_LIMIT_NOTICE.test(item.text.trim()));+ return rows.some(hidden) ? rows.filter((row) => !hidden(row)) : rows;+}++/** Whether a usage-limit recovery holds the thread's snooze, so its notice offers Wake now. */+export function limitRecoveryOwnsSnooze(input: {+ readonly runId: RunId | null | undefined;+ readonly resetAt: string | null | undefined;+ readonly recovery: OrchestrationV2LimitRecovery | null | undefined;+ readonly snoozedUntil: string | null | undefined;+}): boolean {+ const { runId, resetAt, recovery, snoozedUntil } = input;+ return (+ recovery?.snooze === true &&+ runId != null &&+ recovery.runId === runId &&+ resetAt != null &&+ recovery.resetAt === resetAt &&+ snoozedUntil != null &&+ Date.parse(snoozedUntil) === Date.parse(resetAt)+ );+}+export function threadRuntimeHasInterruptibleRun(runtime: ThreadStructureRuntime | null | undefined,): boolean {