fix(ui): unify loading and refresh feedback across clients (#9561)

Co-authored-by: Julius Marminge <[email protected]>
This commit is contained in:
Wout StiensandJulius Marminge authored and GitHub committed 2026-09-05 16:26:02 -07:00
1 parent be53bbd850
commit f12d39359f
42 files changed
+506 -183

No files matched your search

@@ -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 (
+13 -22
View File
@@ -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) =>
@@ -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>
<Switch
+2 -4
View File
@@ -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"}
+2 -2
View File
@@ -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>
@@ -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>
<TooltipPopup
side="top"
@@ -5352,7 +5352,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
/>
}
>
<RotateCcwIcon />
<RefreshIcon />
</TooltipTrigger>
<TooltipPopup
side="top"
@@ -5425,7 +5425,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
/>
}
>
<RotateCcwIcon />
<RefreshIcon />
</TooltipTrigger>
<TooltipPopup
side="top"
@@ -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>
<span
@@ -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" />;
@@ -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>
);
@@ -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>
</>
@@ -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>
@@ -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 ? (
@@ -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>
@@ -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>
@@ -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>
@@ -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 ? (
<PullRequestsUnavailableState
error={detailQuery.error}
refreshing={detailQuery.isPending}
onRetry={refreshDetail}
{...(unavailableGitHubUrl ? { gitHubUrl: unavailableGitHubUrl } : {})}
/>
@@ -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 answer
differently, 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>
@@ -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>
<InputGroupInput
type="search"
@@ -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}
@@ -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 {
@@ -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>
@@ -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>
}
/>
@@ -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}
@@ -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 ? (
@@ -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>
}
@@ -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" />
)}
@@ -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>
}
/>
@@ -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 />
)}
@@ -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}
/>
);
@@ -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" ? (
@@ -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}
/>
);
}
+6 -4
View File
@@ -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
<LoaderCircleIcon
aria-label="Loading"
className={cn("animate-spin", className)}
ref={observeVisibleAnimation}
className={cn("motion-safe:visible-animate-spin", className)}
role="status"
{...props}
/>
+4 -3
View File
@@ -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}
<div
+35 -16
View File
@@ -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() {
<Button
onClick={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() {
<Button
onClick={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>
+3 -2
View File
@@ -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>
+9 -5
View File
@@ -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>
);
}
+13 -22
View File
@@ -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) =>
+4
View File
@@ -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"
@@ -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", () => {
+7 -1
View File
@@ -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>(
@@ -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();
});
});
@@ -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();
}
}),
);
}