Compare commits

..
Author SHA1 Message Date
Mohamed Boudra 02e2c5f3ec fix(app): record a host eviction only after its delete commits
Eviction marked the host as evicted before deleteHost ran. If storage aborted
that delete, the rows stayed stored but the mark remained. A malformed-row
repair running behind it trusted the mark: it skipped the checkpoint update
yet still deleted the row, leaving a workspace cursor with no workspace. The
next refresh then resumed past that workspace.

The mark is now set after the delete commits, so it always matches storage.
A failed eviction leaves no mark, and the repair updates the row and its
cursor together.
2026-11-20 23:36:50 +07:00
Mohamed Boudra cf0c4243a3 fix(app): apply the eviction rule to malformed-row repairs
Repairing a malformed directory row reads the checkpoint, drops the affected
cursor, and writes the rest back. That write went straight to the row store
through queueOperation, outside the eviction check in the regular persist
path. If a write evicted the same host while the repair was reading, the
repair stored a checkpoint for a host with no directory rows, the state this
branch exists to prevent.

All three repair writes now go through one helper that runs in the serialized
writer and drops the checkpoint upsert when the host has been evicted since.
The deletes still apply.
2026-11-20 23:27:50 +07:00
Mohamed Boudra 1f28cde1a9 fix(app): advance directory cursors from live updates only after a refresh
A live update moved the directory cursor whenever no refresh was in flight,
including when no refresh had ever completed on the current subscriptions.
If the first sync after discarding a version 1 checkpoint failed, the next
project update saved a cursor at its own sequence with only that project
stored. The retry asked for changes after it, the daemon had none, and the
other projects stayed missing across restarts. The previous commit closed
this window during the cache load only; a failed refresh reopened it.

A live event's sequence covers everything before it only when a refresh
completed on the subscriptions that delivered it, which is what
satisfiedDemandSource already records. Live events now update rows either
way but move the cursor only in that state, so a cursor never skips changes
the client did not receive. Once a refresh completes, live updates advance
the cursor as before.

The sidebar recovery e2e fixture unwrapped the checkpoint only when it was
version 1, so the version 2 writer made it abort before damaging the cache.
It now reads either envelope and stores the damage as version 1, the format
this branch stops trusting, so the test fails against the previous cache
module and passes here.
2026-11-20 23:19:42 +07:00
Mohamed Boudra a138bea3ee fix(app): hold workspace updates that arrive while the directory cache loads
A project update received while the cached directory was being read went
straight into the replica. It advanced the project cursor before any refresh
had established a baseline, and saved that cursor to the cache. On an install
damaged before the eviction fix, that write replaced the version 1 checkpoint
with a version 2 one before the reader could reject it. The refresh then asked
for project changes after the live update, the daemon had none, and projects
missing from the cache stayed missing across restarts.

Agents already open a transaction before the cache load, so their updates are
recorded and applied over the refreshed snapshot. Workspaces now do the same.
An update during the load also stops the cached cursors being adopted, so the
refresh fetches full snapshots, which is the recovery a damaged cache needs.
2026-11-20 22:52:28 +07:00
Mohamed Boudra d328f0fbbf fix(app): restore a host's workspaces after its cached directory is evicted
A host could keep a current directory checkpoint in the replica cache with
none of the rows it described. The daemon then answered "no changes" since
that cursor, and the sidebar had no projects to place cached workspaces
under, so every workspace for that host vanished and stayed missing across
restarts.

The cache already refused mutations for an evicted host, but it checked at
the moment a mutation was queued. Eviction happens later, inside the
serialized write, so anything queued before the eviction ran was still
written, checkpoint included. The check moves into materializePendingChanges
so it runs in the same serialized step that evicts, which also covers an
eviction that lands while an earlier persist is still indexing the store.

Checking at queue time was also losing good data: once a host was
invalidated, every mutation was dropped, including updates accepted between
a reconnect's baseline replacement and its write. Those are kept now,
because the baseline is in the same pending batch.

Version 1 checkpoints could have been written by that path, so they are no
longer trusted. A reader discards them and keeps the cached rows, so the
sidebar still paints from cache and each host re-syncs its directory once.
Later launches resume incrementally.

Both the race and the recovery live in the shared cache, so this covers iOS,
Android, web, and Electron. It does not address two tabs or windows sharing
one IndexedDB database, where another connection evicts the host.
2026-11-20 22:39:05 +07:00
39 changed files with 532 additions and 746 deletions
+7 -2
View File
@@ -582,12 +582,17 @@ host, kinds, and ids. Opening a cached workspace uses exact workspace and projec
directory scan. One invalid row is deleted and returned as a miss without affecting other rows.
An invalid directory row and its affected checkpoint cursor are repaired in one transaction, so a
later launch cannot accept a checkpoint for a partial baseline. Directory changes and their
checkpoint are also applied in one transaction. Reads wait for accepted changes to reach storage,
checkpoint are also applied in one transaction. A stored checkpoint carries a version. When a writer
bug could have stored a checkpoint without its directory, bump the version: older checkpoints are
rejected on read, cached rows still paint, and each host re-syncs its directory once. Reads wait for
accepted changes to reach storage,
then retry only when a requested row changes during the read. Unrelated agent streams do not
invalidate the read. Directory baseline replacements and host removal or renaming still invalidate
the affected reads.
The cache is capped at 32 MiB and evicts whole hosts in least-recently-written order. Budget
The cache is capped at 32 MiB and evicts whole hosts in least-recently-written order. After an
eviction, only a baseline replacement stores that host's directory again. Mutations queued around
the eviction are dropped when they are written, so a checkpoint never outlives its rows. Budget
bookkeeping may scan opaque row sizes during a deferred write, never during host registry startup or
before a requested cache row can paint. The row store is not encrypted. A cached timeline can contain
source code, prompts, and tool output; encrypted-at-rest storage is a separate security decision.
@@ -206,13 +206,14 @@ async function simulateDamagedLegacyDirectoryCache(
return;
}
const stored = JSON.parse(checkpoint.payload);
// Accept either writer so this fixture also reproduces on the unfixed client.
const cursors = stored.version === 1 ? stored.cursors : stored;
if (!cursors.workspaces?.generation) {
// Read the cursors from whichever version wrote them, then store them as version 1:
// the format whose writer could keep a checkpoint after evicting the rows it describes.
const cursors = typeof stored.version === "number" ? stored.cursors : stored;
if (!cursors?.workspaces?.generation) {
transaction.abort();
return;
}
store.put({ ...checkpoint, payload: JSON.stringify(cursors) });
store.put({ ...checkpoint, payload: JSON.stringify({ version: 1, cursors }) });
for (const row of rows) {
if (
row.serverId === serverId &&
@@ -503,34 +503,6 @@ test.describe("terminal history with a finger", () => {
await expectMouseWheelScrollsHistory(page);
});
test("finger scrolling leaves terminal input unfocused until a tap", async ({ page }) => {
await openPhoneTerminalHistory(page);
await blurTerminalInput(page);
await expectSingleFingerScroll(page, 24);
await expect(input(page)).not.toBeFocused();
await expectSingleFingerScroll(page, 1);
await expect(input(page)).not.toBeFocused();
await tapTerminalScreen(page);
await expect(input(page)).toBeFocused();
});
test("finger scrolling keeps a floating keyboard's input focused", async ({ page }) => {
await openPhoneTerminalHistory(page);
await tapTerminalScreen(page);
await expect(input(page)).toBeFocused();
// A floating keyboard leaves the visual viewport unchanged.
await expectSingleFingerScroll(page, 24);
await expect(input(page)).toBeFocused();
await expect(input(page)).toHaveAttribute("virtualkeyboardpolicy", "manual");
// Android Back also leaves the input focused. A tap restores automatic keyboard opening.
await tapTerminalScreen(page);
await expect(input(page)).not.toHaveAttribute("virtualkeyboardpolicy");
});
for (const mode of ["alternate", "mouse"] as const) {
test(`preserves finger navigation in ${mode} input mode`, async ({ page }) => {
await openPhoneInputCapture(page, mode);
@@ -559,26 +531,6 @@ async function openPhoneTerminalHistory(page: Page) {
});
await openPhoneTerminal(page);
await expect.poll(() => getTerminalBufferText(page)).toContain("HISTORY_150");
await expect
.poll(() => page.evaluate(() => window.__paseoTerminal!.buffer.active.baseY))
.toBeGreaterThan(0);
await page.evaluate(() => window.__paseoTerminal!.scrollToBottom());
await expect.poll(() => viewport(page)).toBeGreaterThan(0);
}
function terminalScreen(page: Page) {
return page.getByTestId("terminal-surface").filter({ visible: true }).locator(".xterm-screen");
}
async function tapTerminalScreen(page: Page) {
const box = await terminalScreen(page).boundingBox();
expect(box).not.toBeNull();
await page.touchscreen.tap(box!.x + box!.width / 2, box!.y + box!.height / 3);
}
async function blurTerminalInput(page: Page) {
await input(page).evaluate((element) => element.blur());
await expect(input(page)).not.toBeFocused();
}
async function openPhoneInputCapture(page: Page, mode: "alternate" | "mouse") {
@@ -618,20 +570,6 @@ async function openPhoneTerminal(page: Page) {
await page.getByTestId(`sidebar-workspace-row-${getServerId()}:${harness.workspaceId}`).click();
await expect(page.getByRole("textbox", { name: "Terminal input" })).toBeVisible();
await expect(page.getByTestId("terminal-surface").filter({ visible: true })).toBeVisible();
// The terminal stays mounted while the sidebar's closing backdrop still intercepts input.
await expect
.poll(() =>
page
.getByTestId("terminal-surface")
.filter({ visible: true })
.evaluate((root) => {
const box = root.querySelector(".xterm-screen")!.getBoundingClientRect();
return root.contains(
document.elementFromPoint(box.x + box.width / 2, box.y + box.height / 3),
);
}),
)
.toBe(true);
}
async function expectMouseWheelScrollsHistory(page: Page) {
+1 -103
View File
@@ -2,14 +2,13 @@ import { tmpdir } from "node:os";
import { randomUUID } from "node:crypto";
import path from "node:path";
import type { Page } from "@playwright/test";
import type { UsageReport, UsageReportEntry } from "@getpaseo/protocol/messages";
import type { UsageReportEntry } from "@getpaseo/protocol/messages";
import { expect, test } from "../support/fixtures";
import { gotoAppShell, openSettings } from "../support/helpers/app";
import { addConnectedHostAndReload } from "../support/helpers/hosts";
import { startIsolatedHostDaemon } from "../support/helpers/isolated-host-daemon";
import { openSettingsSection } from "../support/helpers/settings";
import { gate } from "../support/helpers/context-window";
import { installDaemonWebSocketGate } from "../support/helpers/daemon-websocket-gate";
import { getServerId } from "../support/helpers/server-id";
import { seedSidebarFooterPreferences } from "../support/helpers/sidebar-nav-settings";
import {
@@ -46,7 +45,6 @@ import {
refreshAllUsage,
togglePin,
usageItem,
usageModal,
} from "../support/helpers/usage-sidebar-item";
const emptyHome = path.join(tmpdir(), `paseo-usage-empty-${randomUUID()}`);
@@ -867,106 +865,6 @@ test("open usage clocks advance without refreshing or reopening", async ({ page
}
});
test("Refresh all keeps quota visible and restores the forecast after a timeout", async ({
page,
}) => {
const reading = new Date();
const login = await installLoginUsage(usageReading(reading, 40));
try {
const transport = await installDaemonWebSocketGate(page);
await openCompactUsageWithClock(page, reading);
await expectQuota(page, "40% used", /runs out in /);
await timeOutUsageRefresh(page, transport);
await expectQuota(page, "40% used", null);
await expectUsageRefreshError(page).toBeVisible();
await login.setReport(usageReading(reading, 10));
transport.releaseHeldClientRequest();
await refreshAllUsage(page);
await expectQuota(page, "10% used", "~50% left at reset");
await expectUsageRefreshError(page).toBeHidden();
} finally {
await login.cleanup();
}
});
test("a card refresh timeout is visible alongside a newer quota forecast", async ({ page }) => {
const reading = new Date();
const login = await installLoginUsage(usageReading(reading, 40));
try {
const transport = await installDaemonWebSocketGate(page);
await openCompactUsageWithClock(page, reading);
await expectQuota(page, "40% used", /runs out in /);
await delayCardRefreshResponse(page, transport);
await login.setReport(usageReading(reading, 10));
await refreshAllUsage(page);
await expectQuota(page, "10% used", "~50% left at reset");
await advanceUsageClock(page, 61_000);
await expectUsageRefreshError(page).toBeVisible();
await expectQuota(page, "10% used", "~50% left at reset");
} finally {
await login.cleanup();
}
});
function expectUsageRefreshError(page: Page) {
return expect(usageModal(page).getByText("Unable to refresh usage", { exact: true }));
}
async function delayCardRefreshResponse(
page: Page,
transport: Awaited<ReturnType<typeof installDaemonWebSocketGate>>,
) {
await expect(page.getByRole("button", { name: "Refresh all", exact: true })).toBeEnabled();
transport.holdNextServerMessage("usage.list_reports.response");
await refreshLoginUsage(page);
await transport.waitForHeldServerMessage("usage.list_reports.response");
}
function usageReading(observed: Date, usedPct: number): UsageReport {
return {
status: "available",
observedAt: observed.toISOString(),
windows: [
{
id: "session",
label: "Session",
usedPct,
durationSeconds: 18_000,
resetsAt: new Date(observed.getTime() + 4 * 3_600_000).toISOString(),
},
],
};
}
async function expectQuota(page: Page, amount: string, forecast: string | RegExp | null) {
const usage = usageModal(page);
await expect(usage.getByText(amount, { exact: true })).toBeVisible();
await expect(usage.getByText(/^resets in /)).toBeVisible();
if (forecast === null) {
await expect(usage.getByText(/^runs out in /)).toBeHidden();
return;
}
await expect(usage.getByText(forecast)).toBeVisible();
}
async function timeOutUsageRefresh(
page: Page,
transport: Awaited<ReturnType<typeof installDaemonWebSocketGate>>,
) {
const refresh = page.getByRole("button", { name: "Refresh all", exact: true });
await expect(refresh).toBeEnabled();
transport.holdNextClientRequest("usage.list_reports.request");
await refreshAllUsage(page);
await transport.waitForHeldClientRequest();
await expect(refresh).toBeDisabled();
await advanceUsageClock(page, 61_000);
await expect(refresh).toBeEnabled();
}
async function openCompactUsageWithClock(page: Page, now: Date) {
await page.setViewportSize({ width: 390, height: 844 });
await page.clock.install({ time: now });
@@ -185,15 +185,13 @@ function onLogin(report: UsageReportEntry, login: string): UsageReportEntry {
}
export function expiredLogin(report: UsageReportEntry): UsageReportEntry {
const fetchedAt = Date.now();
return {
...report,
fetchedAt: new Date(fetchedAt).toISOString(),
report: {
status: "unavailable",
problem: {
kind: "expired",
expiresAt: new Date(fetchedAt - 2 * 60 * 60_000).toISOString(),
expiresAt: new Date(Date.now() - 2 * 60 * 60_000).toISOString(),
refreshedBy: "claude",
},
},
@@ -13,7 +13,6 @@ import {
useRef,
type CSSProperties,
type MouseEvent as ReactMouseEvent,
type PointerEvent as ReactPointerEvent,
type Ref,
} from "react";
import type { DOMProps } from "expo/dom";
@@ -64,12 +63,6 @@ const HOST_DIV_STYLE: CSSProperties = {
paddingRight: 0,
};
interface TerminalTouchFocus {
pointerId: number;
x: number;
y: number;
}
function buildXtermThemeKey(theme: ITheme): string {
const values: Array<string> = [
theme.background,
@@ -560,46 +553,10 @@ export default function TerminalEmulator({
});
}, []);
const touchFocusRef = useRef<TerminalTouchFocus | null>(null);
const handleRootPointerDown = useCallback(
(event: ReactPointerEvent) => {
onFocus?.();
touchFocusRef.current = null;
if (event.pointerType !== "touch") {
runtimeRef.current?.focus();
return;
}
// Focusing before a touch becomes a tap opens the keyboard during a scroll.
if (event.isPrimary) {
touchFocusRef.current = {
pointerId: event.pointerId,
x: event.clientX,
y: event.clientY,
};
}
},
[onFocus],
);
const handleRootPointerMove = useCallback((event: ReactPointerEvent) => {
const touch = touchFocusRef.current;
if (touch?.pointerId !== event.pointerId) return;
if (Math.hypot(event.clientX - touch.x, event.clientY - touch.y) > 8) {
touchFocusRef.current = null;
runtimeRef.current?.suppressAutomaticKeyboard();
}
}, []);
const handleRootPointerUp = useCallback((event: ReactPointerEvent) => {
const touch = touchFocusRef.current;
touchFocusRef.current = null;
if (touch?.pointerId === event.pointerId) runtimeRef.current?.focus();
}, []);
const handleRootPointerCancel = useCallback(() => {
touchFocusRef.current = null;
}, []);
const handleRootPointerDown = useCallback(() => {
onFocus?.();
runtimeRef.current?.focus();
}, [onFocus]);
const handleRootContextMenu = useCallback(
(event: ReactMouseEvent) => {
@@ -631,9 +588,6 @@ export default function TerminalEmulator({
data-terminal-scrollbar-root="true"
style={rootDivStyle}
onPointerDown={handleRootPointerDown}
onPointerMove={handleRootPointerMove}
onPointerUp={handleRootPointerUp}
onPointerCancel={handleRootPointerCancel}
onContextMenu={handleRootContextMenu}
>
<div ref={hostRef} style={HOST_DIV_STYLE} />
-3
View File
@@ -2323,9 +2323,6 @@ export const ar: TranslationResources = {
resetsIn: "تتم إعادة التعيين خلال {{duration}}",
resetsAtWeekday: "{{weekday}} {{time}}",
resetsAtDate: "{{date}}، {{time}}",
projectedLeftAtReset: "نحو {{percentage}} متبقية عند إعادة التعيين",
limitReached: "تم بلوغ الحد",
mayHaveRunOut: "ربما نفدت الحصة",
runsOutNow: "ينفد الآن",
runsOutIn: "ينفد خلال {{duration}}",
justNow: "الآن",
-3
View File
@@ -2333,9 +2333,6 @@ export const en = {
resetsIn: "resets in {{duration}}",
resetsAtWeekday: "{{weekday}} {{time}}",
resetsAtDate: "{{date}}, {{time}}",
projectedLeftAtReset: "~{{percentage}} left at reset",
limitReached: "Limit reached",
mayHaveRunOut: "May have run out",
runsOutNow: "runs out now",
runsOutIn: "runs out in {{duration}}",
justNow: "just now",
-3
View File
@@ -2354,9 +2354,6 @@ export const es: TranslationResources = {
resetsIn: "se restablece en {{duration}}",
resetsAtWeekday: "{{weekday}} {{time}}",
resetsAtDate: "{{date}}, {{time}}",
projectedLeftAtReset: "~{{percentage}} restante al restablecerse",
limitReached: "Límite alcanzado",
mayHaveRunOut: "Puede que ya se haya agotado",
runsOutNow: "se agota ahora",
runsOutIn: "se agota en {{duration}}",
justNow: "ahora mismo",
-3
View File
@@ -2355,9 +2355,6 @@ export const fr: TranslationResources = {
resetsIn: "se réinitialise dans {{duration}}",
resetsAtWeekday: "{{weekday}} {{time}}",
resetsAtDate: "{{date}}, {{time}}",
projectedLeftAtReset: "~{{percentage}} restant à la réinitialisation",
limitReached: "Limite atteinte",
mayHaveRunOut: "Le quota est peut-être épuisé",
runsOutNow: "s’épuise maintenant",
runsOutIn: "s’épuise dans {{duration}}",
justNow: "à l’instant",
-3
View File
@@ -2328,9 +2328,6 @@ export const ja: TranslationResources = {
resetsIn: "{{duration}}後にリセット",
resetsAtWeekday: "{{weekday}} {{time}}",
resetsAtDate: "{{date}} {{time}}",
projectedLeftAtReset: "リセット時に約{{percentage}}残る見込み",
limitReached: "上限に達しました",
mayHaveRunOut: "上限に達した可能性があります",
runsOutNow: "まもなく上限に到達",
runsOutIn: "{{duration}}後に上限に到達",
justNow: "たった今",
-3
View File
@@ -2316,9 +2316,6 @@ export const ko: TranslationResources = {
resetsIn: "{{duration}} 후 재설정",
resetsAtWeekday: "{{weekday}} {{time}}",
resetsAtDate: "{{date}} {{time}}",
projectedLeftAtReset: "초기화 시 약 {{percentage}} 남을 예정",
limitReached: "한도에 도달함",
mayHaveRunOut: "한도를 소진했을 수 있음",
runsOutNow: "지금 한도에 도달",
runsOutIn: "{{duration}} 후 한도에 도달",
justNow: "방금",
-3
View File
@@ -2339,9 +2339,6 @@ export const ptBR: TranslationResources = {
resetsIn: "redefine em {{duration}}",
resetsAtWeekday: "{{weekday}} {{time}}",
resetsAtDate: "{{date}}, {{time}}",
projectedLeftAtReset: "~{{percentage}} restará na renovação",
limitReached: "Limite atingido",
mayHaveRunOut: "A cota pode ter se esgotado",
runsOutNow: "esgota agora",
runsOutIn: "esgota em {{duration}}",
justNow: "agora mesmo",
-3
View File
@@ -2341,9 +2341,6 @@ export const ru: TranslationResources = {
resetsIn: "сброс через {{duration}}",
resetsAtWeekday: "{{weekday}} {{time}}",
resetsAtDate: "{{date}}, {{time}}",
projectedLeftAtReset: "К сбросу останется ~{{percentage}}",
limitReached: "Лимит исчерпан",
mayHaveRunOut: "Лимит мог уже исчерпаться",
runsOutNow: "закончится сейчас",
runsOutIn: "закончится через {{duration}}",
justNow: "только что",
-3
View File
@@ -2282,9 +2282,6 @@ export const zhCN: TranslationResources = {
resetsIn: "将在 {{duration}}后重置",
resetsAtWeekday: "{{weekday}} {{time}}",
resetsAtDate: "{{date}} {{time}}",
projectedLeftAtReset: "重置时约剩余 {{percentage}}",
limitReached: "已达到上限",
mayHaveRunOut: "额度可能已用完",
runsOutNow: "即将用尽",
runsOutIn: "将在 {{duration}}后用尽",
justNow: "刚刚",
@@ -10,7 +10,10 @@ import type {
DaemonClient,
WorkspaceLabelListPayload,
} from "@getpaseo/client/internal/daemon-client";
import type { SessionOutboundMessage } from "@getpaseo/protocol/messages";
import type {
SessionOutboundMessage,
WorkspaceDescriptorPayload,
} from "@getpaseo/protocol/messages";
import {
normalizeProjectDescriptor,
normalizeWorkspaceDescriptor,
@@ -1667,6 +1670,187 @@ it("fills every cached workspace beneath live updates received during the SQLite
database.close();
});
/**
* A host whose cache was damaged before the eviction fix: workspaces survived, project rows did not,
* and a version 1 checkpoint still claims the project directory is current. The daemon holds
* projects A and B; renaming A is its update at `renameSeq`.
*/
async function createDamagedLegacyProjectDirectory(serverId: string, renameSeq: number) {
serverIds.add(serverId);
const { cache, database, storage, reopen, holdRead } = createSqliteCache();
cache.setHosts([serverId]);
const workspacePayload = (id: string, projectId: string): WorkspaceDescriptorPayload => ({
id,
projectId,
projectDisplayName: projectId,
projectRootPath: `/repo/${projectId}`,
workspaceDirectory: `/repo/${projectId}`,
projectKind: "git",
workspaceKind: "local_checkout",
name: id,
status: "done",
statusEnteredAt: null,
activityAt: null,
archivingAt: null,
diffStat: null,
scripts: [],
});
const project = (projectId: string, projectDisplayName: string) => ({
projectId,
projectDisplayName,
projectRootPath: `/repo/${projectId}`,
projectKind: "git" as const,
});
const workspaceEntries = [workspacePayload("wa", "A"), workspacePayload("wb", "B")];
cache.replaceDirectoryBaseline(serverId, {
agents: new Map(),
workspaces: new Map(
workspaceEntries.map((entry) => [entry.id, normalizeWorkspaceDescriptor(entry)]),
),
projects: new Map(),
});
await cache.flush();
await storage.apply({
deletes: [],
upserts: [
{
serverId,
kind: "checkpoint",
id: "singleton",
payload: JSON.stringify({
version: 1,
cursors: { projects: { generation: "g", afterSeq: renameSeq - 1 } },
}),
},
],
});
const reopened = reopen();
reopened.setHosts([serverId]);
const client = new FakeDirectoryClient();
let failNextProjectRequest = false;
client.listProjects = async (options?: unknown): Promise<ProjectListResult> => {
client.lastProjectOptions = options;
if (failNextProjectRequest) {
failNextProjectRequest = false;
throw new Error("Request timed out");
}
const resumesAfterRename =
(options as { sync?: { afterSeq?: number } } | undefined)?.sync?.afterSeq === renameSeq;
return resumesAfterRename
? {
requestId: "projects",
projects: [],
sync: { generation: "g", headSeq: renameSeq, mode: "changes", removals: [] },
}
: {
requestId: "projects",
projects: [project("A", "Renamed"), project("B", "B")],
sync: { generation: "g", headSeq: renameSeq, mode: "snapshot", removals: [] },
};
};
client.fetchWorkspaces = async (): Promise<WorkspaceFetchResult> => ({
requestId: "workspaces",
entries: workspaceEntries,
emptyProjects: [],
pageInfo: { hasMore: false, nextCursor: null, prevCursor: null },
sync: { generation: "g", headSeq: 2, mode: "snapshot", removals: [] },
});
const directory = new DirectorySync(
serverId,
{
onAgentStoppedRunning: () => {},
markAgentLoading: () => {},
markAgentReady: () => {},
markAgentError: () => {},
},
reopened,
);
const store = useSessionStore.getState();
store.initializeSession(serverId, client as unknown as DaemonClient, 1);
store.updateSessionServerInfo(serverId, {
serverId,
hostname: null,
version: "test",
features: { workspaceMultiplicity: true, directorySync: true, projectList: true },
});
directory.connectionChanged({
client: client as unknown as DaemonClient,
status: "online",
source: { clientGeneration: 1, connectionEpoch: 1 },
});
return {
client,
directory,
holdRead,
failNextProjectRequest: () => {
failNextProjectRequest = true;
},
renameProjectA: () =>
client.emit({
type: "project.update",
payload: {
kind: "upsert",
project: project("A", "Renamed"),
generation: "g",
seq: renameSeq,
},
}),
sessionProjectIds: () =>
[...useSessionStore.getState().sessions[serverId].projects.keys()].sort(),
persistedProjectIds: async () => {
await reopened.flush();
const restarted = reopen();
restarted.setHosts([serverId]);
return [...(await restarted.readDirectory(serverId)).projects.keys()].sort();
},
close: async () => {
directory.dispose();
await reopened.flush();
database.close();
},
};
}
it("re-syncs every project when a project update lands while an untrusted cache loads", async () => {
const damaged = await createDamagedLegacyProjectDirectory("untrusted-checkpoint-race", 6);
try {
let renamed = false;
damaged.holdRead(async () => {
if (renamed) return;
renamed = true;
damaged.renameProjectA();
});
damaged.directory.setDemand({}, true);
await damaged.directory.refreshDemand();
expect(renamed).toBe(true);
expect(damaged.client.lastProjectOptions).toEqual({ sync: {} });
expect(damaged.sessionProjectIds()).toEqual(["A", "B"]);
expect(await damaged.persistedProjectIds()).toEqual(["A", "B"]);
} finally {
await damaged.close();
}
});
it("re-syncs every project when a project update lands after the first sync fails", async () => {
const damaged = await createDamagedLegacyProjectDirectory("failed-first-sync", 3);
try {
damaged.failNextProjectRequest();
damaged.directory.setDemand({}, true);
await expect(damaged.directory.refreshDemand()).rejects.toThrow("Request timed out");
damaged.renameProjectA();
await damaged.directory.refreshDemand();
expect(damaged.client.lastProjectOptions).toEqual({ sync: {} });
expect(damaged.sessionProjectIds()).toEqual(["A", "B"]);
expect(await damaged.persistedProjectIds()).toEqual(["A", "B"]);
} finally {
await damaged.close();
}
});
function createWorkspaceLabelDirectory(serverId: string) {
const { client, directory } = createDirectory(serverId, { workspaceLabels: true });
const store = useSessionStore.getState();
@@ -288,7 +288,7 @@ export class DirectorySync {
this.revision += 1;
if (this.agentTransactions.record(source, delta)) return;
this.agents.applyDelta(delta);
this.noteLiveCursor("agents", delta);
if (this.extendsRefreshedBaseline(source)) this.noteLiveCursor("agents", delta);
this.persistCheckpoint();
}
@@ -300,7 +300,7 @@ export class DirectorySync {
this.workspaceRevision += 1;
if (this.workspaceTransactions.record(source, delta)) return;
this.applyWorkspaceDelta(delta);
if (delta.kind !== "script_status")
if (delta.kind !== "script_status" && this.extendsRefreshedBaseline(source))
this.noteLiveCursor(
"projectId" in delta || "project" in delta ? "projects" : "workspaces",
delta,
@@ -308,6 +308,20 @@ export class DirectorySync {
this.persistCheckpoint();
}
/**
* A live event's sequence covers everything before it only when a refresh completed on the
* subscriptions that delivered it. Before that (first sync still pending or failed) or after
* they lapse, the client may have missed earlier changes, so the event updates rows but leaves
* the cursor where the next refresh can still fetch what was missed.
*/
private extendsRefreshedBaseline(source: DirectorySourceToken): boolean {
const refreshed = this.satisfiedDemandSource;
return (
refreshed?.clientGeneration === source.clientGeneration &&
refreshed.connectionEpoch === source.connectionEpoch
);
}
private observeDirectoryEvents(): void {
if (this.eventSubscription) return;
const { client, source } = this.requireOnline();
@@ -566,24 +580,16 @@ export class DirectorySync {
input: { subscribe?: boolean } | undefined,
loadDirectoryCache: boolean,
): Promise<void> {
if (loadDirectoryCache) await this.loadCachedDirectory();
if (loadDirectoryCache) {
this.primeWorkspaceTransactionForCacheLoad();
await this.loadCachedDirectory();
}
const onlineConnection = this.getOnlineConnection();
if (!onlineConnection) return;
const { client, source } = onlineConnection;
const transaction = this.workspaceTransactions.begin(source, () => {
const baseline = this.workspaces.snapshot();
return {
workspaces: new Map(baseline.workspaces),
projects: new Map(baseline.projects),
// Cache hydration can advance the live replica while these requests await responses.
// Every page must use the cursors belonging to the maps captured here.
requestCursors: { ...this.cursors },
syncCursors: {},
syncModes: {},
touchedWorkspaceIds: new Set(),
touchedProjectIds: new Set(),
};
});
const transaction = this.workspaceTransactions.begin(source, () =>
this.createWorkspaceRefreshSnapshot(),
);
try {
await this.waitForSessionMetadata(client, source);
const serverInfo = useSessionStore.getState().sessions[this.serverId]?.serverInfo;
@@ -807,6 +813,31 @@ export class DirectorySync {
}));
}
// Updates that arrive before a refresh completes have no trusted baseline to advance from.
// Holding them keeps their cursor out of the cache until the refresh they are applied over.
private primeWorkspaceTransactionForCacheLoad(): void {
const connection = this.getOnlineConnection();
if (!connection) return;
this.workspaceTransactions.begin(connection.source, () =>
this.createWorkspaceRefreshSnapshot(),
);
}
private createWorkspaceRefreshSnapshot(): WorkspaceRefreshSnapshot {
const baseline = this.workspaces.snapshot();
return {
workspaces: new Map(baseline.workspaces),
projects: new Map(baseline.projects),
// Cache hydration can advance the live replica while these requests await responses.
// Every page must use the cursors belonging to the maps captured here.
requestCursors: { ...this.cursors },
syncCursors: {},
syncModes: {},
touchedWorkspaceIds: new Set(),
touchedProjectIds: new Set(),
};
}
private supportsDirectorySync(): boolean {
return (
useSessionStore.getState().sessions[this.serverId]?.serverInfo?.features?.directorySync ===
@@ -37,6 +37,9 @@ class MemoryStorage implements ReplicaRowStore {
onRead: (() => void) | null = null;
/** Throws once a read goes past this count, so a non-terminating read loop fails the test. */
readLimit: number | null = null;
/** Awaited before the store lists every row or deletes a host, so a test can interleave there. */
beforeReadAll: (() => Promise<void>) | null = null;
beforeDeleteHost: (() => Promise<void>) | null = null;
private key(row: Pick<ReplicaRow, "serverId" | "kind" | "id">): string {
return `${row.serverId}:${row.kind}:${row.id}`;
@@ -68,6 +71,7 @@ class MemoryStorage implements ReplicaRowStore {
}
async readAll(): Promise<ReplicaHostRows[]> {
await this.beforeReadAll?.();
const hosts = new Map<string, ReplicaRow[]>();
for (const row of this.rows.values()) {
const rows = hosts.get(row.serverId) ?? [];
@@ -91,6 +95,7 @@ class MemoryStorage implements ReplicaRowStore {
}
async deleteHost(serverId: string): Promise<void> {
await this.beforeDeleteHost?.();
for (const [key, row] of this.rows) if (row.serverId === serverId) this.rows.delete(key);
}
@@ -436,40 +441,49 @@ describe("ReplicaCache", () => {
await expectLegacyWorkspaceRefresh(cached);
});
it("rejects pre-baseline-fix checkpoints without discarding cached rows or timelines", async () => {
const storage = new MemoryStorage();
const writer = createCache(storage);
const baseline = directory();
writer.replaceDirectoryBaseline(SERVER_ID, baseline);
writer.commitTimeline(SERVER_ID, "agent-1", timeline());
await writer.flush();
await storage.apply({
deletes: [],
upserts: [
{
serverId: SERVER_ID,
kind: "checkpoint",
id: "singleton",
payload: JSON.stringify(baseline.checkpoint),
},
],
});
it.each([
["before the baseline fix", (checkpoint: DirectoryCheckpoint): unknown => checkpoint],
[
"before the eviction fix",
(checkpoint: DirectoryCheckpoint): unknown => ({ version: 1, cursors: checkpoint }),
],
])(
"rejects checkpoints written %s without discarding cached rows or timelines",
async (_era, legacyPayload) => {
const storage = new MemoryStorage();
const writer = createCache(storage);
const baseline = directory();
writer.replaceDirectoryBaseline(SERVER_ID, baseline);
writer.commitTimeline(SERVER_ID, "agent-1", timeline());
await writer.flush();
await storage.apply({
deletes: [],
upserts: [
{
serverId: SERVER_ID,
kind: "checkpoint",
id: "singleton",
payload: JSON.stringify(legacyPayload(baseline.checkpoint)),
},
],
});
const reader = createCache(storage);
const restored = await reader.readDirectory(SERVER_ID);
expect(restored.checkpoint).toBeUndefined();
expect([...restored.workspaces.keys()]).toEqual([...baseline.workspaces.keys()]);
expect([...restored.projects.keys()]).toEqual([...baseline.projects.keys()]);
expect([...restored.agents.keys()]).toEqual([...baseline.agents.keys()]);
expect(await reader.readTimeline(SERVER_ID, "agent-1")).toEqual(timeline());
expect(await storage.read(SERVER_ID, ["checkpoint"])).toEqual([]);
const reader = createCache(storage);
const restored = await reader.readDirectory(SERVER_ID);
expect(restored.checkpoint).toBeUndefined();
expect([...restored.workspaces.keys()]).toEqual([...baseline.workspaces.keys()]);
expect([...restored.projects.keys()]).toEqual([...baseline.projects.keys()]);
expect([...restored.agents.keys()]).toEqual([...baseline.agents.keys()]);
expect(await reader.readTimeline(SERVER_ID, "agent-1")).toEqual(timeline());
expect(await storage.read(SERVER_ID, ["checkpoint"])).toEqual([]);
reader.replaceDirectoryBaseline(SERVER_ID, baseline);
await reader.flush();
expect((await createCache(storage).readDirectory(SERVER_ID)).checkpoint).toEqual(
baseline.checkpoint,
);
});
reader.replaceDirectoryBaseline(SERVER_ID, baseline);
await reader.flush();
expect((await createCache(storage).readDirectory(SERVER_ID)).checkpoint).toEqual(
baseline.checkpoint,
);
},
);
it("does nothing until an owner explicitly commits data", async () => {
const storage = new MemoryStorage();
@@ -1102,6 +1116,113 @@ describe("ReplicaCache", () => {
).toEqual(["agent", "checkpoint", "project", "workspace"]);
});
it.each(["beforeReadAll", "beforeDeleteHost"] as const)(
"stores no checkpoint for a host evicted after its update was queued (%s)",
async (pausePoint) => {
const storage = new MemoryStorage();
const previousSession = new ReplicaCache(storage, noLegacyCleanup);
previousSession.setHosts([SERVER_ID, "other-host"]);
previousSession.replaceDirectoryBaseline(SERVER_ID, directory());
previousSession.replaceDirectoryBaseline("other-host", directory());
await previousSession.flush();
const cache = new ReplicaCache(storage, { ...noLegacyCleanup, maxBytes: 8_192 });
cache.setHosts([SERVER_ID, "other-host"]);
const paused = deferred();
const resume = deferred();
storage[pausePoint] = async () => {
storage[pausePoint] = null;
paused.resolve();
await resume.promise;
};
// Larger than the whole budget, so this persist evicts both hosts.
cache.commitTimeline(SERVER_ID, "agent-1", timeline("x".repeat(16_384)));
const eviction = cache.flush();
await paused.promise;
cache.commitDirectoryMutations(SERVER_ID, [], { agents: { generation: "g", afterSeq: 13 } });
resume.resolve();
await eviction;
await cache.flush();
const restored = await createCache(storage).readDirectory(SERVER_ID);
expect(restored.agents.size).toBe(0);
expect(restored.checkpoint).toBeUndefined();
},
);
it("stores no checkpoint for a host evicted while a malformed row is repaired", async () => {
const { storage } = await cacheWithoutBackgroundVisibility();
const reader = createCache(storage, 8_192);
storage.onRead = () => {
if (!storage.reads.at(-1)?.kinds.includes("checkpoint")) return;
storage.onRead = null;
// Larger than the whole budget, so this persist evicts the host before the repair writes.
reader.commitTimeline(SERVER_ID, "agent-1", timeline("x".repeat(16_384)));
void reader.flush();
};
expect(await reader.readWorkspace(SERVER_ID, "workspace-1")).toBeUndefined();
await reader.flush();
const restored = await createCache(storage).readDirectory(SERVER_ID);
expect(restored.projects.size).toBe(0);
expect(restored.checkpoint).toBeUndefined();
});
it("repairs a malformed row's cursor when the overlapping eviction fails", async () => {
const { storage } = await cacheWithoutBackgroundVisibility();
const reader = createCache(storage, 8_192);
storage.onRead = () => {
if (!storage.reads.at(-1)?.kinds.includes("checkpoint")) return;
storage.onRead = null;
storage.beforeDeleteHost = async () => {
storage.beforeDeleteHost = null;
throw new Error("Eviction aborted");
};
reader.commitTimeline(SERVER_ID, "agent-1", timeline("x".repeat(16_384)));
void reader.flush();
};
expect(await reader.readWorkspace(SERVER_ID, "workspace-1")).toBeUndefined();
// A newer timeline fits the budget, so no later eviction clears the checkpoint.
reader.commitTimeline(SERVER_ID, "agent-1", timeline());
await reader.flush();
const restored = await createCache(storage).readDirectory(SERVER_ID);
expect(restored.workspaces.size).toBe(0);
expect(restored.checkpoint).toEqual({
agents: { generation: "g", afterSeq: 12 },
projects: { generation: "g", afterSeq: 4 },
});
});
it("keeps an update queued behind the baseline that rebuilds an evicted host", async () => {
const storage = new MemoryStorage();
const cache = new ReplicaCache(storage, { ...noLegacyCleanup, maxBytes: 2_500 });
cache.setHosts([SERVER_ID, "other-host"]);
const baseline = directory();
cache.replaceDirectoryBaseline(SERVER_ID, baseline);
await cache.flush();
cache.replaceDirectoryBaseline("other-host", baseline);
await cache.flush();
expect((await cache.readDirectory(SERVER_ID)).agents.size).toBe(0);
const renamed = { ...agent(), title: "Renamed agent" };
cache.replaceDirectoryBaseline(SERVER_ID, baseline);
cache.commitDirectoryMutations(
SERVER_ID,
[{ kind: "agent", type: "upsert", id: renamed.id, value: renamed }],
{ agents: { generation: "g", afterSeq: 13 } },
);
await cache.flush();
cache.commitDirectoryMutations(SERVER_ID, [], { agents: { generation: "g", afterSeq: 14 } });
await cache.flush();
const restored = await createCache(storage).readDirectory(SERVER_ID);
expect(restored.checkpoint).toEqual({ agents: { generation: "g", afterSeq: 14 } });
expect(restored.agents.get(renamed.id)?.title).toBe("Renamed agent");
});
it("runs legacy cleanup once when storage is first used", async () => {
const storage = new MemoryStorage();
const cache = new ReplicaCache(storage, {
+34 -20
View File
@@ -397,15 +397,19 @@ const DirectoryCheckpointSchema = z.strictObject({
agents: DirectoryCursorSchema.optional(),
});
// Old checkpoints could describe a baseline that an overlapping refresh had discarded.
// Revalidate directory contents once without evicting cached rows or timelines.
// A checkpoint is trusted only when this version wrote it. Earlier writers could store one for a
// directory the cache no longer held: unversioned ones after an overlapping refresh, version 1
// after an eviction. Rejecting them revalidates directory contents once without evicting cached
// rows or timelines.
const DIRECTORY_CHECKPOINT_VERSION = 2;
const StoredDirectoryCheckpointSchema = z.strictObject({
version: z.literal(1),
version: z.literal(DIRECTORY_CHECKPOINT_VERSION),
cursors: DirectoryCheckpointSchema,
});
function serializeDirectoryCheckpoint(cursors: DirectoryCheckpoint) {
return { version: 1 as const, cursors };
return { version: DIRECTORY_CHECKPOINT_VERSION, cursors };
}
function deserializeDirectoryCheckpoint(payload: string): DirectoryCheckpoint {
@@ -968,6 +972,7 @@ export class ReplicaCache {
private pendingUpserts = new Map<string, StructuredReplicaUpsert>();
private pendingDeletes = new Map<string, ReplicaRowKey>();
private pendingBaselines = new Set<string>();
// Hosts whose stored directory was evicted. Only a baseline stores their directory again.
private readonly invalidatedHosts = new Set<string>();
private readonly maxBytes: number;
private totalBytes = 0;
@@ -1109,11 +1114,7 @@ export class ReplicaCache {
private async deleteInvalidRow(row: ReplicaRow): Promise<void> {
const invalidEntity = directoryEntityForRow(row);
if (!invalidEntity) {
const changes = { upserts: [], deletes: [row] } satisfies ReplicaRowChanges;
await this.queueOperation(async () => {
await this.rowStore.apply(changes);
this.applyStoredChanges(changes);
});
await this.applyRepair(row.serverId, { upserts: [], deletes: [row] });
return;
}
@@ -1144,10 +1145,7 @@ export class ReplicaCache {
]
: [],
};
await this.queueOperation(async () => {
await this.rowStore.apply(changes);
this.applyStoredChanges(changes);
});
await this.applyRepair(row.serverId, changes);
}
private async repairInvalidDirectoryRows(
@@ -1170,9 +1168,16 @@ export class ReplicaCache {
]
: [],
};
await this.queueOperation(async () => {
await this.rowStore.apply(changes);
this.applyStoredChanges(changes);
await this.applyRepair(serverId, changes);
}
// A repair is queued behind writes that can evict its host. If one did, the host has no
// directory left for the repaired checkpoint to describe, so only the deletes still apply.
private applyRepair(serverId: string, changes: ReplicaRowChanges): Promise<void> {
return this.queueOperation(async () => {
const applied = this.invalidatedHosts.has(serverId) ? { ...changes, upserts: [] } : changes;
await this.rowStore.apply(applied);
this.applyStoredChanges(applied);
});
}
@@ -1182,7 +1187,6 @@ export class ReplicaCache {
checkpoint?: DirectoryCheckpoint,
): void {
if (!this.activeServerIds.has(serverId)) return;
if (this.invalidatedHosts.has(serverId)) return;
for (const mutation of mutations) {
if (mutation.type === "delete") {
this.queueEntityDelete(serverId, mutation.kind, mutation.id);
@@ -1412,9 +1416,17 @@ export class ReplicaCache {
}
private materializePendingChanges(pending: PendingReplicaChanges): ReplicaRowChanges {
const deletes = new Map(pending.deletes.map((row) => [pendingRowKey(row), row]));
// Decided here, inside the serialized write, because eviction happens there too. A mutation
// queued before its host was evicted would otherwise store a checkpoint without its directory.
const isStorable = (row: ReplicaRowKey): boolean =>
row.kind === "timeline" ||
!this.invalidatedHosts.has(row.serverId) ||
pending.baselines.has(row.serverId);
const deletes = new Map(
pending.deletes.filter(isStorable).map((row) => [pendingRowKey(row), row]),
);
const upserts: ReplicaRow[] = [];
for (const upsert of pending.upserts) {
for (const upsert of pending.upserts.filter(isStorable)) {
const row = this.materializeUpsert(upsert);
if (row) upserts.push(row);
else deletes.set(pendingRowKey(upsert), upsert);
@@ -1563,8 +1575,10 @@ export class ReplicaCache {
projectedTotal -= bytes;
projectedBytes.delete(serverId);
evicted.add(serverId);
this.invalidatedHosts.add(serverId);
if (this.storedRows.has(serverId)) await this.rowStore.deleteHost(serverId);
// Only after the delete commits: a failed eviction leaves the rows stored, and writers that
// check this set must keep their checkpoint in step with those rows.
this.invalidatedHosts.add(serverId);
this.removeStoredHost(serverId);
}
@@ -1053,19 +1053,12 @@ export class TerminalEmulatorRuntime {
if (!terminal) {
return;
}
terminal.textarea?.removeAttribute("virtualkeyboardpolicy");
if (input?.forceRefocus) {
terminal.blur();
}
terminal.focus();
}
suppressAutomaticKeyboard(): void {
// Android Chrome can reopen the keyboard during a drag after Back leaves the input
// focused. Manual policy prevents that without closing an already open keyboard.
this.terminal?.textarea?.setAttribute("virtualkeyboardpolicy", "manual");
}
blur(): void {
this.terminal?.blur();
}
@@ -32,7 +32,6 @@ it("translates mounted usage rows when the language changes", async () => {
<>
<UsageWindowBar
window={window}
forecastAt={null}
displayAs="used"
pinnable={false}
pinned={false}
@@ -52,44 +51,3 @@ it("translates mounted usage rows when the language changes", async () => {
expect(container.textContent).toContain("セッション70% 使用済み");
expect(container.textContent).toContain("クレジット");
});
const narrowReadingMs = Date.now();
const narrowForecastAt = new Date(narrowReadingMs).toISOString();
const narrowWindow: UsageWindow = {
id: "weekly",
label: "Weekly",
usedPct: 0.2,
durationSeconds: 604_800,
resetsAt: new Date(narrowReadingMs + 165.5 * 3_600_000).toISOString(),
};
it("keeps the French reset countdown and forecast apart in a narrow card", async () => {
await i18n.changeLanguage("fr");
container.style.width = "272px";
act(() =>
root.render(
<UsageWindowBar
window={narrowWindow}
forecastAt={narrowForecastAt}
displayAs="used"
pinnable={false}
pinned={false}
onTogglePin={ignorePin}
pinLabel=""
pinTestID=""
/>,
),
);
function textBounds(prefix: string) {
const element = Array.from(container.querySelectorAll("*")).find(
(node) => node.childElementCount === 0 && node.textContent.startsWith(prefix),
);
expect(element).toBeDefined();
const range = document.createRange();
range.selectNodeContents(element!);
return range.getBoundingClientRect();
}
expect(textBounds("se réinitialise").right).toBeLessThan(textBounds("~").left);
});
+2 -6
View File
@@ -70,7 +70,7 @@ export function UsageCard({
}) {
const { t } = useTranslation();
const isCompact = useIsCompactFormFactor();
const { refresh, refreshState } = useReportRefresh(serverId, entry, agentId);
const { refresh, refreshState } = useReportRefresh(serverId, entry.id, agentId);
// Where there is no hover the freshness is printed on the card; elsewhere the Refresh tooltip.
const showsFreshnessInline = isNative || isCompact || !refreshable;
const usage = entry.report;
@@ -176,7 +176,7 @@ function UsageCardBody({
refreshState: UsageRefresh;
}) {
const { t } = useTranslation();
const { windows, balances, details, retained, successfulAt, forecastAt, messages } = report;
const { windows, balances, details, retained, successfulAt, messages } = report;
const footer = entry.account.label ?? null;
return (
<>
@@ -194,7 +194,6 @@ function UsageCardBody({
entry={entry}
window={window}
retained={retained}
forecastAt={forecastAt}
display={display}
pinnable={pinnable}
/>
@@ -268,10 +267,8 @@ function CardWindowBar({
display,
pinnable,
retained,
forecastAt,
}: {
retained: boolean;
forecastAt: string | null;
entry: UsageReportEntry;
window: UsageWindow;
display: UsageDisplay;
@@ -288,7 +285,6 @@ function CardWindowBar({
<UsageWindowBar
window={window}
retained={retained}
forecastAt={forecastAt}
displayAs={display.displayAs}
pinnable={pinnable}
pinned={display.isPinned(pin)}
+8 -58
View File
@@ -2,7 +2,6 @@ import { afterEach, describe, expect, it } from "vitest";
import { i18n } from "@/i18n/i18next";
import {
resolveUsageReport,
markUsageRefreshFailure,
displayPercent,
resolveAgentUsageView,
replaceReport,
@@ -83,7 +82,7 @@ describe("resolveUsageView", () => {
expect(resolveUsageView({ ...base, query: undefined })).toEqual({ kind: "loading" });
expect(
resolveUsageView({ ...base, query: { data: [], error: null, isFetching: true } }),
).toEqual({ kind: "ready", reports: [], isRefreshing: true, refreshFailed: false });
).toEqual({ kind: "ready", reports: [], isRefreshing: true });
expect(
resolveUsageView({
...base,
@@ -91,19 +90,6 @@ describe("resolveUsageView", () => {
}),
).toEqual({ kind: "error", message: "boom" });
});
it("shows a failed Refresh all alongside the reports still on screen", () => {
const reports = [entry({})];
expect(
resolveUsageView({
hostLabel: "Laptop",
isConnected: true,
supportsUsage: true,
query: ready(reports),
refreshState: "failed",
}),
).toEqual({ kind: "ready", reports, isRefreshing: false, refreshFailed: true });
});
});
afterEach(async () => {
@@ -217,12 +203,15 @@ describe("displayPercent", () => {
describe("resolveUsageRefresh", () => {
it("is pending while a refresh runs, even after an earlier failure", () => {
expect(resolveUsageRefresh({ isPending: true, isError: true })).toBe("pending");
expect(resolveUsageRefresh({ isPending: true, error: new Error("boom") })).toBe("pending");
});
it("reports the request outcome independently of the reading", () => {
expect(resolveUsageRefresh({ isPending: false, isError: true })).toBe("failed");
expect(resolveUsageRefresh({ isPending: false, isError: false })).toBe("idle");
it("is failed after a refresh errors", () => {
expect(resolveUsageRefresh({ isPending: false, error: new Error("boom") })).toBe("failed");
});
it("is idle before and after a successful refresh", () => {
expect(resolveUsageRefresh({ isPending: false, error: null })).toBe("idle");
});
});
@@ -363,7 +352,6 @@ it("resolves retained usage and successful time without inventing old-daemon his
details: [],
planLabel: null,
successfulAt: success.fetchedAt,
forecastAt: null,
retained: true,
messages: ["Rate limited"],
});
@@ -373,7 +361,6 @@ it("resolves retained usage and successful time without inventing old-daemon his
details: [],
planLabel: null,
successfulAt: null,
forecastAt: null,
retained: false,
messages: ["Rate limited"],
});
@@ -383,48 +370,11 @@ it("resolves retained usage and successful time without inventing old-daemon his
details: [],
planLabel: null,
successfulAt: success.fetchedAt,
forecastAt: success.fetchedAt,
retained: false,
messages: [],
});
});
it("uses the quota observation time for pace and keeps the reading after a failed request", () => {
const success = entry({ windows: [{ id: "weekly", label: "Weekly", usedPct: 42 }] });
if (success.report.status !== "available") throw new Error("fixture must be available");
const observedAt = success.fetchedAt;
const successfulAt = "2026-01-01T00:15:00.000Z";
const report = { ...success, successfulAt, report: { ...success.report, observedAt } };
expect(resolveUsageReport(report, i18n.t)).toMatchObject({
successfulAt,
forecastAt: observedAt,
});
expect(resolveUsageReport({ ...report, forecastStale: true }, i18n.t)).toMatchObject({
windows: success.report.windows,
successfulAt,
forecastAt: null,
});
});
it("keeps cached quota and hides its forecast when Refresh all fails before a new report arrives", () => {
const before = entry({ windows: [{ id: "weekly", label: "Weekly", usedPct: 42 }] });
const other = entry({ sourceId: "other" });
const refreshedAt = "2026-01-01T00:06:00.000Z";
const streamed = { ...other, fetchedAt: refreshedAt };
const attempted = [before, other];
const failed = markUsageRefreshFailure([before, streamed], attempted)!;
expect(resolveUsageReport(failed[0]!, i18n.t)).toMatchObject({
forecastAt: null,
windows: before.report.status === "available" ? before.report.windows : [],
});
expect(resolveUsageReport(failed[1]!, i18n.t).forecastAt).toBe(refreshedAt);
expect(resolveUsageReport(upsertReport(failed, before)[0]!, i18n.t).forecastAt).toBeNull();
const retried = settleReports(failed, [{ ...before, fetchedAt: refreshedAt }, streamed]);
expect(resolveUsageReport(retried[0]!, i18n.t).forecastAt).toBe(refreshedAt);
});
it("orders failed polls by attempt time even when successful data is older", () => {
const success = entry({});
if (success.report.status !== "available") throw new Error("fixture must be available");
+7 -35
View File
@@ -38,31 +38,18 @@ export function usageWindowRowLabel(input: {
return `${input.pinLabel}, ${summary}`;
}
/** The outcome of a user-requested usage refresh. */
/** A user-requested refresh of one report. The previous report stays on screen throughout. */
export type UsageRefresh = "idle" | "pending" | "failed";
export function resolveUsageRefresh(mutation: {
isPending: boolean;
isError: boolean;
error: unknown;
}): UsageRefresh {
if (mutation.isPending) return "pending";
if (mutation.isError) return "failed";
if (mutation.error) return "failed";
return "idle";
}
/** Keep quota readings after a failed refresh and attach the outcome to the readings it targeted. */
export function markUsageRefreshFailure(
current: UsageReportEntry[] | undefined,
attempted: readonly UsageReportEntry[],
): UsageReportEntry[] | undefined {
const attemptedAt = new Map(attempted.map((entry) => [entry.id, entry.fetchedAt]));
return current?.map((entry) =>
attemptedAt.get(entry.id) === entry.fetchedAt && !entry.forecastStale
? { ...entry, forecastStale: true }
: entry,
);
}
/**
* A host's report list with one report swapped for its refreshed copy, in place.
* `null` means the daemon no longer knows the ID, so the report leaves the list.
@@ -73,9 +60,7 @@ export function replaceReport(
refreshed: UsageReportEntry | null,
): UsageReportEntry[] {
if (!refreshed) return reports.filter((report) => report.id !== reportId);
return reports.map((report) =>
report.id === reportId ? laterFetched(report, refreshed) : report,
);
return reports.map((report) => (report.id === reportId ? refreshed : report));
}
/**
@@ -83,9 +68,7 @@ export function replaceReport(
* started, so a Refresh that lands while it streams is newer than what the request still delivers.
*/
function laterFetched(shown: UsageReportEntry, arriving: UsageReportEntry): UsageReportEntry {
const shownAt = Date.parse(shown.fetchedAt);
const arrivingAt = Date.parse(arriving.fetchedAt);
return shownAt > arrivingAt || (shownAt === arrivingAt && shown.forecastStale) ? shown : arriving;
return Date.parse(shown.fetchedAt) > Date.parse(arriving.fetchedAt) ? shown : arriving;
}
/**
@@ -134,11 +117,10 @@ export function resolveUsageView(
isConnected: boolean;
supportsUsage: boolean;
query: UsageQueryState | undefined;
refreshState?: UsageRefresh;
},
t: TFunction = i18n.t,
): UsageView {
const { hostLabel, isConnected, supportsUsage, query, refreshState } = input;
const { hostLabel, isConnected, supportsUsage, query } = input;
if (!isConnected)
return {
kind: "unavailable",
@@ -153,12 +135,7 @@ export function resolveUsageView(
if (input.enabled === false)
return { kind: "off", message: t("providerUsage.off", { host: hostLabel }) };
if (query?.data) {
return {
kind: "ready",
reports: query.data,
isRefreshing: query.isFetching || refreshState === "pending",
refreshFailed: refreshState === "failed",
};
return { kind: "ready", reports: query.data, isRefreshing: query.isFetching };
}
if (query?.error) {
return {
@@ -273,12 +250,7 @@ export function resolveUsageReport(entry: UsageReportEntry, t: TFunction) {
// COMPAT(usageLoginErrors): added in v0.11.0, remove after 2027-04-05 once daemon floor >= v0.11.0.
else messages.push(usageProblemText(entry.report, t));
}
const forecastAt =
snapshot && !snapshot.retained && !entry.forecastStale
? (snapshot.report.observedAt ?? snapshot.successfulAt)
: null;
return {
forecastAt,
windows: snapshot?.report.windows ?? [],
balances: snapshot?.report.balances ?? [],
details: snapshot?.report.details ?? [],
-45
View File
@@ -1,45 +0,0 @@
import { describe, expect, it } from "vitest";
import { usagePace } from "./pace";
import type { UsageWindow } from "./types";
const day = "2026-11-20T";
const reading = (time: string) => `${day}${time}:00.000Z`;
const window: UsageWindow = {
id: "five_hour",
label: "Session",
durationSeconds: 18_000,
usedPct: 65,
resetsAt: reading("15:00"),
};
describe("usage pace", () => {
it("projects the limit from the sample time and keeps it fixed between readings", () => {
const sampledAt = reading("12:00");
const estimate = { kind: "runsOut", at: `${day}13:04:36.923Z` };
expect(usagePace(window, sampledAt, Date.parse(sampledAt))).toEqual(estimate);
expect(usagePace(window, sampledAt, Date.parse(reading("12:30")))).toEqual(estimate);
});
it("updates after a later reading and works with a remaining percentage", () => {
const close = reading("13:30");
const safe = reading("14:00");
const forecast = usagePace(window, close, Date.parse(close));
expect(forecast.kind).toBe("remaining");
if (forecast.kind === "remaining") expect(forecast.remainingAtResetPct).toBeCloseTo(7.14);
expect(
usagePace({ ...window, usedPct: undefined, remainingPct: 35 }, safe, Date.parse(safe)),
).toEqual({ kind: "remaining", remainingAtResetPct: 18.75 });
});
it("only forecasts with timing and an active, usable reading", () => {
const sampledAt = reading("12:00");
const now = Date.parse(sampledAt);
expect(usagePace({ ...window, durationSeconds: undefined }, sampledAt, now)).toEqual({
kind: "unknown",
});
expect(usagePace(window, null, now)).toEqual({ kind: "unknown" });
expect(usagePace(window, reading("10:01"), now)).toEqual({ kind: "unknown" });
expect(usagePace(window, sampledAt, Date.parse(window.resetsAt!))).toEqual({ kind: "unknown" });
expect(usagePace({ ...window, usedPct: 100 }, sampledAt, now)).toEqual({ kind: "reached" });
});
});
-45
View File
@@ -1,45 +0,0 @@
import { usedPercent } from "./model";
import type { UsageWindow } from "./types";
type UsagePace =
| { kind: "unknown" }
| { kind: "reached" }
| { kind: "runsOut"; at: string }
| { kind: "remaining"; remainingAtResetPct: number };
/** Estimate from the window's average pace as of the reading. The clock only expires the estimate. */
export function usagePace(window: UsageWindow, observedAt: string | null, now: number): UsagePace {
if (observedAt === null) return { kind: "unknown" };
const reset = Date.parse(window.resetsAt ?? "");
if (reset <= now) return { kind: "unknown" };
const used = usedPercent(window);
if (used != null && used >= 100) return { kind: "reached" };
const supplied = window.runsOutAt;
const suppliedAt = Date.parse(supplied ?? "");
if (supplied && Number.isFinite(suppliedAt) && (!Number.isFinite(reset) || suppliedAt < reset)) {
return { kind: "runsOut", at: supplied };
}
const duration = (window.durationSeconds ?? 0) * 1_000;
const sampled = Date.parse(observedAt);
const elapsed = sampled - (reset - duration);
if (
used == null ||
!Number.isFinite(used) ||
used < 0 ||
!Number.isFinite(elapsed) ||
sampled >= reset ||
elapsed < Math.max(60_000, duration * 0.01)
) {
return { kind: "unknown" };
}
const projectedAtReset = (used / elapsed) * duration;
if (projectedAtReset > 100) {
const runsOut = sampled + ((100 - used) / used) * elapsed;
return { kind: "runsOut", at: new Date(runsOut).toISOString() };
}
return { kind: "remaining", remainingAtResetPct: 100 - projectedAtReset };
}
+19 -42
View File
@@ -20,7 +20,6 @@ import { useSessionStore, type SessionState } from "@/stores/session-store";
import { useUsageSetting } from "./setting";
import { usageCopy } from "./copy";
import {
markUsageRefreshFailure,
replaceReport,
resolveAgentUsageView,
resolveUsageRefresh,
@@ -98,32 +97,17 @@ async function streamReports(input: {
return settleReports(queryClient.getQueryData<UsageReportEntry[]>(queryKey), reports);
}
async function listReports(
function listReports(
queryClient: QueryClient,
serverId: string,
forceRefresh = false,
): Promise<UsageReportEntry[]> {
const queryKey = usageReportsQueryKey(serverId);
const attempted = queryClient.getQueryData<UsageReportEntry[]>(queryKey) ?? [];
try {
return await streamReports({ queryClient, queryKey, serverId, forceRefresh });
} catch (error) {
recordUsageRefreshFailure(queryClient, queryKey, attempted);
throw error;
}
}
function recordUsageRefreshFailure(
queryClient: QueryClient,
queryKey: QueryKey,
attempted: readonly UsageReportEntry[],
): void {
const { dataUpdatedAt } = queryClient.getQueryState(queryKey) ?? {};
queryClient.setQueryData<UsageReportEntry[]>(
queryKey,
(current) => markUsageRefreshFailure(current, attempted),
{ updatedAt: dataUpdatedAt },
);
return streamReports({
queryClient,
queryKey: usageReportsQueryKey(serverId),
serverId,
forceRefresh,
});
}
async function getReport(
@@ -174,12 +158,9 @@ export function useHostUsage(serverId: string): { view: UsageView; refresh: () =
dataShape: "value",
staleTimeMs: REPORTS_STALE_TIME_MS,
});
const mutation = useMutation({
mutationKey: [...usageReportsQueryKey(serverId), "refresh"],
mutationFn: (hostId: string) => refreshReports(queryClient, hostId),
});
const { mutate, variables } = mutation;
const refresh = useCallback(() => mutate(serverId), [mutate, serverId]);
const refresh = useCallback(() => {
void refreshReports(queryClient, serverId).catch(() => undefined);
}, [queryClient, serverId]);
const { t } = useTranslation();
const hostLabel = useHosts().find((host) => host.serverId === serverId)?.label ?? serverId;
const view = resolveUsageView(
@@ -189,7 +170,6 @@ export function useHostUsage(serverId: string): { view: UsageView; refresh: () =
isConnected,
supportsUsage: isSupported,
query: toQueryState(query),
refreshState: variables === serverId ? resolveUsageRefresh(mutation) : "idle",
},
t,
);
@@ -285,26 +265,23 @@ export function useUsageHosts(): UsageHost[] {
*/
export function useReportRefresh(
serverId: string,
entry: UsageReportEntry,
reportId: string,
agentId?: string,
): { refresh: () => void; refreshState: UsageRefresh } {
const queryClient = useQueryClient();
const usageScopeKey = useAgentUsageScopeKey(serverId, agentId);
const queryKey =
agentId === undefined
? usageReportsQueryKey(serverId)
: agentUsageQueryKey(serverId, agentId, usageScopeKey);
const mutation = useMutation({
mutationKey: [...queryKey, "refresh", entry.id],
mutationFn: (attempted: UsageReportEntry) => getReport(serverId, attempted.id, true, agentId),
onSuccess: (report, attempted) => {
queryClient.setQueryData<UsageReportEntry[]>(queryKey, (reports) =>
reports ? replaceReport(reports, attempted.id, report) : reports,
mutationFn: () => getReport(serverId, reportId, true, agentId),
onSuccess: (report) => {
queryClient.setQueryData<UsageReportEntry[]>(
agentId === undefined
? usageReportsQueryKey(serverId)
: agentUsageQueryKey(serverId, agentId, usageScopeKey),
(reports) => (reports ? replaceReport(reports, reportId, report) : reports),
);
},
onError: (_error, attempted) => recordUsageRefreshFailure(queryClient, queryKey, [attempted]),
});
const { mutate } = mutation;
const refresh = useCallback(() => mutate(entry), [mutate, entry]);
const refresh = useCallback(() => mutate(), [mutate]);
return { refresh, refreshState: resolveUsageRefresh(mutation) };
}
+13 -5
View File
@@ -3,21 +3,24 @@ import { StyleSheet } from "react-native-unistyles";
/**
* The reset data of a window or balance: the countdown first, then the exact time. When the line
* is too narrow the exact time truncates and the countdown wraps within its column.
* is too narrow the exact time gives way (truncates) and the countdown stays whole.
*/
export function UsageResetLine({
countdown,
exactTime,
atRisk = false,
testID,
}: {
countdown: string | null;
exactTime: string | null;
/** The countdown is a runs-out warning rather than a reset. */
atRisk?: boolean;
testID?: string;
}) {
if (!countdown) return null;
return (
<View style={styles.line} testID={testID}>
<Text style={[styles.text, styles.countdown]}>{countdown}</Text>
<Text style={atRisk ? styles.atRisk : styles.text}>{countdown}</Text>
{exactTime ? (
<Text style={[styles.text, styles.exactTime]} numberOfLines={1} ellipsizeMode="tail">
{`\u00a0·\u00a0${exactTime}`}
@@ -28,13 +31,18 @@ export function UsageResetLine({
}
const styles = StyleSheet.create((theme) => ({
line: { flexDirection: "row", alignItems: "baseline" },
line: { flexDirection: "row", alignItems: "center" },
text: {
flexShrink: 0,
color: theme.colors.foregroundMuted,
fontSize: theme.fontSize.sm,
fontWeight: theme.fontWeight.normal,
},
countdown: { maxWidth: "100%" },
exactTime: { flexShrink: 1, minWidth: 0 },
atRisk: {
flexShrink: 0,
color: theme.colors.statusDanger,
fontSize: theme.fontSize.sm,
fontWeight: theme.fontWeight.normal,
},
exactTime: { flexShrink: 1 },
}));
+3 -9
View File
@@ -1,12 +1,6 @@
import type {
ProviderUsageTone,
UsageReportEntry as WireUsageReportEntry,
} from "@getpaseo/protocol/messages";
import type { ProviderUsageTone, UsageReportEntry } from "@getpaseo/protocol/messages";
export interface UsageReportEntry extends WireUsageReportEntry {
/** A refresh failed while this reading was cached. */
forecastStale?: true;
}
export type { UsageReportEntry };
export type UsageReport = UsageReportEntry["report"];
export type UsageTone = ProviderUsageTone;
export type AvailableUsageReport = Extract<UsageReport, { status: "available" }>;
@@ -20,4 +14,4 @@ export type UsageView =
| { kind: "unavailable"; message: string }
| { kind: "loading" }
| { kind: "error"; message: string }
| { kind: "ready"; reports: UsageReportEntry[]; isRefreshing: boolean; refreshFailed: boolean };
| { kind: "ready"; reports: UsageReportEntry[]; isRefreshing: boolean };
+5 -13
View File
@@ -84,18 +84,11 @@ export function UsageBody({
);
}
return (
<View style={styles.reports}>
{view.refreshFailed ? (
<Alert size="sm" variant="error" title={t("providerUsage.refreshFailed")} />
) : null}
{view.reports.length === 0 ? (
<UsageMessage text={t("providerUsage.empty")} />
) : (
<UsageList serverId={serverId} reports={view.reports} display={display} />
)}
</View>
);
if (view.reports.length === 0) {
return <UsageMessage text={t("providerUsage.empty")} />;
}
return <UsageList serverId={serverId} reports={view.reports} display={display} />;
}
export function UsageMessage({ text }: { text: string }) {
@@ -107,7 +100,6 @@ export function UsageMessage({ text }: { text: string }) {
}
const styles = StyleSheet.create((theme) => ({
reports: { gap: theme.spacing[3] },
emptyCard: {
padding: theme.spacing[4],
alignItems: "center",
+22 -71
View File
@@ -1,4 +1,3 @@
import type { TFunction } from "i18next";
import { Pin } from "lucide-react-native";
import { useMemo } from "react";
import { useTranslation } from "react-i18next";
@@ -7,7 +6,6 @@ import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import {
formatDisplayPct,
formatPct,
formatProviderUsageLabel,
formatResetLabel,
formatResetTime,
@@ -15,9 +13,9 @@ import {
} from "./format";
import { UsageMeter } from "./meter";
import { displayPercent, usageWindowRowLabel } from "./model";
import { usagePace } from "./pace";
import { UsageResetLine } from "./reset-line";
import type { UsageDisplayAs } from "./preferences";
import { windowTone } from "./tone";
import type { UsageTone, UsageWindow } from "./types";
import { useRelativeTimeTick } from "./use-relative-time-tick";
@@ -30,10 +28,8 @@ export function UsageWindowBar({
pinLabel,
pinTestID,
retained = false,
forecastAt,
}: {
retained?: boolean;
forecastAt: string | null;
window: UsageWindow;
displayAs: UsageDisplayAs;
/** Whether the row pins the window to the sidebar. When false the row is a plain bar. */
@@ -46,11 +42,19 @@ export function UsageWindowBar({
}) {
const { t, i18n } = useTranslation();
const shownPct = displayPercent(window, displayAs);
const tone = windowTone(window);
const now = useRelativeTimeTick({ enabled: window.runsOutAt != null || window.resetsAt != null });
const pace = usagePace(window, forecastAt, now);
const forecast = formatPace(pace, now, t);
const countdown = formatResetLabel(window.resetsAt, retained, now, t);
const exactTime = formatResetTime(window.resetsAt, now, t);
const isAtRisk =
window.runsOutAt != null &&
window.shortfallPct != null &&
(!retained || Date.parse(window.runsOutAt) > now);
const countdown = isAtRisk
? formatRunsOutLabel(window.runsOutAt, now, t)
: formatResetLabel(window.resetsAt, retained, now, t);
// The exact time belongs to the reset; beside a runs-out warning it would read as the moment
// the quota runs out.
const exactTime = isAtRisk ? null : formatResetTime(window.resetsAt, now, t);
const value =
shownPct != null ? formatDisplayPct(shownPct, displayAs, i18n.resolvedLanguage, t) : "—";
@@ -60,8 +64,9 @@ export function UsageWindowBar({
value,
countdown,
exactTime,
forecast,
isAtRisk,
percent: shownPct ?? 0,
tone,
pinned,
};
@@ -81,7 +86,7 @@ export function UsageWindowBar({
accessibilityLabel={usageWindowRowLabel({
pinLabel,
value,
trailing: [countdown, exactTime, forecast?.label].filter(Boolean).join(" · "),
trailing: [countdown, exactTime].filter(Boolean).join(" · "),
})}
accessibilityState={accessibilityState}
aria-checked={pinned}
@@ -98,8 +103,9 @@ function WindowRowContent({
value,
countdown,
exactTime,
forecast,
isAtRisk,
percent,
tone,
pinnable,
pinned,
}: {
@@ -107,8 +113,9 @@ function WindowRowContent({
value: string;
countdown: string | null;
exactTime: string | null;
forecast: PaceLabel | null;
isAtRisk: boolean;
percent: number;
tone: UsageTone;
pinnable: boolean;
pinned: boolean;
}) {
@@ -123,51 +130,12 @@ function WindowRowContent({
</Text>
{pinnable ? <UsagePinGlyph pinned={pinned} /> : null}
</View>
<UsageMeter percent={percent} tone={forecast?.tone ?? "default"} />
{countdown || forecast ? (
<View style={styles.timingRow}>
<View style={styles.resetTiming}>
<UsageResetLine countdown={countdown} exactTime={exactTime} />
</View>
{forecast ? <Text style={styles.forecast(forecast.tone)}>{forecast.label}</Text> : null}
</View>
) : null}
<UsageMeter percent={percent} tone={tone} />
<UsageResetLine countdown={countdown} exactTime={exactTime} atRisk={isAtRisk} />
</>
);
}
interface PaceLabel {
label: string;
tone: UsageTone;
}
function formatPace(
pace: ReturnType<typeof usagePace>,
now: number,
t: TFunction,
): PaceLabel | null {
switch (pace.kind) {
case "reached":
return { label: t("providerUsage.timing.limitReached"), tone: "danger" };
case "runsOut": {
const label =
Date.parse(pace.at) <= now
? t("providerUsage.timing.mayHaveRunOut")
: formatRunsOutLabel(pace.at, now, t);
return label ? { label, tone: "danger" } : null;
}
case "remaining":
return {
label: t("providerUsage.timing.projectedLeftAtReset", {
percentage: formatPct(pace.remainingAtResetPct),
}),
tone: pace.remainingAtResetPct <= 10 ? "warning" : "default",
};
case "unknown":
return null;
}
}
const ThemedPin = withUnistyles(Pin);
function UsagePinGlyph({ pinned }: { pinned: boolean }) {
@@ -199,23 +167,6 @@ function UsagePinGlyph({ pinned }: { pinned: boolean }) {
}
const styles = StyleSheet.create((theme) => ({
timingRow: {
flexDirection: "row",
alignItems: "flex-start",
gap: theme.spacing[2],
},
resetTiming: { flex: 1, minWidth: 0 },
forecast: (tone: UsageTone) => ({
color: {
danger: theme.colors.statusDanger,
warning: theme.colors.statusWarning,
default: theme.colors.foregroundMuted,
ok: theme.colors.statusSuccess,
}[tone],
fontSize: theme.fontSize.sm,
maxWidth: "50%",
textAlign: "right",
}),
row: { gap: 3, paddingVertical: theme.spacing[1.5] },
pin: { width: 12, alignItems: "center" },
tooltipText: { color: theme.colors.popoverForeground, fontSize: theme.fontSize.sm },
+7 -7
View File
@@ -96,12 +96,12 @@ test.each([
])(
"duration %s owns the window's identity and both names",
(durationSeconds, id, label, shortLabel) => {
const window = windowFromReportedDuration({
durationSeconds: durationSeconds as number | null,
unknown: { id: "primary", label: "Primary limit", shortLabel: "" },
utilizationPct: 11,
});
expect(window).toMatchObject({ id, label, shortLabel, usedPct: 11 });
expect(window.durationSeconds).toBe(durationSeconds ?? undefined);
expect(
windowFromReportedDuration({
durationSeconds: durationSeconds as number | null,
unknown: { id: "primary", label: "Primary limit", shortLabel: "" },
utilizationPct: 11,
}),
).toMatchObject({ id, label, shortLabel, usedPct: 11 });
},
);
+5 -11
View File
@@ -16,8 +16,6 @@ export interface UsageWindow {
usedPct?: number | null;
remainingPct?: number | null;
resetsAt?: string | null;
/** Full length of the quota window when known. */
durationSeconds?: number;
runsOutAt?: string | null;
shortfallPct?: number | null;
tone?: "default" | "ok" | "warning" | "danger";
@@ -50,8 +48,6 @@ export type UsageReport =
| {
status: "available";
planLabel?: string;
/** When the provider measured the quota, if the report returns a previous reading. */
observedAt?: string;
windows: UsageWindow[];
balances?: UsageBalance[];
details?: UsageDetail[];
@@ -100,7 +96,6 @@ export function windowFromUsedPct(input: {
shortLabel?: string;
summary?: boolean;
utilizationPct: number | null | undefined;
durationSeconds?: number;
resetsAt?: string | null;
tone?: UsageWindow["tone"];
}): UsageWindow {
@@ -112,7 +107,6 @@ export function windowFromUsedPct(input: {
remainingPct: usedPct === null ? null : Math.max(0, 100 - usedPct),
resetsAt: input.resetsAt ?? null,
};
if (input.durationSeconds !== undefined) window.durationSeconds = input.durationSeconds;
if (input.shortLabel !== undefined) window.shortLabel = input.shortLabel;
if (input.summary) window.summary = true;
if (input.tone) window.tone = input.tone;
@@ -135,10 +129,11 @@ export function windowFromReportedDuration(input: {
summary?: boolean;
tone?: UsageWindow["tone"];
}): UsageWindow {
const reported = input.durationSeconds;
const duration =
reported !== null && Number.isFinite(reported) && reported > 0 ? reported : undefined;
const name = duration === undefined ? input.unknown : durationWindowName(duration);
const duration = input.durationSeconds;
const name =
duration !== null && Number.isFinite(duration) && duration > 0
? durationWindowName(duration)
: input.unknown;
const scope = input.scope;
return windowFromUsedPct({
id: scope ? `${scope.id}:${name.id}` : name.id,
@@ -147,7 +142,6 @@ export function windowFromReportedDuration(input: {
? `${scope.label}${name.shortLabel ? ` ${name.shortLabel}` : ""}`
: name.shortLabel,
utilizationPct: input.utilizationPct,
durationSeconds: duration,
resetsAt: input.resetsAt,
summary: input.summary,
tone: input.tone,
-2
View File
@@ -6992,7 +6992,6 @@ export const ProviderUsageWindowSchema = z.object({
usedPct: z.number().nullable().optional(),
remainingPct: z.number().nullable().optional(),
resetsAt: z.string().nullable().optional(),
durationSeconds: z.number().optional(),
runsOutAt: z.string().nullable().optional(),
shortfallPct: z.number().nullable().optional(),
tone: ProviderUsageToneSchema.optional(),
@@ -7055,7 +7054,6 @@ export const UsageProblemSchema = z.discriminatedUnion("kind", [
const AvailableUsageReportSchema = z.object({
status: z.literal("available"),
planLabel: z.string().optional(),
observedAt: z.string().optional(),
windows: z.array(ProviderUsageWindowSchema),
balances: z.array(ProviderUsageBalanceSchema).optional(),
details: z.array(ProviderUsageDetailSchema).optional(),
@@ -56,17 +56,6 @@ function shortWindow(window: string): string {
return trimmed;
}
function windowDurationSeconds(window: string): number | undefined {
switch (window.trim().toLowerCase()) {
case "5h":
return 5 * 3600;
case "weekly":
return 7 * 86400;
default:
return undefined;
}
}
function shortGroupName(name: string): string {
return name
.trim()
@@ -140,7 +129,6 @@ export class Usage {
shortLabel: formatShortLabel(group.name, bucket.window, includeGroup),
summary: !bucket.disabled && bucket.window === "weekly",
utilizationPct: used,
durationSeconds: windowDurationSeconds(bucket.window),
resetsAt: bucket.disabled ? null : bucket.reset_time,
tone: used === null ? "default" : toneFromUsedPct(used),
}),
@@ -263,7 +263,6 @@ function unscopedWindows(resp: ClaudeUsageResponse): UsageWindow[] {
shortLabel: spec.shortLabel,
summary: spec.summary,
utilizationPct: window.utilization,
durationSeconds: spec.field === "five_hour" ? 5 * 3600 : 7 * 86400,
resetsAt: window.resets_at ?? null,
tone: toneFromUsedPct(window.utilization),
}),
@@ -284,7 +283,6 @@ function scopedWindows(limits: ScopedLimit[]): UsageWindow[] {
label: `Weekly \u00b7 ${limit.name}`,
shortLabel: `wk ${limit.name}`,
utilizationPct: limit.usedPct,
durationSeconds: 7 * 86400,
resetsAt: limit.resetsAt,
tone: toneFromUsedPct(limit.usedPct),
});
+1 -3
View File
@@ -86,10 +86,8 @@ export class Usage {
try {
const { usage } = await this.read(account, launch);
if (!usage) return unavailable({ kind: "no_quota", detail: "No usage quota reported" });
const observedAt = new Date(usage.observedAtMs).toISOString();
return {
status: "available",
observedAt,
planLabel: usage.tier,
windows: [
windowFromReportedDuration({
@@ -114,7 +112,7 @@ export class Usage {
{
id: "observed",
label: "Observed",
value: observedAt,
value: new Date(usage.observedAtMs).toISOString(),
},
],
};
+1 -5
View File
@@ -1505,7 +1505,6 @@ for (const usage of [
expect(report).toMatchObject({
status: "available",
planLabel: "Pro",
observedAt: new Date(usage.usage.observedAtMs).toISOString(),
windows: [
{
id: "five_hour",
@@ -1801,10 +1800,7 @@ test("Muse reports belong only to the session's account and remain available glo
for (const [index, agentId] of ["muse-home", "muse-work"].entries()) {
const reports = await registry.listReports({ agentId });
expect(reports.map((report) => report.id)).toEqual([accountIds[index]]);
expect(reports[0]!.report).toMatchObject({
status: "available",
observedAt: "2023-11-14T22:13:20.000Z",
});
expect(reports[0]!.report.status).toBe("available");
}
expect(await registry.listReports({ agentId: "muse-unknown" })).toEqual([]);
expect((await registry.listReports()).map((report) => report.id)).toEqual(accountIds);
+1 -5
View File
@@ -616,11 +616,7 @@ For numeric durations, use `windowFromReportedDuration()` from
`@getpaseo/plugin/server/usage` (Paseo 0.11+). Pass the reported seconds or `null`, a neutral
`unknown` identity and name, and an optional stable quota `scope`. The helper derives the ID,
label, and short label together; it accepts no duration-label override. For named API periods,
use `windowFromUsedPct()` with names justified by that field. Set `durationSeconds` when
the period has a known fixed length. Usage Details uses it with the reset time and the
latest reading to estimate whether the quota will last until reset. If the source returns
a previous reading, include its measurement time as an ISO timestamp in the report’s
`observedAt` field.
use `windowFromUsedPct()` with names justified by that field.
A window ID identifies a quota scope and period, never its response position, utilization, or
reset instant. Scope model-specific quotas by the provider's stable feature ID, falling back to