TypeScript
fix(ui): unify loading and refresh feedback across clients (#9561)
Wout Stiensf12d39359f0f
diff --git a/apps/mobile/src/features/usage/UsageRouteScreen.tsx b/apps/mobile/src/features/usage/UsageRouteScreen.tsxindex 17841cbd74f..164b0955651 100644--- a/apps/mobile/src/features/usage/UsageRouteScreen.tsx+++ b/apps/mobile/src/features/usage/UsageRouteScreen.tsx@@ -11,7 +11,7 @@ import {formatUsd,makeWindow,} from "@t3tools/shared/usageFormat";-import { useMemo, useState } from "react";+import { useMemo, useRef, useState } from "react";import { Platform, Pressable, RefreshControl, ScrollView, View } from "react-native";import { useSafeAreaInsets } from "react-native-safe-area-context";@@ -91,10 +91,8 @@ export function UsageRouteScreen() {[isPast24Hours, merged.daily, merged.hourly],);- // The pull spinner tracks re-scans of environments that have answered- // before. The initial scan renders its own placeholder, and an unreachable- // environment stays pending forever — neither may pin the spinner on.- const refreshingUsage = environments.some((entry) => entry.isPending && entry.summary !== null);+ const [refreshingUsage, setRefreshingUsage] = useState(false);+ const refreshingRef = useRef(false);const showingLimits = tab === "limits";const selectWindow = (days: number) => {setWindowSelection({@@ -103,17 +101,22 @@ export function UsageRouteScreen() {});};const refreshWindow = () => {+ if (refreshingRef.current) return;const nextWindow = makeWindow(windowDays, undefined, isPast24Hours ? "hour" : "day");if (- nextWindow.sinceDay === window.sinceDay &&- nextWindow.untilDay === window.untilDay &&- nextWindow.sinceTime === window.sinceTime &&- nextWindow.untilTime === window.untilTime+ nextWindow.sinceDay !== window.sinceDay ||+ nextWindow.untilDay !== window.untilDay ||+ nextWindow.sinceTime !== window.sinceTime ||+ nextWindow.untilTime !== window.untilTime) {- refresh();- } else {setWindowSelection({ days: windowDays, window: nextWindow });}+ refreshingRef.current = true;+ setRefreshingUsage(true);+ void refresh(nextWindow).finally(() => {+ refreshingRef.current = false;+ setRefreshingUsage(false);+ });};return (diff --git a/apps/mobile/src/state/usage.ts b/apps/mobile/src/state/usage.tsindex f5bdc0d0858..8686a37e2c9 100644--- a/apps/mobile/src/state/usage.ts+++ b/apps/mobile/src/state/usage.ts@@ -16,7 +16,7 @@ import {type UsageSummary,type UsageSummaryInput,} from "@t3tools/contracts";-import { runAtomCommand } from "@t3tools/client-runtime/state/runtime";+import { refreshUsage } from "@t3tools/client-runtime/state/usage";import { mergeUsage, type EnvironmentUsage, type MergedUsage } from "@t3tools/shared/usageMerge";import * as Option from "effect/Option";import { AsyncResult, Atom } from "effect/unstable/reactivity";@@ -72,7 +72,7 @@ export interface UsageView {* improve by waiting on them, so they must not read as "still reporting".*/readonly isPartial: boolean;- readonly refresh: () => void;+ readonly refresh: (input?: UsageSummaryInput) => Promise<void>;}export function useUsage(input: UsageSummaryInput): UsageView {@@ -98,26 +98,17 @@ export function useUsage(input: UsageSummaryInput): UsageView {const atom = usageByWindowAtom(windowKey);const environments = useAtomValue(atom);- // Refreshing only the derived atom would re-read the per-environment SWR- // queries within their stale window and change nothing. Refresh each- // environment's query so pull-to-refresh always rescans.- //- // Each environment refetches model pricing first, so a model released since- // its last daily fetch gets priced by the rescan. The rescan runs whether or- // not the refetch succeeds: an offline environment still recounts tokens.- const refresh = useCallback(() => {- const input = JSON.parse(windowKey) as UsageSummaryInput;- for (const environment of environments) {- const { environmentId } = environment;- const query = serverEnvironment.usageSummary({ environmentId, input });- void runAtomCommand(- appAtomRegistry,- serverEnvironment.refreshUsageRates,- { environmentId, input: {} },- { reportFailure: false },- ).finally(() => appAtomRegistry.refresh(query));- }- }, [environments, windowKey]);+ const refresh = useCallback(+ (nextInput?: UsageSummaryInput) =>+ refreshUsage({+ registry: appAtomRegistry,+ server: serverEnvironment,+ presentations: environmentPresentations,+ environmentIds: environments.map(({ environmentId }) => environmentId),+ input: nextInput ?? (JSON.parse(windowKey) as UsageSummaryInput),+ }),+ [environments, windowKey],+ );const merged = useMemo(() => {const answered: EnvironmentUsage[] = environments.flatMap((environment) =>diff --git a/apps/web/src/components/BranchToolbarBranchSelector.tsx b/apps/web/src/components/BranchToolbarBranchSelector.tsxindex 27bf2ede9b9..f6bdd64756d 100644--- a/apps/web/src/components/BranchToolbarBranchSelector.tsx+++ b/apps/web/src/components/BranchToolbarBranchSelector.tsx@@ -1,3 +1,4 @@+import { RefreshIcon } from "~/components/ui/refresh-icon";import { scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime/environment";import {isAtomCommandInterrupted,@@ -5,7 +6,7 @@ import {} from "@t3tools/client-runtime/state/runtime";import type { ContextMenuItem, EnvironmentId, VcsRef, ThreadId } from "@t3tools/contracts";import { LegendList, type LegendListRef } from "@legendapp/list/react";-import { ChevronDownIcon, GitBranchIcon, RefreshCwIcon, SearchIcon } from "lucide-react";+import { ChevronDownIcon, GitBranchIcon, SearchIcon } from "lucide-react";import {useCallback,useDeferredValue,@@ -864,7 +865,7 @@ export function BranchToolbarBranchSelector({className="flex cursor-pointer items-center justify-between gap-3 border-t border-border/60 px-3 py-2 text-xs"><span className="flex min-w-0 items-center gap-1.5 font-medium text-muted-foreground">- <RefreshCwIcon aria-hidden="true" className="size-3 shrink-0 opacity-70" />+ <RefreshIcon aria-hidden="true" className="size-3 shrink-0 opacity-70" /><span className="truncate">Start from origin</span></span><Switchdiff --git a/apps/web/src/components/DiffPanel.tsx b/apps/web/src/components/DiffPanel.tsxindex 87f5f1ba56f..af6d95dba0b 100644--- a/apps/web/src/components/DiffPanel.tsx+++ b/apps/web/src/components/DiffPanel.tsx@@ -1,3 +1,4 @@+import { RefreshIcon } from "~/components/ui/refresh-icon";import { useAtomValue } from "@effect/atom-react";import type { FileDiffContentsLoader } from "@pierre/diffs";import { useParams } from "@tanstack/react-router";@@ -17,7 +18,6 @@ import {Columns2Icon,FolderTreeIcon,PilcrowIcon,- RefreshCwIcon,Rows3Icon,SearchIcon,TextWrapIcon,@@ -766,9 +766,7 @@ export default function DiffPanel({/>}>- <RefreshCwIcon- className={cn("size-3.5", branchDiffPreview.isPending && "animate-spin")}- />+ <RefreshIcon className="size-3.5" refreshing={branchDiffPreview.isPending} /></TooltipTrigger><TooltipPopup side="top">{branchDiffPreview.isPending ? "Refreshing diff…" : "Refresh diff"}diff --git a/apps/web/src/components/LegacySidebar.tsx b/apps/web/src/components/LegacySidebar.tsxindex 872fa1e4ec6..bacdfa62118 100644--- a/apps/web/src/components/LegacySidebar.tsx+++ b/apps/web/src/components/LegacySidebar.tsx@@ -1,3 +1,4 @@+import { Spinner } from "~/components/ui/spinner";import {ArchiveIcon,ArrowUpDownIcon,@@ -6,7 +7,6 @@ import {ContainerIcon,FolderPlusIcon,Globe2Icon,- LoaderIcon,SearchIcon,SquarePenIcon,TerminalIcon,@@ -2648,7 +2648,7 @@ function LocalSecondaryStatus() {variant="default"className="rounded-2xl border-border/40 bg-accent/40 text-muted-foreground">- <LoaderIcon className="animate-spin" />+ <Spinner /><AlertTitle className="text-xs font-medium text-foreground">Connecting {connecting.join(", ")}</AlertTitle>diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsxindex 9772efc3290..0a54a2a55ab 100644--- a/apps/web/src/components/chat/ChatComposer.tsx+++ b/apps/web/src/components/chat/ChatComposer.tsx@@ -1,3 +1,4 @@+import { RefreshIcon } from "~/components/ui/refresh-icon";import type {ApprovalRequestId,AssistantCitation,@@ -789,7 +790,6 @@ import {LockIcon,LockOpenIcon,PenLineIcon,- RotateCcwIcon,SparklesIcon,XIcon,} from "lucide-react";@@ -5273,7 +5273,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)/>}>- <RotateCcwIcon />+ <RefreshIcon /></TooltipTrigger><TooltipPopupside="top"@@ -5352,7 +5352,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)/>}>- <RotateCcwIcon />+ <RefreshIcon /></TooltipTrigger><TooltipPopupside="top"@@ -5425,7 +5425,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)/>}>- <RotateCcwIcon />+ <RefreshIcon /></TooltipTrigger><TooltipPopupside="top"diff --git a/apps/web/src/components/chat/ComposerActivityStatus.tsx b/apps/web/src/components/chat/ComposerActivityStatus.tsxindex d9e459bcf9e..7a8b83ae736 100644--- a/apps/web/src/components/chat/ComposerActivityStatus.tsx+++ b/apps/web/src/components/chat/ComposerActivityStatus.tsx@@ -1,13 +1,13 @@-import { LoaderCircleIcon } from "lucide-react";-import { observeVisibleAnimation } from "../../lib/visibleAnimation";+import { Spinner } from "~/components/ui/spinner";+import { threadSyncLabel, type ThreadSyncPhase } from "../../threadSync";import { ComposerBanner } from "./ComposerBanner";export function ComposerActivityRow({ phase }: { readonly phase: ThreadSyncPhase }) {return (<ComposerBanner.Row>- <ComposerBanner.Icon ref={observeVisibleAnimation}>- <LoaderCircleIcon className="motion-safe:visible-animate-spin" />+ <ComposerBanner.Icon>+ <Spinner /></ComposerBanner.Icon><ComposerBanner.Content><spandiff --git a/apps/web/src/components/chat/ComposerServerUpdateStatus.tsx b/apps/web/src/components/chat/ComposerServerUpdateStatus.tsxindex 4c5aa60ff06..7431932ce9a 100644--- a/apps/web/src/components/chat/ComposerServerUpdateStatus.tsx+++ b/apps/web/src/components/chat/ComposerServerUpdateStatus.tsx@@ -1,8 +1,8 @@+import { Spinner } from "~/components/ui/spinner";import type { ServerUpdateState } from "@t3tools/client-runtime/state/server";-import { CircleAlertIcon, DownloadIcon, LoaderCircleIcon } from "lucide-react";+import { CircleAlertIcon, DownloadIcon } from "lucide-react";import { useId, useState } from "react";-import { observeVisibleAnimation } from "../../lib/visibleAnimation";import { serverUpdateStageLabel } from "../ServerUpdateAction";import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";import { ComposerBanner } from "./ComposerBanner";@@ -13,13 +13,7 @@ export function ComposerServerUpdateIcon({readonly status: ServerUpdateState["status"];}) {if (status === "running") {- return (- <LoaderCircleIcon- aria-hidden- ref={observeVisibleAnimation}- className="motion-safe:visible-animate-spin"- />- );+ return <Spinner aria-hidden />;}if (status === "failed") {return <CircleAlertIcon aria-hidden className="text-error" />;diff --git a/apps/web/src/components/clerk/ClerkUserProfilePage.tsx b/apps/web/src/components/clerk/ClerkUserProfilePage.tsxindex 00f20e53fbe..2ddf8f56dd2 100644--- a/apps/web/src/components/clerk/ClerkUserProfilePage.tsx+++ b/apps/web/src/components/clerk/ClerkUserProfilePage.tsx@@ -1,4 +1,5 @@-import { RefreshCwIcon } from "lucide-react";+import { RefreshIcon } from "~/components/ui/refresh-icon";+import type { ReactNode } from "react";import { cn } from "../../lib/utils";@@ -55,7 +56,7 @@ export function ClerkUserProfileRefreshButton({disabled={disabled || isPending}onClick={onClick}>- <RefreshCwIcon aria-hidden="true" className={cn("size-3.5", isPending && "animate-spin")} />+ <RefreshIcon aria-hidden="true" className="size-3.5" refreshing={isPending} />Refresh</Button>);diff --git a/apps/web/src/components/files/FileBreadcrumbs.tsx b/apps/web/src/components/files/FileBreadcrumbs.tsxindex 7c7bfe8e9ff..4896c9ce2df 100644--- a/apps/web/src/components/files/FileBreadcrumbs.tsx+++ b/apps/web/src/components/files/FileBreadcrumbs.tsx@@ -1,5 +1,7 @@+import { RefreshIcon } from "~/components/ui/refresh-icon";+import { Spinner } from "~/components/ui/spinner";import type { EnvironmentId } from "@t3tools/contracts";-import { ArrowLeftIcon, ChevronRightIcon, LoaderCircleIcon, RotateCwIcon } from "lucide-react";+import { ArrowLeftIcon, ChevronRightIcon } from "lucide-react";import { useEffect, useMemo, useState } from "react";import { PierreEntryIcon } from "~/components/chat/PierreEntryIcon";@@ -124,12 +126,12 @@ function BreadcrumbMenuContent(props: {<MenuGroup key={props.directoryPath}>{entriesQuery.isPending && entriesQuery.data === null ? (<MenuItem disabled>- <LoaderCircleIcon className="animate-spin" />+ <Spinner />Loading folder…</MenuItem>) : entriesQuery.error && entriesQuery.data === null ? (<MenuItem closeOnClick={false} onClick={entriesQuery.refresh}>- <RotateCwIcon />+ <RefreshIcon refreshing={entriesQuery.isPending} /><span className="min-w-0 flex-1 truncate">Retry loading folder</span></MenuItem>) : !directoryAvailable && !entriesTruncated ? (@@ -177,7 +179,7 @@ function BreadcrumbMenuContent(props: {<><MenuSeparator /><MenuItem closeOnClick={false} onClick={entriesQuery.refresh}>- <RotateCwIcon />+ <RefreshIcon refreshing={entriesQuery.isPending} />Refresh failed — retry</MenuItem></>diff --git a/apps/web/src/components/files/FileBrowserPanel.tsx b/apps/web/src/components/files/FileBrowserPanel.tsxindex dc3cfcef013..7ed900963b4 100644--- a/apps/web/src/components/files/FileBrowserPanel.tsx+++ b/apps/web/src/components/files/FileBrowserPanel.tsx@@ -1,3 +1,4 @@+import { RefreshIcon } from "~/components/ui/refresh-icon";import type {ContextMenuItem as TreeContextMenuItem,ContextMenuOpenContext as TreeContextMenuOpenContext,@@ -5,7 +6,7 @@ import type {import type { EnvironmentId, ProjectEntry } from "@t3tools/contracts";import { FileTree, useFileTree, useFileTreeSearch, useFileTreeSelector } from "@pierre/trees/react";import { serializeComposerFileLink } from "@t3tools/shared/composerTrigger";-import { ChevronsDownUpIcon, ChevronsUpDownIcon, RotateCw } from "lucide-react";+import { ChevronsDownUpIcon, ChevronsUpDownIcon } from "lucide-react";import { useEffect, useMemo, useRef } from "react";import { Button } from "~/components/ui/button";@@ -16,7 +17,6 @@ import { useComposerHandleContext } from "~/composerHandleContext";import { writeTextToClipboard } from "~/hooks/useCopyToClipboard";import { useTheme } from "~/hooks/useTheme";import { useWorkspaceMutationRefresh } from "~/hooks/useWorkspaceMutationRefresh";-import { cn } from "~/lib/utils";import { readLocalApi } from "~/localApi";import { T3_PIERRE_ICONS } from "~/pierre-icons";import { PIERRE_TREE_UNSAFE_CSS, pierreTreeStyle } from "~/pierre-tree-theme";@@ -57,7 +57,7 @@ function RefreshFilesButton(props: { isPending: boolean; onRefresh: () => void }/>}>- <RotateCw className={cn(props.isPending && "animate-spin")} />+ <RefreshIcon refreshing={props.isPending} /></TooltipTrigger><TooltipPopup>{props.isPending ? "Refreshing…" : "Refresh files"}</TooltipPopup></Tooltip>diff --git a/apps/web/src/components/files/FilePreviewPanel.tsx b/apps/web/src/components/files/FilePreviewPanel.tsxindex 33d4d9a4b6c..b739d120da6 100644--- a/apps/web/src/components/files/FilePreviewPanel.tsx+++ b/apps/web/src/components/files/FilePreviewPanel.tsx@@ -1,3 +1,4 @@+import { Spinner } from "~/components/ui/spinner";import type {ChatFileAttachment,EditorId,@@ -18,7 +19,7 @@ import {squashAtomCommandFailure,} from "@t3tools/client-runtime/state/runtime";import { mediaFileReference } from "@t3tools/client-runtime/media-reference";-import { Code2, Eye, FolderTree, Globe2, LoaderCircle } from "lucide-react";+import { Code2, Eye, FolderTree, Globe2 } from "lucide-react";import * as Schema from "effect/Schema";import { useCallback, useEffect, useMemo, useRef, useState } from "react";@@ -198,7 +199,7 @@ function WorkspaceImagePreview(props: {</div>) : (<div className="flex min-h-0 flex-1 items-center justify-center text-muted-foreground">- <LoaderCircle className="size-5 animate-spin" />+ <Spinner className="size-5" /></div>);}@@ -252,7 +253,7 @@ function AttachmentBrowserPreview(props: {if (assetUrl._tag !== "Success") {return (<div className="flex min-h-0 flex-1 items-center justify-center text-muted-foreground">- <LoaderCircle className="size-5 animate-spin" />+ <Spinner className="size-5" /></div>);}@@ -308,7 +309,7 @@ function WorkspaceBrowserPreview(props: {if (assetUrl._tag !== "Success") {return (<div className="flex min-h-0 flex-1 items-center justify-center text-muted-foreground">- <LoaderCircle className="size-5 animate-spin" />+ <Spinner className="size-5" /></div>);}@@ -1262,7 +1263,7 @@ export default function FilePreviewPanel({</div>) : relativePath && file.data === null ? (<div className="flex min-h-0 flex-1 items-center justify-center text-muted-foreground">- <LoaderCircle className="size-5 animate-spin" />+ <Spinner className="size-5" /></div>) : relativePath && file.data ? (isMarkdown && renderMarkdown ? (diff --git a/apps/web/src/components/onboarding/FirstRunGate.tsx b/apps/web/src/components/onboarding/FirstRunGate.tsxindex a9df5cb00b5..6debb0376bd 100644--- a/apps/web/src/components/onboarding/FirstRunGate.tsx+++ b/apps/web/src/components/onboarding/FirstRunGate.tsx@@ -1,7 +1,7 @@+import { RefreshIcon } from "~/components/ui/refresh-icon";import { useAtomValue } from "@effect/atom-react";import { useLocation, useNavigate } from "@tanstack/react-router";import { Atom } from "effect/unstable/reactivity";-import { RotateCcwIcon } from "lucide-react";import { useEffect, useLayoutEffect, useState } from "react";import {@@ -235,7 +235,7 @@ function FirstRunRecovery({}}}>- <RotateCcwIcon />+ <RefreshIcon refreshing={retrying} />{settingsReadFailed ? "Retry" : "Reload"}</Button></div>diff --git a/apps/web/src/components/preview/PreviewChromeRow.tsx b/apps/web/src/components/preview/PreviewChromeRow.tsxindex 8dbf9f0904f..7ca0c496a04 100644--- a/apps/web/src/components/preview/PreviewChromeRow.tsx+++ b/apps/web/src/components/preview/PreviewChromeRow.tsx@@ -1,3 +1,4 @@+import { RefreshIcon } from "~/components/ui/refresh-icon";import {ArrowLeft,ArrowRight,@@ -5,7 +6,6 @@ import {ExternalLink,MousePointerClick,PictureInPicture2,- RotateCw,} from "lucide-react";import {type FormEvent,@@ -166,7 +166,7 @@ export function PreviewChromeRow({/>}>- <RotateCw className={cn(loading && "animate-spin")} />+ <RefreshIcon refreshing={loading} /></TooltipTrigger><TooltipPopup>{loading ? "Loading…" : "Refresh"}</TooltipPopup></Tooltip>diff --git a/apps/web/src/components/pullRequest/PullRequestActivityUnavailableState.tsx b/apps/web/src/components/pullRequest/PullRequestActivityUnavailableState.tsxindex d87dfa45b0f..2aa1413438e 100644--- a/apps/web/src/components/pullRequest/PullRequestActivityUnavailableState.tsx+++ b/apps/web/src/components/pullRequest/PullRequestActivityUnavailableState.tsx@@ -1,4 +1,4 @@-import { RefreshCwIcon } from "lucide-react";+import { RefreshIcon } from "~/components/ui/refresh-icon";import { cn } from "~/lib/utils";@@ -23,7 +23,7 @@ export function PullRequestActivityUnavailableState({<p className="text-sm font-medium text-foreground">Could not load pull request activity</p><p className="max-w-md text-xs text-muted-foreground">{error}</p><Button size="sm" variant="outline" onClick={onRetry}>- <RefreshCwIcon aria-hidden className="size-3.5" />+ <RefreshIcon aria-hidden className="size-3.5" />Retry</Button></div>diff --git a/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx b/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsxindex 76e50b60003..e4aa17b383c 100644--- a/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx+++ b/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx@@ -1,3 +1,4 @@+import { RefreshIcon } from "~/components/ui/refresh-icon";import { scopedThreadKey, scopeProjectRef } from "@t3tools/client-runtime/environment";import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";import {@@ -36,7 +37,6 @@ import {PanelRightIcon,PencilIcon,PlayIcon,- RefreshCwIcon,RotateCcwIcon,TriangleAlertIcon,} from "lucide-react";@@ -728,10 +728,16 @@ export function PullRequestDetailPanel({// invalidation goes first so the re-reads miss that cache; if it fails, the reads still run// and at worst answer from it.const invalidate = useAtomCommand(pullRequestEnvironment.invalidate, { reportFailure: false });+ const [isInvalidating, setIsInvalidating] = useState(false);const refreshFromHost = useCallback(async () => {- await invalidate({ environmentId, input: { reference } });- refreshDetail();- setRefreshToken((token) => token + 1);+ setIsInvalidating(true);+ try {+ await invalidate({ environmentId, input: { reference } });+ refreshDetail();+ setRefreshToken((token) => token + 1);+ } finally {+ setIsInvalidating(false);+ }}, [environmentId, invalidate, reference, refreshDetail]);// A refresh asked for by the page: the detail, and through the token below, the diff with it.const appliedForcedToken = useRef(forcedRefreshToken);@@ -1670,8 +1676,14 @@ export function PullRequestDetailPanel({<MoreHorizontalIcon className="size-4" /></MenuTrigger><MenuPopup align="end" side="bottom" className="min-w-72">- <MenuItem disabled={detailQuery.isPending} onClick={() => void refreshFromHost()}>- <RefreshCwIcon className="size-3.5" />+ <MenuItem+ disabled={isInvalidating || detailQuery.isPending}+ onClick={() => void refreshFromHost()}+ >+ <RefreshIcon+ className="size-3.5"+ refreshing={isInvalidating || detailQuery.isPending}+ />Refresh</MenuItem><MenuItem disabled={handoff !== null} onClick={askAboutPullRequest}>@@ -2315,6 +2327,7 @@ export function PullRequestDetailPanel({{detailQuery.error && !detail ? (<PullRequestsUnavailableStateerror={detailQuery.error}+ refreshing={detailQuery.isPending}onRetry={refreshDetail}{...(unavailableGitHubUrl ? { gitHubUrl: unavailableGitHubUrl } : {})}/>diff --git a/apps/web/src/components/pullRequest/PullRequestListEmptyState.tsx b/apps/web/src/components/pullRequest/PullRequestListEmptyState.tsxindex 4dd92dbf224..8c5f862700b 100644--- a/apps/web/src/components/pullRequest/PullRequestListEmptyState.tsx+++ b/apps/web/src/components/pullRequest/PullRequestListEmptyState.tsx@@ -1,3 +1,4 @@+import { RefreshIcon } from "~/components/ui/refresh-icon";/*** What the list shows when it has no rows to show.*@@ -11,7 +12,7 @@* with no project to read from — leave the button out, since pressing it could only repeat what* is already happening or ask nobody.*/-import { PlusIcon, RefreshCwIcon, SearchIcon } from "lucide-react";+import { PlusIcon, SearchIcon } from "lucide-react";import { openCommandPalette } from "../../commandPaletteBus";import { Button } from "../ui/button";@@ -149,7 +150,7 @@ export function PullRequestListEmptyState({{/* The hosts answered this query once; a pull request opened since then would answerdifferently, and nothing on screen says which of the two the reader is looking at. */}<Button size="sm" variant="outline" disabled={refreshing} onClick={onRefresh}>- <RefreshCwIcon className="size-3.5" />+ <RefreshIcon className="size-3.5" refreshing={refreshing} />{refreshing ? "Checking..." : "Check again"}</Button></EmptyContent>@@ -175,7 +176,7 @@ export function PullRequestListEmptyState({</Button>) : null}<Button size="sm" variant="outline" disabled={refreshing} onClick={onRefresh}>- <RefreshCwIcon className="size-3.5" />+ <RefreshIcon className="size-3.5" refreshing={refreshing} />{refreshing ? "Checking..." : "Check again"}</Button></EmptyContent>diff --git a/apps/web/src/components/pullRequest/PullRequestListFilters.tsx b/apps/web/src/components/pullRequest/PullRequestListFilters.tsxindex f77e2b84508..1c703bce3e2 100644--- a/apps/web/src/components/pullRequest/PullRequestListFilters.tsx+++ b/apps/web/src/components/pullRequest/PullRequestListFilters.tsx@@ -1,3 +1,4 @@+import { Spinner } from "~/components/ui/spinner";import type {EnvironmentId,ProjectId,@@ -17,7 +18,6 @@ import {GitPullRequestDraftIcon,LayersIcon,ListFilterIcon,- LoaderIcon,SearchIcon,TagIcon,UserRoundIcon,@@ -120,7 +120,7 @@ export function PullRequestSearchInput({return (<InputGroup className="min-w-0 flex-1 **:[input]:h-9 sm:**:[input]:h-8"><InputGroupAddon>- {busy ? <LoaderIcon aria-hidden className="animate-spin" /> : <SearchIcon aria-hidden />}+ {busy ? <Spinner aria-hidden /> : <SearchIcon aria-hidden />}</InputGroupAddon><InputGroupInputtype="search"diff --git a/apps/web/src/components/pullRequest/PullRequestsUnavailableState.tsx b/apps/web/src/components/pullRequest/PullRequestsUnavailableState.tsxindex 70f5c845d2c..26c80326aec 100644--- a/apps/web/src/components/pullRequest/PullRequestsUnavailableState.tsx+++ b/apps/web/src/components/pullRequest/PullRequestsUnavailableState.tsx@@ -1,4 +1,5 @@-import { ExternalLinkIcon, GitPullRequestIcon, RefreshCwIcon } from "lucide-react";+import { RefreshIcon } from "~/components/ui/refresh-icon";+import { ExternalLinkIcon, GitPullRequestIcon } from "lucide-react";import { Button } from "../ui/button";import {@@ -14,11 +15,13 @@ export function PullRequestsUnavailableState({title = "Could not load pull requests",error,onRetry,+ refreshing = false,gitHubUrl,}: {title?: string;error: string;onRetry?: () => void;+ refreshing?: boolean;gitHubUrl?: string;}) {return (@@ -35,8 +38,14 @@ export function PullRequestsUnavailableState({{onRetry || gitHubUrl ? (<EmptyContent className="flex-row flex-wrap justify-center gap-2">{onRetry ? (- <Button size="sm" variant="outline" onClick={onRetry}>- <RefreshCwIcon className="size-3.5" />+ <Button+ size="sm"+ variant="outline"+ onClick={onRetry}+ disabled={refreshing}+ aria-busy={refreshing}+ >+ <RefreshIcon className="size-3.5" refreshing={refreshing} />Retry</Button>) : null}diff --git a/apps/web/src/components/pullRequest/pullRequestPresentation.tsx b/apps/web/src/components/pullRequest/pullRequestPresentation.tsxindex 8611ddc28dd..3c41e0956fe 100644--- a/apps/web/src/components/pullRequest/pullRequestPresentation.tsx+++ b/apps/web/src/components/pullRequest/pullRequestPresentation.tsx@@ -1,3 +1,4 @@+import { Spinner } from "~/components/ui/spinner";import type {PullRequestActor,PullRequestCheck,@@ -15,7 +16,6 @@ import {GitPullRequestClosedIcon,GitPullRequestDraftIcon,GitPullRequestIcon,- LoaderIcon,TriangleAlertIcon,} from "lucide-react";import { Children, isValidElement, type ReactNode } from "react";@@ -119,7 +119,7 @@ export function PullRequestStateGlyph({}const CHECK_STATUS_PRESENTATION = {- pending: { label: "Running", Icon: LoaderIcon, toneClassName: "animate-spin text-amber-500" },+ pending: { label: "Running", Icon: Spinner, toneClassName: "text-amber-500" },"action-required": {label: "Awaiting action",Icon: CircleDotIcon,@@ -136,7 +136,7 @@ const CHECK_STATUS_PRESENTATION = {neutral: { label: "Neutral", Icon: CircleDashedIcon, toneClassName: "text-muted-foreground/70" },} as const satisfies Record<PullRequestCheckStatus,- { label: string; Icon: typeof CircleCheckIcon; toneClassName: string }+ { label: string; Icon: typeof CircleCheckIcon | typeof Spinner; toneClassName: string }>;function isWorkflowApprovalCheck(check: Pick<PullRequestCheck, "status" | "url">): boolean {diff --git a/apps/web/src/components/search/ProjectContentSearchDialog.tsx b/apps/web/src/components/search/ProjectContentSearchDialog.tsxindex 6be17ed3324..26015c5b339 100644--- a/apps/web/src/components/search/ProjectContentSearchDialog.tsx+++ b/apps/web/src/components/search/ProjectContentSearchDialog.tsx@@ -1,5 +1,6 @@+import { Spinner } from "~/components/ui/spinner";import type { ProjectContentMatch } from "@t3tools/contracts";-import { LoaderCircle } from "lucide-react";+import { useCallback, useEffect, useMemo, useState, type ReactNode } from "react";import { useActiveProjectTarget, type ActiveProjectTarget } from "~/hooks/useActiveProjectTarget";@@ -225,7 +226,7 @@ function OpenContentSearchDialog(props: {<div className="flex h-9 shrink-0 items-center border-b px-3 text-xs text-muted-foreground">{search.isPending ? (<span className="flex items-center gap-2">- <LoaderCircle className="size-3.5 animate-spin" /> Searching…+ <Spinner className="size-3.5" /> Searching…</span>) : search.error ? (<span className="text-destructive">{search.error}</span>diff --git a/apps/web/src/components/settings/DiagnosticsSettings.tsx b/apps/web/src/components/settings/DiagnosticsSettings.tsxindex 0b23fb2d207..ec3bf854d7b 100644--- a/apps/web/src/components/settings/DiagnosticsSettings.tsx+++ b/apps/web/src/components/settings/DiagnosticsSettings.tsx@@ -1,3 +1,4 @@+import { RefreshIcon } from "~/components/ui/refresh-icon";import {AlertTriangleIcon,ChevronDownIcon,@@ -5,7 +6,6 @@ import {CopyIcon,FolderOpenIcon,InfoIcon,- RefreshCwIcon,} from "lucide-react";import { useAtomValue } from "@effect/atom-react";import {@@ -766,7 +766,7 @@ function DiagnosticsRefreshButton({onClick={onClick}aria-label={label}>- <RefreshCwIcon className={cn(isPending && "animate-spin")} />+ <RefreshIcon refreshing={isPending} /></Button>}/>diff --git a/apps/web/src/components/settings/ProviderInstanceCard.tsx b/apps/web/src/components/settings/ProviderInstanceCard.tsxindex b3faa7b0509..327b48c2d44 100644--- a/apps/web/src/components/settings/ProviderInstanceCard.tsx+++ b/apps/web/src/components/settings/ProviderInstanceCard.tsx@@ -1,10 +1,11 @@"use client";+import { Spinner } from "~/components/ui/spinner";+import {ArrowUpCircleIcon,CopyIcon,DownloadIcon,- LoaderIcon,LockIcon,LockOpenIcon,PlusIcon,@@ -739,7 +740,7 @@ export function ProviderInstanceCard({disabled={isUpdating}onClick={onRunUpdate}>- {isUpdating ? <LoaderIcon className="animate-spin" /> : <DownloadIcon />}+ {isUpdating ? <Spinner /> : <DownloadIcon />}{isUpdating ? "Updating" : "Update now"}</Button>) : null}diff --git a/apps/web/src/components/settings/ProviderSettingsPanel.tsx b/apps/web/src/components/settings/ProviderSettingsPanel.tsxindex fb4620b054c..74676e3ff16 100644--- a/apps/web/src/components/settings/ProviderSettingsPanel.tsx+++ b/apps/web/src/components/settings/ProviderSettingsPanel.tsx@@ -1,3 +1,4 @@+import { RefreshIcon } from "~/components/ui/refresh-icon";import { useAtomValue } from "@effect/atom-react";import { connectionStatusTitle } from "@t3tools/client-runtime/connection";import { safeErrorLogAttributes } from "@t3tools/client-runtime/errors";@@ -24,7 +25,7 @@ import * as Arr from "effect/Array";import * as Duration from "effect/Duration";import * as Equal from "effect/Equal";import * as Result from "effect/Result";-import { PlusIcon, RefreshCwIcon } from "lucide-react";+import { PlusIcon } from "lucide-react";import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";import { isDesktopLocalConnectionTarget } from "../../connection/desktopLocal";@@ -993,7 +994,7 @@ export function EnvironmentProviderSettings({aria-busy={isRefreshingProviders}onClick={() => void refreshProviders()}>- <RefreshCwIcon />+ <RefreshIcon refreshing={isRefreshingProviders} /><span className="sr-only">Refresh provider status</span><span className="hidden min-w-0 truncate sm:inline">{isRefreshingProviders ? (diff --git a/apps/web/src/components/settings/ResourceTelemetryDiagnostics.tsx b/apps/web/src/components/settings/ResourceTelemetryDiagnostics.tsxindex ca934952f8a..003e46869a9 100644--- a/apps/web/src/components/settings/ResourceTelemetryDiagnostics.tsx+++ b/apps/web/src/components/settings/ResourceTelemetryDiagnostics.tsx@@ -1,3 +1,4 @@+import { RefreshIcon } from "~/components/ui/refresh-icon";import {ActivityIcon,AlertTriangleIcon,@@ -9,8 +10,6 @@ import {GaugeIcon,HardDriveIcon,MemoryStickIcon,- RefreshCwIcon,- RotateCcwIcon,} from "lucide-react";import type {BackgroundBooleanState,@@ -982,9 +981,7 @@ export function ResourceTelemetryDiagnostics() {onClick={telemetry.refresh}aria-label="Refresh resource telemetry">- <RefreshCwIcon- className={cn("size-3", telemetry.isPending && "animate-spin")}- />+ <RefreshIcon className="size-3" refreshing={telemetry.isPending} /></Button>}/>@@ -1095,7 +1092,7 @@ export function ResourceTelemetryDiagnostics() {headerAction={collectorNeedsRetry ? (<Button size="xs" variant="outline" disabled={isRetrying} onClick={retryCollector}>- <RotateCcwIcon className={cn("size-3", isRetrying && "animate-spin")} />+ <RefreshIcon className="size-3" refreshing={isRetrying} />Retry monitor</Button>) : null@@ -1233,7 +1230,7 @@ export function ResourceTelemetryDiagnostics() {onClick={history.refresh}aria-label="Refresh resource history">- <RefreshCwIcon className={cn("size-3", history.isPending && "animate-spin")} />+ <RefreshIcon className="size-3" refreshing={history.isPending} /></Button></div>}diff --git a/apps/web/src/components/settings/SettingsPanels.tsx b/apps/web/src/components/settings/SettingsPanels.tsxindex e79464d1757..fe782c5757d 100644--- a/apps/web/src/components/settings/SettingsPanels.tsx+++ b/apps/web/src/components/settings/SettingsPanels.tsx@@ -1,4 +1,5 @@-import { ArchiveIcon, ArchiveX, ChevronRightIcon, LoaderIcon, SettingsIcon } from "lucide-react";+import { Spinner } from "~/components/ui/spinner";+import { ArchiveIcon, ArchiveX, ChevronRightIcon, SettingsIcon } from "lucide-react";import { Link, useNavigate } from "@tanstack/react-router";import type { CSSProperties, ReactNode } from "react";import { useCallback, useEffect, useMemo, useRef, useState } from "react";@@ -3029,7 +3030,7 @@ export function ArchivedThreadsPanel() {title={<span className="inline-flex items-center gap-2">{isLoadingArchive ? (- <LoaderIcon className="size-3.5 animate-spin text-muted-foreground" />+ <Spinner className="size-3.5 text-muted-foreground" />) : (<ArchiveIcon className="size-3.5 text-muted-foreground" />)}diff --git a/apps/web/src/components/settings/SourceControlSettings.tsx b/apps/web/src/components/settings/SourceControlSettings.tsxindex ee1fa66a3db..736b7f1b4b9 100644--- a/apps/web/src/components/settings/SourceControlSettings.tsx+++ b/apps/web/src/components/settings/SourceControlSettings.tsx@@ -1,4 +1,5 @@-import { ChevronDownIcon, GitPullRequestIcon, RefreshCwIcon } from "lucide-react";+import { RefreshIcon } from "~/components/ui/refresh-icon";+import { ChevronDownIcon, GitPullRequestIcon } from "lucide-react";import * as Duration from "effect/Duration";import * as Option from "effect/Option";import { useEffect, useState, type ReactNode } from "react";@@ -487,7 +488,7 @@ function EmptySourceControlDiscovery({</EmptyHeader><EmptyContent><Button size="sm" variant="outline" onClick={onScan} disabled={isPending}>- <RefreshCwIcon className={cn("size-3.5", isPending && "animate-spin")} />+ <RefreshIcon className="size-3.5" refreshing={isPending} />Scan</Button></EmptyContent>@@ -532,7 +533,7 @@ export function SourceControlSettingsPanel() {disabled={discovery.isPending}aria-label="Rescan server environment">- <RefreshCwIcon className={cn(discovery.isPending && "animate-spin")} />+ <RefreshIcon refreshing={discovery.isPending} /></Button>}/>diff --git a/apps/web/src/components/settings/ThemeSearchSection.tsx b/apps/web/src/components/settings/ThemeSearchSection.tsxindex b270bf7b8e4..eb6620a136f 100644--- a/apps/web/src/components/settings/ThemeSearchSection.tsx+++ b/apps/web/src/components/settings/ThemeSearchSection.tsx@@ -1,10 +1,5 @@-import {- ExternalLinkIcon,- PackagePlusIcon,- PaletteIcon,- RefreshCwIcon,- SearchIcon,-} from "lucide-react";+import { RefreshIcon } from "~/components/ui/refresh-icon";+import { ExternalLinkIcon, PackagePlusIcon, PaletteIcon, SearchIcon } from "lucide-react";import { useCallback, useEffect, useRef, useState } from "react";import {importOpenVsxThemeExtension,@@ -417,7 +412,7 @@ export function ThemeSearchSection({{isInstalling ? (<Spinner />) : isInstalled ? (- <RefreshCwIcon />+ <RefreshIcon />) : (<PackagePlusIcon />)}diff --git a/apps/web/src/components/sidebar/DesktopUpdateStatusIcon.tsx b/apps/web/src/components/sidebar/DesktopUpdateStatusIcon.tsxindex 60fa379ce30..833559e1cc2 100644--- a/apps/web/src/components/sidebar/DesktopUpdateStatusIcon.tsx+++ b/apps/web/src/components/sidebar/DesktopUpdateStatusIcon.tsx@@ -1,8 +1,7 @@-import { CheckIcon, DownloadIcon, RefreshCwIcon, RotateCwIcon } from "lucide-react";+import { RefreshIcon } from "~/components/ui/refresh-icon";+import { CheckIcon, DownloadIcon, RotateCwIcon } from "lucide-react";import type { AnimationEventHandler } from "react";-import { cn } from "../../lib/utils";-const DOWNLOAD_PROGRESS_RADIUS = 14;const DOWNLOAD_PROGRESS_CIRCUMFERENCE = 2 * Math.PI * DOWNLOAD_PROGRESS_RADIUS;@@ -118,8 +117,9 @@ export function DesktopUpdateStatusIcon({if (status === "downloaded") return <DesktopUpdateDownloadedIcon />;return (- <RefreshCwIcon- className={cn("size-4", status === "checking" && isCheckAnimating && "animate-spin")}+ <RefreshIcon+ className="size-4"+ refreshing={status === "checking" && isCheckAnimating === true}onAnimationIteration={onCheckAnimationIteration}/>);diff --git a/apps/web/src/components/sidebar/SidebarProviderUpdatePill.tsx b/apps/web/src/components/sidebar/SidebarProviderUpdatePill.tsxindex 84dd7f4b563..066b7e58325 100644--- a/apps/web/src/components/sidebar/SidebarProviderUpdatePill.tsx+++ b/apps/web/src/components/sidebar/SidebarProviderUpdatePill.tsx@@ -1,7 +1,8 @@+import { Spinner } from "~/components/ui/spinner";import { useNavigate } from "@tanstack/react-router";import { useAtomValue } from "@effect/atom-react";import type { ServerProvider } from "@t3tools/contracts";-import { CircleCheckIcon, DownloadIcon, LoaderIcon, TriangleAlertIcon, XIcon } from "lucide-react";+import { CircleCheckIcon, DownloadIcon, TriangleAlertIcon, XIcon } from "lucide-react";import { useCallback, useEffect, useState, type CSSProperties } from "react";import { primaryServerProvidersAtom } from "../../state/server";@@ -173,7 +174,7 @@ export function SidebarProviderUpdatePill() {onClick={openProviderSettings}>{displayedView.tone === "loading" ? (- <LoaderIcon className="size-3.5 animate-spin" />+ <Spinner className="size-3.5" />) : displayedView.tone === "success" ? (<CircleCheckIcon className="size-3.5" />) : displayedView.tone === "error" ? (diff --git a/apps/web/src/components/ui/refresh-icon.tsx b/apps/web/src/components/ui/refresh-icon.tsxnew file mode 100644index 00000000000..6fbddeb365a--- /dev/null+++ b/apps/web/src/components/ui/refresh-icon.tsx@@ -0,0 +1,20 @@+import { RefreshCwIcon } from "lucide-react";++import { cn } from "~/lib/utils";+import { observeVisibleAnimation } from "~/lib/visibleAnimation";++/** Keep the refresh glyph in place while its owning action is running. */+export function RefreshIcon({+ refreshing = false,+ className,+ ...props+}: React.ComponentPropsWithoutRef<typeof RefreshCwIcon> & { refreshing?: boolean }) {+ return (+ <RefreshCwIcon+ aria-hidden+ ref={refreshing ? observeVisibleAnimation : undefined}+ className={cn(refreshing && "motion-safe:visible-animate-spin", className)}+ {...props}+ />+ );+}diff --git a/apps/web/src/components/ui/spinner.tsx b/apps/web/src/components/ui/spinner.tsxindex 362b78f9546..44f0ffd5081 100644--- a/apps/web/src/components/ui/spinner.tsx+++ b/apps/web/src/components/ui/spinner.tsx@@ -1,11 +1,13 @@-import { Loader2Icon } from "lucide-react";+import { LoaderCircleIcon } from "lucide-react";+import { observeVisibleAnimation } from "~/lib/visibleAnimation";import { cn } from "~/lib/utils";-function Spinner({ className, ...props }: React.ComponentProps<typeof Loader2Icon>) {+function Spinner({ className, ...props }: React.ComponentPropsWithoutRef<typeof LoaderCircleIcon>) {return (- <Loader2Icon+ <LoaderCircleIconaria-label="Loading"- className={cn("animate-spin", className)}+ ref={observeVisibleAnimation}+ className={cn("motion-safe:visible-animate-spin", className)}role="status"{...props}/>diff --git a/apps/web/src/components/ui/toast.tsx b/apps/web/src/components/ui/toast.tsxindex 69fd0ebf366..0f6483c2ae6 100644--- a/apps/web/src/components/ui/toast.tsx+++ b/apps/web/src/components/ui/toast.tsx@@ -1,5 +1,7 @@"use client";+import { Spinner } from "~/components/ui/spinner";+import { Toast } from "@base-ui/react/toast";import {useEffect,@@ -20,7 +22,6 @@ import {CircleCheckIcon,CopyIcon,InfoIcon,- LoaderCircleIcon,TriangleAlertIcon,XIcon,} from "lucide-react";@@ -83,7 +84,7 @@ const threadToastVisibleTimeoutRemainingMs = new Map<ToastId, number>();const TOAST_ICONS = {error: CircleAlertIcon,info: InfoIcon,- loading: LoaderCircleIcon,+ loading: Spinner,success: CircleCheckIcon,warning: TriangleAlertIcon,} as const;@@ -357,7 +358,7 @@ function ToastBodyContent({className="[&>svg]:h-lh [&>svg]:w-4 [&_svg]:pointer-events-none [&_svg]:shrink-0"data-slot="toast-icon">- <Icon className="in-data-[type=loading]:animate-spin in-data-[type=error]:text-destructive in-data-[type=info]:text-info in-data-[type=success]:text-success in-data-[type=warning]:text-warning in-data-[type=loading]:opacity-80" />+ <Icon className="in-data-[type=error]:text-destructive in-data-[type=info]:text-info in-data-[type=success]:text-success in-data-[type=warning]:text-warning in-data-[type=loading]:opacity-80" /></div>) : null}<divdiff --git a/apps/web/src/components/usage/UsagePage.tsx b/apps/web/src/components/usage/UsagePage.tsxindex e957002115a..f0dcec49ad9 100644--- a/apps/web/src/components/usage/UsagePage.tsx+++ b/apps/web/src/components/usage/UsagePage.tsx@@ -1,3 +1,4 @@+import { RefreshIcon } from "~/components/ui/refresh-icon";import { useAtomValue } from "@effect/atom-react";import {USAGE_CONTRACT_VERSION,@@ -8,10 +9,9 @@ import {CircleAlertIcon,ChevronDownIcon,CircleDashedIcon,- RefreshCwIcon,SlidersHorizontalIcon,} from "lucide-react";-import { useMemo, useState } from "react";+import { useMemo, useRef, useState } from "react";import {isCompatibleUsageContractVersion,@@ -88,6 +88,8 @@ export function UsagePage() {}));const [metric, setMetric] = useState<UsageMetric>("cost");const showingLimits = metric === "limits";+ const [isRefreshing, setIsRefreshing] = useState(false);+ const refreshingRef = useRef(false);const [breakdown, setBreakdown] = useState<"model" | "time">("model");const [selectedEnvironmentIds, setSelectedEnvironmentIds] =useState<ReadonlySet<EnvironmentId> | null>(null);@@ -138,26 +140,39 @@ export function UsagePage() {});};const refreshWindow = () => {+ if (refreshingRef.current) return;+if (showingLimits) {- for (const [environmentId, presentation] of presentations) {- if (selectedEnvironmentIds !== null && !selectedEnvironmentIds.has(environmentId)) continue;- if (presentation.connection.phase === "connected" && presentation.serverConfig !== null) {- void refreshProviders({ environmentId, input: {} });- }- }+ refreshingRef.current = true;+ setIsRefreshing(true);+ void Promise.all(+ Array.from(presentations, ([environmentId, presentation]) => {+ if (selectedEnvironmentIds !== null && !selectedEnvironmentIds.has(environmentId)) return;+ if (presentation.connection.phase === "connected" && presentation.serverConfig !== null) {+ return refreshProviders({ environmentId, input: {} });+ }+ }),+ ).finally(() => {+ refreshingRef.current = false;+ setIsRefreshing(false);+ });return;}const nextWindow = makeWindow(windowDays, undefined, isPast24Hours ? "hour" : "day");if (- nextWindow.sinceDay === window.sinceDay &&- nextWindow.untilDay === window.untilDay &&- nextWindow.sinceTime === window.sinceTime &&- nextWindow.untilTime === window.untilTime+ nextWindow.sinceDay !== window.sinceDay ||+ nextWindow.untilDay !== window.untilDay ||+ nextWindow.sinceTime !== window.sinceTime ||+ nextWindow.untilTime !== window.untilTime) {- refresh();- } else {setWindowSelection({ days: windowDays, window: nextWindow });}+ refreshingRef.current = true;+ setIsRefreshing(true);+ void refresh(nextWindow).finally(() => {+ refreshingRef.current = false;+ setIsRefreshing(false);+ });};const windowLabel =isPast24Hours && window.sinceTime !== undefined && window.untilTime !== undefined@@ -225,10 +240,12 @@ export function UsagePage() {<ButtononClick={refreshWindow}aria-label={showingLimits ? "Refresh limits" : "Refresh usage"}+ aria-busy={isRefreshing}+ disabled={isRefreshing}size="icon-sm"variant="ghost">- <RefreshCwIcon className="size-3.5" />+ <RefreshIcon className="size-3.5" refreshing={isRefreshing} /></Button></div><div className="col-span-2 ms-auto flex min-w-0 items-center justify-end gap-1 xl:hidden">@@ -282,10 +299,12 @@ export function UsagePage() {<ButtononClick={refreshWindow}aria-label={showingLimits ? "Refresh limits" : "Refresh usage"}+ aria-busy={isRefreshing}+ disabled={isRefreshing}size="icon-sm"variant="ghost">- <RefreshCwIcon className="size-3.5" />+ <RefreshIcon className="size-3.5" refreshing={isRefreshing} /></Button></div></div>diff --git a/apps/web/src/routes/_chat.index.tsx b/apps/web/src/routes/_chat.index.tsxindex 6a53ee02454..339c7eae223 100644--- a/apps/web/src/routes/_chat.index.tsx+++ b/apps/web/src/routes/_chat.index.tsx@@ -1,6 +1,7 @@+import { RefreshIcon } from "~/components/ui/refresh-icon";import { scopeProjectRef } from "@t3tools/client-runtime/environment";import { createFileRoute, Link } from "@tanstack/react-router";-import { LinkIcon, PlusIcon, RotateCcwIcon } from "lucide-react";+import { LinkIcon, PlusIcon } from "lucide-react";import { useCallback, useEffect, useMemo, useRef, useState } from "react";import { openCommandPalette } from "../commandPaletteBus";@@ -96,7 +97,7 @@ function DraftStartError({ onRetry }: { readonly onRetry: () => void }) {</EmptyDescription><div className="mt-5 flex justify-center"><Button size="sm" onClick={onRetry}>- <RotateCcwIcon className="size-4" />+ <RefreshIcon className="size-4" />Try again</Button></div>diff --git a/apps/web/src/routes/_chat.pull-requests.tsx b/apps/web/src/routes/_chat.pull-requests.tsxindex 37522ea3b0a..7aab91d1b82 100644--- a/apps/web/src/routes/_chat.pull-requests.tsx+++ b/apps/web/src/routes/_chat.pull-requests.tsx@@ -1,3 +1,5 @@+import { RefreshIcon } from "~/components/ui/refresh-icon";+import { Spinner } from "~/components/ui/spinner";import { scopeThreadRef } from "@t3tools/client-runtime/environment";import { pullRequestHostOf, resolveEnvironmentMachineKind, ThreadId } from "@t3tools/contracts";import type {@@ -26,10 +28,8 @@ import {LayersIcon,ListChecksIcon,PenLineIcon,- LoaderIcon,Maximize2Icon,Minimize2Icon,- RefreshCwIcon,SearchIcon,} from "lucide-react";import {@@ -1581,7 +1581,11 @@ function PullRequestsRouteView() {) : firstLoad ? (<PullRequestListGhost rows={7} />) : listQuery.error && entries.length === 0 ? (- <PullRequestsUnavailableState error={listQuery.error} onRetry={() => listQuery.refresh()} />+ <PullRequestsUnavailableState+ error={listQuery.error}+ refreshing={listQuery.isPending}+ onRetry={() => listQuery.refresh()}+ />) : carriedToNothing ? (<PullRequestListGhost rows={7} />) : entries.length === 0 ? (@@ -1658,7 +1662,7 @@ function PullRequestsRouteView() {<div className="flex justify-center py-3 text-xs text-muted-foreground">{loadingMore ? (<span className="flex items-center gap-2">- <LoaderIcon aria-hidden className="size-3.5 animate-spin" />+ <Spinner aria-hidden className="size-3.5" />{sentCursors === null ? "Updating pull requests" : "Loading more"}</span>) : canContinue || pageSize < MAX_PAGE_SIZE ? (@@ -2318,7 +2322,7 @@ function PullRequestRefreshControl({onClick={onRefresh}disabled={refreshing}>- <RefreshCwIcon className={cn("size-4", refreshing && "animate-spin")} />+ <RefreshIcon className="size-4" refreshing={refreshing} /></Button>);}diff --git a/apps/web/src/state/usage.ts b/apps/web/src/state/usage.tsindex be65400c980..617ac93e4b7 100644--- a/apps/web/src/state/usage.ts+++ b/apps/web/src/state/usage.ts@@ -13,7 +13,7 @@ import {type UsageSummary,type UsageSummaryInput,} from "@t3tools/contracts";-import { runAtomCommand } from "@t3tools/client-runtime/state/runtime";+import { refreshUsage } from "@t3tools/client-runtime/state/usage";import * as Option from "effect/Option";import { AsyncResult, Atom } from "effect/unstable/reactivity";import { useCallback, useMemo } from "react";@@ -70,7 +70,7 @@ export interface UsageView {* improve by waiting on them, so they must not read as "still reporting".*/readonly isPartial: boolean;- readonly refresh: () => void;+ readonly refresh: (input?: UsageSummaryInput) => Promise<void>;}export function useUsage(@@ -108,26 +108,17 @@ export function useUsage([environments, selectedEnvironmentIds],);- // Refreshing only the derived atom would re-read the per-environment SWR- // queries within their stale window and change nothing. Refresh each- // environment's query so the button always rescans.- //- // Each environment refetches model pricing first, so a model released since- // its last daily fetch gets priced by the rescan. The rescan runs whether or- // not the refetch succeeds: an offline environment still recounts tokens.- const refresh = useCallback(() => {- const input = JSON.parse(windowKey) as UsageSummaryInput;- for (const environment of selectedEnvironments) {- const { environmentId } = environment;- const query = serverEnvironment.usageSummary({ environmentId, input });- void runAtomCommand(- appAtomRegistry,- serverEnvironment.refreshUsageRates,- { environmentId, input: {} },- { reportFailure: false },- ).finally(() => appAtomRegistry.refresh(query));- }- }, [selectedEnvironments, windowKey]);+ const refresh = useCallback(+ (nextInput?: UsageSummaryInput) =>+ refreshUsage({+ registry: appAtomRegistry,+ server: serverEnvironment,+ presentations: environmentPresentations,+ environmentIds: selectedEnvironments.map(({ environmentId }) => environmentId),+ input: nextInput ?? (JSON.parse(windowKey) as UsageSummaryInput),+ }),+ [selectedEnvironments, windowKey],+ );const merged = useMemo(() => {const answered: EnvironmentUsage[] = selectedEnvironments.flatMap((environment) =>diff --git a/packages/client-runtime/package.json b/packages/client-runtime/package.jsonindex 68f5bad5147..c7d92139344 100644--- a/packages/client-runtime/package.json+++ b/packages/client-runtime/package.json@@ -147,6 +147,10 @@"types": "./src/state/runtime.ts","default": "./src/state/runtime.ts"},+ "./state/usage": {+ "types": "./src/state/usage.ts",+ "default": "./src/state/usage.ts"+ },"./state/server": {"types": "./src/state/server.ts","default": "./src/state/server.ts"diff --git a/packages/client-runtime/src/state/runtime.test.ts b/packages/client-runtime/src/state/runtime.test.tsindex 3f12f44d5f4..ca4ac5ac911 100644--- a/packages/client-runtime/src/state/runtime.test.ts+++ b/packages/client-runtime/src/state/runtime.test.ts@@ -683,6 +683,24 @@ describe("executeAtomQuery", () => {registry.dispose();});++ it("settles when its caller aborts a waiting query", async () => {+ const registry = AtomRegistry.make();+ const controller = new AbortController();+ const resultPromise = executeAtomQuery(registry, Atom.make(Effect.never), {+ reportDefect: false,+ signal: controller.signal,+ });++ controller.abort();++ const result = await resultPromise;+ expect(result._tag).toBe("Failure");+ if (result._tag === "Failure") {+ expect(Cause.hasInterruptsOnly(result.cause)).toBe(true);+ }+ registry.dispose();+ });});describe("runtime command runner", () => {diff --git a/packages/client-runtime/src/state/runtime.ts b/packages/client-runtime/src/state/runtime.tsindex affd5aa90ec..3e61909ee71 100644--- a/packages/client-runtime/src/state/runtime.ts+++ b/packages/client-runtime/src/state/runtime.ts@@ -336,6 +336,8 @@ export interface AtomQueryOptions extends AtomCommandOptions {* verification flows where a cached failure must not satisfy a retry.*/readonly refresh?: boolean;+ /** Interrupt the query wait when its caller no longer wants the result. */+ readonly signal?: AbortSignal;}export async function executeAtomQuery<A, E>(@@ -362,7 +364,11 @@ export async function executeAtomQuery<A, E>(});}),);- return executeAtomCommand(() => Effect.runPromiseExit(query), options, reporter);+ return executeAtomCommand(+ () => Effect.runPromiseExit(query, { signal: options.signal }),+ options,+ reporter,+ );}export function createRuntimeCommand<R, ER, W, A, E>(diff --git a/packages/client-runtime/src/state/usage.test.ts b/packages/client-runtime/src/state/usage.test.tsnew file mode 100644index 00000000000..29f029c9d86--- /dev/null+++ b/packages/client-runtime/src/state/usage.test.ts@@ -0,0 +1,184 @@+import {+ EnvironmentId,+ UsageDay,+ USAGE_CONTRACT_VERSION,+ type UsageSummary,+} from "@t3tools/contracts";+import * as Effect from "effect/Effect";+import { AsyncResult, Atom, AtomRegistry } from "effect/unstable/reactivity";+import { afterEach, describe, expect, it } from "vite-plus/test";++import type { EnvironmentPresentation } from "../connection/presentation.ts";+import { EnvironmentRpcUnavailableError } from "../rpc/client.ts";+import { refreshUsage } from "./usage.ts";++const input = {+ sinceDay: UsageDay.make("2026-09-05"),+ untilDay: UsageDay.make("2026-09-05"),+ timeZone: "UTC",+};+const pricing = { status: "fresh" as const, source: "test", fetchedAt: null, knownModels: 1 };+const summary: UsageSummary = {+ ...input,+ contractVersion: USAGE_CONTRACT_VERSION,+ readAt: "2026-09-05T12:00:00Z",+ buckets: [],+ sources: [],+ pricing,+ scanDurationMs: 1,+};+const registries: AtomRegistry.AtomRegistry[] = [];+afterEach(() => {+ for (const registry of registries.splice(0)) registry.dispose();+});++function harness(ids = ["a"]) {+ const registry = AtomRegistry.make();+ registries.push(registry);+ const environments = ids.map((id) => {+ const environmentId = EnvironmentId.make(id);+ const rates = Promise.withResolvers<+ AsyncResult.Success<typeof pricing> | AsyncResult.Failure<never, unknown>+ >();+ const scan = Promise.withResolvers<UsageSummary>();+ const scanStarted = Promise.withResolvers<void>();+ const presentation = Atom.make({+ connection: { phase: "connected" },+ } as EnvironmentPresentation | null);+ const query = Atom.make(+ Effect.promise(() => {+ scanStarted.resolve();+ return scan.promise;+ }),+ );+ return { environmentId, rates, scan, scanStarted, presentation, query };+ });+ function get(environmentId: EnvironmentId) {+ const environment = environments.find((entry) => entry.environmentId === environmentId);+ if (!environment) throw new Error(`Unknown environment: ${environmentId}`);+ return environment;+ }+ const options = {+ registry,+ environmentIds: environments.map((entry) => entry.environmentId),+ input,+ server: {+ usageSummary: ({ environmentId }: { environmentId: EnvironmentId }) =>+ get(environmentId).query,+ refreshUsageRates: {+ label: "test:rates",+ run: (+ _registry: AtomRegistry.AtomRegistry,+ { environmentId }: { environmentId: EnvironmentId },+ ) => get(environmentId).rates.promise,+ },+ },+ presentations: {+ presentationAtom: (environmentId: EnvironmentId) => get(environmentId).presentation,+ },+ } satisfies Parameters<typeof refreshUsage>[0];+ return { registry, environments, refresh: () => refreshUsage(options) };+}++describe("manual usage refresh", () => {+ it.each(["success", "failure"])("waits for the rescan after a pricing %s", async (result) => {+ const {+ environments: [environment],+ refresh,+ } = harness();+ const entry = environment!;+ let finished = false;+ const refreshing = refresh().then(() => {+ finished = true;+ });+ expect(finished).toBe(false);+ entry.rates.resolve(+ result === "success"+ ? AsyncResult.success(pricing)+ : AsyncResult.fail(new Error("Pricing offline")),+ );+ await entry.scanStarted.promise;+ expect(finished).toBe(false);+ entry.scan.resolve(summary);+ await refreshing;+ expect(finished).toBe(true);+ });++ it("settles when an environment disconnects during the rescan", async () => {+ const {+ registry,+ environments: [environment],+ refresh,+ } = harness();+ const entry = environment!;+ const refreshing = refresh();+ entry.rates.resolve(AsyncResult.success(pricing));+ await entry.scanStarted.promise;+ registry.set(entry.presentation, null);+ await refreshing;+ });++ it("waits for healthy environments without waiting for a recovering environment", async () => {+ const { registry, environments, refresh } = harness(["healthy", "recovering"]);+ const [healthy, recovering] = environments;+ registry.set(recovering!.presentation, null);+ let finished = false;+ const refreshing = refresh().then(() => {+ finished = true;+ });+ for (const entry of environments) entry.rates.resolve(AsyncResult.success(pricing));+ await healthy!.scanStarted.promise;+ expect(finished).toBe(false);+ healthy!.scan.resolve(summary);+ await refreshing;+ expect(finished).toBe(true);+ });++ it("settles when connected state has no usable RPC session", async () => {+ const {+ environments: [environment],+ refresh,+ } = harness();+ const entry = environment!;+ const refreshing = refresh();+ entry.rates.resolve(+ AsyncResult.fail(+ new EnvironmentRpcUnavailableError({+ environmentId: entry.environmentId,+ message: "No session",+ }),+ ),+ );+ await refreshing;+ });++ it("replaces a scan that started before pricing was refreshed", async () => {+ const {+ registry,+ environments: [environment],+ refresh,+ } = harness();+ const entry = environment!;+ let reads = 0;+ const rescanned = Promise.withResolvers<void>();+ const query = Atom.make(+ Effect.promise(() => {+ reads += 1;+ if (reads > 1) {+ rescanned.resolve();+ return Promise.resolve(summary);+ }+ return new Promise<UsageSummary>(() => {});+ }),+ );+ entry.query = query;+ const unmount = registry.mount(query);+ expect(reads).toBe(1);+ const refreshing = refresh();+ entry.rates.resolve(AsyncResult.success(pricing));+ await rescanned.promise;+ await refreshing;+ expect(reads).toBe(2);+ unmount();+ });+});diff --git a/packages/client-runtime/src/state/usage.ts b/packages/client-runtime/src/state/usage.tsnew file mode 100644index 00000000000..10a565a0c24--- /dev/null+++ b/packages/client-runtime/src/state/usage.ts@@ -0,0 +1,61 @@+import type { EnvironmentId, UsageSummaryInput } from "@t3tools/contracts";+import * as Schema from "effect/Schema";+import type { AtomRegistry } from "effect/unstable/reactivity";++import { EnvironmentRpcUnavailableError } from "../rpc/client.ts";+import type { createEnvironmentPresentationAtoms } from "./presentation.ts";+import { executeAtomQuery, runAtomCommand, squashAtomCommandFailure } from "./runtime.ts";+import type { createServerEnvironmentAtoms } from "./server.ts";++const isEnvironmentRpcUnavailable = Schema.is(EnvironmentRpcUnavailableError);++/** Refresh pricing, then await each selected environment's rescan while it remains connected. */+export async function refreshUsage({+ registry,+ server,+ presentations,+ environmentIds,+ input,+}: {+ registry: AtomRegistry.AtomRegistry;+ server: Pick<+ ReturnType<typeof createServerEnvironmentAtoms>,+ "usageSummary" | "refreshUsageRates"+ >;+ presentations: Pick<ReturnType<typeof createEnvironmentPresentationAtoms>, "presentationAtom">;+ environmentIds: readonly EnvironmentId[];+ input: UsageSummaryInput;+}): Promise<void> {+ await Promise.all(+ environmentIds.map(async (environmentId) => {+ const query = server.usageSummary({ environmentId, input });+ const presentation = presentations.presentationAtom(environmentId);+ const controller = new AbortController();+ const abortWhenDisconnected = () => {+ if (registry.get(presentation)?.connection.phase !== "connected") controller.abort();+ };+ const unsubscribe = registry.subscribe(presentation, abortWhenDisconnected);+ abortWhenDisconnected();+ try {+ const ratesResult = await runAtomCommand(+ registry,+ server.refreshUsageRates,+ { environmentId, input: {} },+ { reportFailure: false },+ );+ const sessionUnavailable =+ ratesResult._tag === "Failure" &&+ isEnvironmentRpcUnavailable(squashAtomCommandFailure(ratesResult));+ // Invalidate even on failure so reconnects cannot reuse the old summary.+ registry.refresh(query);+ if (sessionUnavailable || controller.signal.aborted) return;+ await executeAtomQuery(registry, query, {+ reportFailure: false,+ signal: controller.signal,+ });+ } finally {+ unsubscribe();+ }+ }),+ );+}