mirror of
https://github.com/getpaseo/paseo.git
synced 2026-11-20 23:35:27 +00:00
Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
27c126d352 | ||
|
|
7e3826ad6c |
+2
-7
@@ -582,17 +582,12 @@ 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. 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,
|
||||
checkpoint are also applied in one transaction. 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. 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
|
||||
The cache is capped at 32 MiB and evicts whole hosts in least-recently-written order. 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,14 +206,13 @@ async function simulateDamagedLegacyDirectoryCache(
|
||||
return;
|
||||
}
|
||||
const stored = JSON.parse(checkpoint.payload);
|
||||
// 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) {
|
||||
// Accept either writer so this fixture also reproduces on the unfixed client.
|
||||
const cursors = stored.version === 1 ? stored.cursors : stored;
|
||||
if (!cursors.workspaces?.generation) {
|
||||
transaction.abort();
|
||||
return;
|
||||
}
|
||||
store.put({ ...checkpoint, payload: JSON.stringify({ version: 1, cursors }) });
|
||||
store.put({ ...checkpoint, payload: JSON.stringify(cursors) });
|
||||
for (const row of rows) {
|
||||
if (
|
||||
row.serverId === serverId &&
|
||||
|
||||
@@ -503,6 +503,34 @@ 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);
|
||||
@@ -531,6 +559,26 @@ 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") {
|
||||
@@ -570,6 +618,20 @@ 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) {
|
||||
|
||||
@@ -2,13 +2,14 @@ import { tmpdir } from "node:os";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import path from "node:path";
|
||||
import type { Page } from "@playwright/test";
|
||||
import type { UsageReportEntry } from "@getpaseo/protocol/messages";
|
||||
import type { UsageReport, 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 {
|
||||
@@ -45,6 +46,7 @@ import {
|
||||
refreshAllUsage,
|
||||
togglePin,
|
||||
usageItem,
|
||||
usageModal,
|
||||
} from "../support/helpers/usage-sidebar-item";
|
||||
|
||||
const emptyHome = path.join(tmpdir(), `paseo-usage-empty-${randomUUID()}`);
|
||||
@@ -865,6 +867,106 @@ 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,13 +185,15 @@ 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(Date.now() - 2 * 60 * 60_000).toISOString(),
|
||||
expiresAt: new Date(fetchedAt - 2 * 60 * 60_000).toISOString(),
|
||||
refreshedBy: "claude",
|
||||
},
|
||||
},
|
||||
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
useRef,
|
||||
type CSSProperties,
|
||||
type MouseEvent as ReactMouseEvent,
|
||||
type PointerEvent as ReactPointerEvent,
|
||||
type Ref,
|
||||
} from "react";
|
||||
import type { DOMProps } from "expo/dom";
|
||||
@@ -63,6 +64,12 @@ 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,
|
||||
@@ -553,10 +560,46 @@ export default function TerminalEmulator({
|
||||
});
|
||||
}, []);
|
||||
|
||||
const handleRootPointerDown = useCallback(() => {
|
||||
onFocus?.();
|
||||
runtimeRef.current?.focus();
|
||||
}, [onFocus]);
|
||||
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 handleRootContextMenu = useCallback(
|
||||
(event: ReactMouseEvent) => {
|
||||
@@ -588,6 +631,9 @@ 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} />
|
||||
|
||||
@@ -2323,6 +2323,9 @@ export const ar: TranslationResources = {
|
||||
resetsIn: "تتم إعادة التعيين خلال {{duration}}",
|
||||
resetsAtWeekday: "{{weekday}} {{time}}",
|
||||
resetsAtDate: "{{date}}، {{time}}",
|
||||
projectedLeftAtReset: "نحو {{percentage}} متبقية عند إعادة التعيين",
|
||||
limitReached: "تم بلوغ الحد",
|
||||
mayHaveRunOut: "ربما نفدت الحصة",
|
||||
runsOutNow: "ينفد الآن",
|
||||
runsOutIn: "ينفد خلال {{duration}}",
|
||||
justNow: "الآن",
|
||||
|
||||
@@ -2333,6 +2333,9 @@ 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",
|
||||
|
||||
@@ -2354,6 +2354,9 @@ 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",
|
||||
|
||||
@@ -2355,6 +2355,9 @@ 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",
|
||||
|
||||
@@ -2328,6 +2328,9 @@ export const ja: TranslationResources = {
|
||||
resetsIn: "{{duration}}後にリセット",
|
||||
resetsAtWeekday: "{{weekday}} {{time}}",
|
||||
resetsAtDate: "{{date}} {{time}}",
|
||||
projectedLeftAtReset: "リセット時に約{{percentage}}残る見込み",
|
||||
limitReached: "上限に達しました",
|
||||
mayHaveRunOut: "上限に達した可能性があります",
|
||||
runsOutNow: "まもなく上限に到達",
|
||||
runsOutIn: "{{duration}}後に上限に到達",
|
||||
justNow: "たった今",
|
||||
|
||||
@@ -2316,6 +2316,9 @@ export const ko: TranslationResources = {
|
||||
resetsIn: "{{duration}} 후 재설정",
|
||||
resetsAtWeekday: "{{weekday}} {{time}}",
|
||||
resetsAtDate: "{{date}} {{time}}",
|
||||
projectedLeftAtReset: "초기화 시 약 {{percentage}} 남을 예정",
|
||||
limitReached: "한도에 도달함",
|
||||
mayHaveRunOut: "한도를 소진했을 수 있음",
|
||||
runsOutNow: "지금 한도에 도달",
|
||||
runsOutIn: "{{duration}} 후 한도에 도달",
|
||||
justNow: "방금",
|
||||
|
||||
@@ -2339,6 +2339,9 @@ 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",
|
||||
|
||||
@@ -2341,6 +2341,9 @@ export const ru: TranslationResources = {
|
||||
resetsIn: "сброс через {{duration}}",
|
||||
resetsAtWeekday: "{{weekday}} {{time}}",
|
||||
resetsAtDate: "{{date}}, {{time}}",
|
||||
projectedLeftAtReset: "К сбросу останется ~{{percentage}}",
|
||||
limitReached: "Лимит исчерпан",
|
||||
mayHaveRunOut: "Лимит мог уже исчерпаться",
|
||||
runsOutNow: "закончится сейчас",
|
||||
runsOutIn: "закончится через {{duration}}",
|
||||
justNow: "только что",
|
||||
|
||||
@@ -2282,6 +2282,9 @@ export const zhCN: TranslationResources = {
|
||||
resetsIn: "将在 {{duration}}后重置",
|
||||
resetsAtWeekday: "{{weekday}} {{time}}",
|
||||
resetsAtDate: "{{date}} {{time}}",
|
||||
projectedLeftAtReset: "重置时约剩余 {{percentage}}",
|
||||
limitReached: "已达到上限",
|
||||
mayHaveRunOut: "额度可能已用完",
|
||||
runsOutNow: "即将用尽",
|
||||
runsOutIn: "将在 {{duration}}后用尽",
|
||||
justNow: "刚刚",
|
||||
|
||||
@@ -10,10 +10,7 @@ import type {
|
||||
DaemonClient,
|
||||
WorkspaceLabelListPayload,
|
||||
} from "@getpaseo/client/internal/daemon-client";
|
||||
import type {
|
||||
SessionOutboundMessage,
|
||||
WorkspaceDescriptorPayload,
|
||||
} from "@getpaseo/protocol/messages";
|
||||
import type { SessionOutboundMessage } from "@getpaseo/protocol/messages";
|
||||
import {
|
||||
normalizeProjectDescriptor,
|
||||
normalizeWorkspaceDescriptor,
|
||||
@@ -1670,187 +1667,6 @@ 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);
|
||||
if (this.extendsRefreshedBaseline(source)) this.noteLiveCursor("agents", delta);
|
||||
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" && this.extendsRefreshedBaseline(source))
|
||||
if (delta.kind !== "script_status")
|
||||
this.noteLiveCursor(
|
||||
"projectId" in delta || "project" in delta ? "projects" : "workspaces",
|
||||
delta,
|
||||
@@ -308,20 +308,6 @@ 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();
|
||||
@@ -580,16 +566,24 @@ export class DirectorySync {
|
||||
input: { subscribe?: boolean } | undefined,
|
||||
loadDirectoryCache: boolean,
|
||||
): Promise<void> {
|
||||
if (loadDirectoryCache) {
|
||||
this.primeWorkspaceTransactionForCacheLoad();
|
||||
await this.loadCachedDirectory();
|
||||
}
|
||||
if (loadDirectoryCache) await this.loadCachedDirectory();
|
||||
const onlineConnection = this.getOnlineConnection();
|
||||
if (!onlineConnection) return;
|
||||
const { client, source } = onlineConnection;
|
||||
const transaction = this.workspaceTransactions.begin(source, () =>
|
||||
this.createWorkspaceRefreshSnapshot(),
|
||||
);
|
||||
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(),
|
||||
};
|
||||
});
|
||||
try {
|
||||
await this.waitForSessionMetadata(client, source);
|
||||
const serverInfo = useSessionStore.getState().sessions[this.serverId]?.serverInfo;
|
||||
@@ -813,31 +807,6 @@ 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,9 +37,6 @@ 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}`;
|
||||
@@ -71,7 +68,6 @@ 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) ?? [];
|
||||
@@ -95,7 +91,6 @@ 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);
|
||||
}
|
||||
|
||||
@@ -441,49 +436,40 @@ describe("ReplicaCache", () => {
|
||||
await expectLegacyWorkspaceRefresh(cached);
|
||||
});
|
||||
|
||||
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)),
|
||||
},
|
||||
],
|
||||
});
|
||||
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),
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
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();
|
||||
@@ -1116,113 +1102,6 @@ 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, {
|
||||
|
||||
@@ -397,19 +397,15 @@ const DirectoryCheckpointSchema = z.strictObject({
|
||||
agents: DirectoryCursorSchema.optional(),
|
||||
});
|
||||
|
||||
// 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;
|
||||
|
||||
// Old checkpoints could describe a baseline that an overlapping refresh had discarded.
|
||||
// Revalidate directory contents once without evicting cached rows or timelines.
|
||||
const StoredDirectoryCheckpointSchema = z.strictObject({
|
||||
version: z.literal(DIRECTORY_CHECKPOINT_VERSION),
|
||||
version: z.literal(1),
|
||||
cursors: DirectoryCheckpointSchema,
|
||||
});
|
||||
|
||||
function serializeDirectoryCheckpoint(cursors: DirectoryCheckpoint) {
|
||||
return { version: DIRECTORY_CHECKPOINT_VERSION, cursors };
|
||||
return { version: 1 as const, cursors };
|
||||
}
|
||||
|
||||
function deserializeDirectoryCheckpoint(payload: string): DirectoryCheckpoint {
|
||||
@@ -972,7 +968,6 @@ 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;
|
||||
@@ -1114,7 +1109,11 @@ export class ReplicaCache {
|
||||
private async deleteInvalidRow(row: ReplicaRow): Promise<void> {
|
||||
const invalidEntity = directoryEntityForRow(row);
|
||||
if (!invalidEntity) {
|
||||
await this.applyRepair(row.serverId, { upserts: [], deletes: [row] });
|
||||
const changes = { upserts: [], deletes: [row] } satisfies ReplicaRowChanges;
|
||||
await this.queueOperation(async () => {
|
||||
await this.rowStore.apply(changes);
|
||||
this.applyStoredChanges(changes);
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1145,7 +1144,10 @@ export class ReplicaCache {
|
||||
]
|
||||
: [],
|
||||
};
|
||||
await this.applyRepair(row.serverId, changes);
|
||||
await this.queueOperation(async () => {
|
||||
await this.rowStore.apply(changes);
|
||||
this.applyStoredChanges(changes);
|
||||
});
|
||||
}
|
||||
|
||||
private async repairInvalidDirectoryRows(
|
||||
@@ -1168,16 +1170,9 @@ export class ReplicaCache {
|
||||
]
|
||||
: [],
|
||||
};
|
||||
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);
|
||||
await this.queueOperation(async () => {
|
||||
await this.rowStore.apply(changes);
|
||||
this.applyStoredChanges(changes);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1187,6 +1182,7 @@ 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);
|
||||
@@ -1416,17 +1412,9 @@ export class ReplicaCache {
|
||||
}
|
||||
|
||||
private materializePendingChanges(pending: PendingReplicaChanges): ReplicaRowChanges {
|
||||
// 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 deletes = new Map(pending.deletes.map((row) => [pendingRowKey(row), row]));
|
||||
const upserts: ReplicaRow[] = [];
|
||||
for (const upsert of pending.upserts.filter(isStorable)) {
|
||||
for (const upsert of pending.upserts) {
|
||||
const row = this.materializeUpsert(upsert);
|
||||
if (row) upserts.push(row);
|
||||
else deletes.set(pendingRowKey(upsert), upsert);
|
||||
@@ -1575,10 +1563,8 @@ export class ReplicaCache {
|
||||
projectedTotal -= bytes;
|
||||
projectedBytes.delete(serverId);
|
||||
evicted.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);
|
||||
if (this.storedRows.has(serverId)) await this.rowStore.deleteHost(serverId);
|
||||
this.removeStoredHost(serverId);
|
||||
}
|
||||
|
||||
|
||||
@@ -1053,12 +1053,19 @@ 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,6 +32,7 @@ it("translates mounted usage rows when the language changes", async () => {
|
||||
<>
|
||||
<UsageWindowBar
|
||||
window={window}
|
||||
forecastAt={null}
|
||||
displayAs="used"
|
||||
pinnable={false}
|
||||
pinned={false}
|
||||
@@ -51,3 +52,44 @@ 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);
|
||||
});
|
||||
|
||||
@@ -70,7 +70,7 @@ export function UsageCard({
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const isCompact = useIsCompactFormFactor();
|
||||
const { refresh, refreshState } = useReportRefresh(serverId, entry.id, agentId);
|
||||
const { refresh, refreshState } = useReportRefresh(serverId, entry, 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, messages } = report;
|
||||
const { windows, balances, details, retained, successfulAt, forecastAt, messages } = report;
|
||||
const footer = entry.account.label ?? null;
|
||||
return (
|
||||
<>
|
||||
@@ -194,6 +194,7 @@ function UsageCardBody({
|
||||
entry={entry}
|
||||
window={window}
|
||||
retained={retained}
|
||||
forecastAt={forecastAt}
|
||||
display={display}
|
||||
pinnable={pinnable}
|
||||
/>
|
||||
@@ -267,8 +268,10 @@ function CardWindowBar({
|
||||
display,
|
||||
pinnable,
|
||||
retained,
|
||||
forecastAt,
|
||||
}: {
|
||||
retained: boolean;
|
||||
forecastAt: string | null;
|
||||
entry: UsageReportEntry;
|
||||
window: UsageWindow;
|
||||
display: UsageDisplay;
|
||||
@@ -285,6 +288,7 @@ function CardWindowBar({
|
||||
<UsageWindowBar
|
||||
window={window}
|
||||
retained={retained}
|
||||
forecastAt={forecastAt}
|
||||
displayAs={display.displayAs}
|
||||
pinnable={pinnable}
|
||||
pinned={display.isPinned(pin)}
|
||||
|
||||
@@ -2,6 +2,7 @@ import { afterEach, describe, expect, it } from "vitest";
|
||||
import { i18n } from "@/i18n/i18next";
|
||||
import {
|
||||
resolveUsageReport,
|
||||
markUsageRefreshFailure,
|
||||
displayPercent,
|
||||
resolveAgentUsageView,
|
||||
replaceReport,
|
||||
@@ -82,7 +83,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 });
|
||||
).toEqual({ kind: "ready", reports: [], isRefreshing: true, refreshFailed: false });
|
||||
expect(
|
||||
resolveUsageView({
|
||||
...base,
|
||||
@@ -90,6 +91,19 @@ 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 () => {
|
||||
@@ -203,15 +217,12 @@ describe("displayPercent", () => {
|
||||
|
||||
describe("resolveUsageRefresh", () => {
|
||||
it("is pending while a refresh runs, even after an earlier failure", () => {
|
||||
expect(resolveUsageRefresh({ isPending: true, error: new Error("boom") })).toBe("pending");
|
||||
expect(resolveUsageRefresh({ isPending: true, isError: true })).toBe("pending");
|
||||
});
|
||||
|
||||
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");
|
||||
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");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -352,6 +363,7 @@ 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"],
|
||||
});
|
||||
@@ -361,6 +373,7 @@ it("resolves retained usage and successful time without inventing old-daemon his
|
||||
details: [],
|
||||
planLabel: null,
|
||||
successfulAt: null,
|
||||
forecastAt: null,
|
||||
retained: false,
|
||||
messages: ["Rate limited"],
|
||||
});
|
||||
@@ -370,11 +383,48 @@ 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");
|
||||
|
||||
@@ -38,18 +38,31 @@ export function usageWindowRowLabel(input: {
|
||||
return `${input.pinLabel}, ${summary}`;
|
||||
}
|
||||
|
||||
/** A user-requested refresh of one report. The previous report stays on screen throughout. */
|
||||
/** The outcome of a user-requested usage refresh. */
|
||||
export type UsageRefresh = "idle" | "pending" | "failed";
|
||||
|
||||
export function resolveUsageRefresh(mutation: {
|
||||
isPending: boolean;
|
||||
error: unknown;
|
||||
isError: boolean;
|
||||
}): UsageRefresh {
|
||||
if (mutation.isPending) return "pending";
|
||||
if (mutation.error) return "failed";
|
||||
if (mutation.isError) 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.
|
||||
@@ -60,7 +73,9 @@ export function replaceReport(
|
||||
refreshed: UsageReportEntry | null,
|
||||
): UsageReportEntry[] {
|
||||
if (!refreshed) return reports.filter((report) => report.id !== reportId);
|
||||
return reports.map((report) => (report.id === reportId ? refreshed : report));
|
||||
return reports.map((report) =>
|
||||
report.id === reportId ? laterFetched(report, refreshed) : report,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -68,7 +83,9 @@ 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 {
|
||||
return Date.parse(shown.fetchedAt) > Date.parse(arriving.fetchedAt) ? shown : arriving;
|
||||
const shownAt = Date.parse(shown.fetchedAt);
|
||||
const arrivingAt = Date.parse(arriving.fetchedAt);
|
||||
return shownAt > arrivingAt || (shownAt === arrivingAt && shown.forecastStale) ? shown : arriving;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -117,10 +134,11 @@ export function resolveUsageView(
|
||||
isConnected: boolean;
|
||||
supportsUsage: boolean;
|
||||
query: UsageQueryState | undefined;
|
||||
refreshState?: UsageRefresh;
|
||||
},
|
||||
t: TFunction = i18n.t,
|
||||
): UsageView {
|
||||
const { hostLabel, isConnected, supportsUsage, query } = input;
|
||||
const { hostLabel, isConnected, supportsUsage, query, refreshState } = input;
|
||||
if (!isConnected)
|
||||
return {
|
||||
kind: "unavailable",
|
||||
@@ -135,7 +153,12 @@ 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 };
|
||||
return {
|
||||
kind: "ready",
|
||||
reports: query.data,
|
||||
isRefreshing: query.isFetching || refreshState === "pending",
|
||||
refreshFailed: refreshState === "failed",
|
||||
};
|
||||
}
|
||||
if (query?.error) {
|
||||
return {
|
||||
@@ -250,7 +273,12 @@ 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 ?? [],
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
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" });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,45 @@
|
||||
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 };
|
||||
}
|
||||
@@ -20,6 +20,7 @@ import { useSessionStore, type SessionState } from "@/stores/session-store";
|
||||
import { useUsageSetting } from "./setting";
|
||||
import { usageCopy } from "./copy";
|
||||
import {
|
||||
markUsageRefreshFailure,
|
||||
replaceReport,
|
||||
resolveAgentUsageView,
|
||||
resolveUsageRefresh,
|
||||
@@ -97,17 +98,32 @@ async function streamReports(input: {
|
||||
return settleReports(queryClient.getQueryData<UsageReportEntry[]>(queryKey), reports);
|
||||
}
|
||||
|
||||
function listReports(
|
||||
async function listReports(
|
||||
queryClient: QueryClient,
|
||||
serverId: string,
|
||||
forceRefresh = false,
|
||||
): Promise<UsageReportEntry[]> {
|
||||
return streamReports({
|
||||
queryClient,
|
||||
queryKey: usageReportsQueryKey(serverId),
|
||||
serverId,
|
||||
forceRefresh,
|
||||
});
|
||||
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 },
|
||||
);
|
||||
}
|
||||
|
||||
async function getReport(
|
||||
@@ -158,9 +174,12 @@ export function useHostUsage(serverId: string): { view: UsageView; refresh: () =
|
||||
dataShape: "value",
|
||||
staleTimeMs: REPORTS_STALE_TIME_MS,
|
||||
});
|
||||
const refresh = useCallback(() => {
|
||||
void refreshReports(queryClient, serverId).catch(() => undefined);
|
||||
}, [queryClient, serverId]);
|
||||
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 { t } = useTranslation();
|
||||
const hostLabel = useHosts().find((host) => host.serverId === serverId)?.label ?? serverId;
|
||||
const view = resolveUsageView(
|
||||
@@ -170,6 +189,7 @@ export function useHostUsage(serverId: string): { view: UsageView; refresh: () =
|
||||
isConnected,
|
||||
supportsUsage: isSupported,
|
||||
query: toQueryState(query),
|
||||
refreshState: variables === serverId ? resolveUsageRefresh(mutation) : "idle",
|
||||
},
|
||||
t,
|
||||
);
|
||||
@@ -265,23 +285,26 @@ export function useUsageHosts(): UsageHost[] {
|
||||
*/
|
||||
export function useReportRefresh(
|
||||
serverId: string,
|
||||
reportId: string,
|
||||
entry: UsageReportEntry,
|
||||
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({
|
||||
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),
|
||||
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,
|
||||
);
|
||||
},
|
||||
onError: (_error, attempted) => recordUsageRefreshFailure(queryClient, queryKey, [attempted]),
|
||||
});
|
||||
const { mutate } = mutation;
|
||||
const refresh = useCallback(() => mutate(), [mutate]);
|
||||
const refresh = useCallback(() => mutate(entry), [mutate, entry]);
|
||||
return { refresh, refreshState: resolveUsageRefresh(mutation) };
|
||||
}
|
||||
|
||||
@@ -3,24 +3,21 @@ 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 gives way (truncates) and the countdown stays whole.
|
||||
* is too narrow the exact time truncates and the countdown wraps within its column.
|
||||
*/
|
||||
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={atRisk ? styles.atRisk : styles.text}>{countdown}</Text>
|
||||
<Text style={[styles.text, styles.countdown]}>{countdown}</Text>
|
||||
{exactTime ? (
|
||||
<Text style={[styles.text, styles.exactTime]} numberOfLines={1} ellipsizeMode="tail">
|
||||
{`\u00a0·\u00a0${exactTime}`}
|
||||
@@ -31,18 +28,13 @@ export function UsageResetLine({
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
line: { flexDirection: "row", alignItems: "center" },
|
||||
line: { flexDirection: "row", alignItems: "baseline" },
|
||||
text: {
|
||||
flexShrink: 0,
|
||||
color: theme.colors.foregroundMuted,
|
||||
fontSize: theme.fontSize.sm,
|
||||
fontWeight: theme.fontWeight.normal,
|
||||
},
|
||||
atRisk: {
|
||||
flexShrink: 0,
|
||||
color: theme.colors.statusDanger,
|
||||
fontSize: theme.fontSize.sm,
|
||||
fontWeight: theme.fontWeight.normal,
|
||||
},
|
||||
exactTime: { flexShrink: 1 },
|
||||
countdown: { maxWidth: "100%" },
|
||||
exactTime: { flexShrink: 1, minWidth: 0 },
|
||||
}));
|
||||
|
||||
@@ -1,6 +1,12 @@
|
||||
import type { ProviderUsageTone, UsageReportEntry } from "@getpaseo/protocol/messages";
|
||||
import type {
|
||||
ProviderUsageTone,
|
||||
UsageReportEntry as WireUsageReportEntry,
|
||||
} from "@getpaseo/protocol/messages";
|
||||
|
||||
export type { UsageReportEntry };
|
||||
export interface UsageReportEntry extends WireUsageReportEntry {
|
||||
/** A refresh failed while this reading was cached. */
|
||||
forecastStale?: true;
|
||||
}
|
||||
export type UsageReport = UsageReportEntry["report"];
|
||||
export type UsageTone = ProviderUsageTone;
|
||||
export type AvailableUsageReport = Extract<UsageReport, { status: "available" }>;
|
||||
@@ -14,4 +20,4 @@ export type UsageView =
|
||||
| { kind: "unavailable"; message: string }
|
||||
| { kind: "loading" }
|
||||
| { kind: "error"; message: string }
|
||||
| { kind: "ready"; reports: UsageReportEntry[]; isRefreshing: boolean };
|
||||
| { kind: "ready"; reports: UsageReportEntry[]; isRefreshing: boolean; refreshFailed: boolean };
|
||||
|
||||
@@ -84,11 +84,18 @@ export function UsageBody({
|
||||
);
|
||||
}
|
||||
|
||||
if (view.reports.length === 0) {
|
||||
return <UsageMessage text={t("providerUsage.empty")} />;
|
||||
}
|
||||
|
||||
return <UsageList serverId={serverId} reports={view.reports} display={display} />;
|
||||
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>
|
||||
);
|
||||
}
|
||||
|
||||
export function UsageMessage({ text }: { text: string }) {
|
||||
@@ -100,6 +107,7 @@ export function UsageMessage({ text }: { text: string }) {
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
reports: { gap: theme.spacing[3] },
|
||||
emptyCard: {
|
||||
padding: theme.spacing[4],
|
||||
alignItems: "center",
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import type { TFunction } from "i18next";
|
||||
import { Pin } from "lucide-react-native";
|
||||
import { useMemo } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
@@ -6,6 +7,7 @@ import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
|
||||
import {
|
||||
formatDisplayPct,
|
||||
formatPct,
|
||||
formatProviderUsageLabel,
|
||||
formatResetLabel,
|
||||
formatResetTime,
|
||||
@@ -13,9 +15,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";
|
||||
|
||||
@@ -28,8 +30,10 @@ 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. */
|
||||
@@ -42,19 +46,11 @@ 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 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 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 value =
|
||||
shownPct != null ? formatDisplayPct(shownPct, displayAs, i18n.resolvedLanguage, t) : "—";
|
||||
@@ -64,9 +60,8 @@ export function UsageWindowBar({
|
||||
value,
|
||||
countdown,
|
||||
exactTime,
|
||||
isAtRisk,
|
||||
forecast,
|
||||
percent: shownPct ?? 0,
|
||||
tone,
|
||||
pinned,
|
||||
};
|
||||
|
||||
@@ -86,7 +81,7 @@ export function UsageWindowBar({
|
||||
accessibilityLabel={usageWindowRowLabel({
|
||||
pinLabel,
|
||||
value,
|
||||
trailing: [countdown, exactTime].filter(Boolean).join(" · "),
|
||||
trailing: [countdown, exactTime, forecast?.label].filter(Boolean).join(" · "),
|
||||
})}
|
||||
accessibilityState={accessibilityState}
|
||||
aria-checked={pinned}
|
||||
@@ -103,9 +98,8 @@ function WindowRowContent({
|
||||
value,
|
||||
countdown,
|
||||
exactTime,
|
||||
isAtRisk,
|
||||
forecast,
|
||||
percent,
|
||||
tone,
|
||||
pinnable,
|
||||
pinned,
|
||||
}: {
|
||||
@@ -113,9 +107,8 @@ function WindowRowContent({
|
||||
value: string;
|
||||
countdown: string | null;
|
||||
exactTime: string | null;
|
||||
isAtRisk: boolean;
|
||||
forecast: PaceLabel | null;
|
||||
percent: number;
|
||||
tone: UsageTone;
|
||||
pinnable: boolean;
|
||||
pinned: boolean;
|
||||
}) {
|
||||
@@ -130,12 +123,51 @@ function WindowRowContent({
|
||||
</Text>
|
||||
{pinnable ? <UsagePinGlyph pinned={pinned} /> : null}
|
||||
</View>
|
||||
<UsageMeter percent={percent} tone={tone} />
|
||||
<UsageResetLine countdown={countdown} exactTime={exactTime} atRisk={isAtRisk} />
|
||||
<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}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
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 }) {
|
||||
@@ -167,6 +199,23 @@ 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 },
|
||||
|
||||
@@ -96,12 +96,12 @@ test.each([
|
||||
])(
|
||||
"duration %s owns the window's identity and both names",
|
||||
(durationSeconds, id, label, shortLabel) => {
|
||||
expect(
|
||||
windowFromReportedDuration({
|
||||
durationSeconds: durationSeconds as number | null,
|
||||
unknown: { id: "primary", label: "Primary limit", shortLabel: "" },
|
||||
utilizationPct: 11,
|
||||
}),
|
||||
).toMatchObject({ id, label, shortLabel, usedPct: 11 });
|
||||
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);
|
||||
},
|
||||
);
|
||||
|
||||
@@ -16,6 +16,8 @@ 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";
|
||||
@@ -48,6 +50,8 @@ 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[];
|
||||
@@ -96,6 +100,7 @@ export function windowFromUsedPct(input: {
|
||||
shortLabel?: string;
|
||||
summary?: boolean;
|
||||
utilizationPct: number | null | undefined;
|
||||
durationSeconds?: number;
|
||||
resetsAt?: string | null;
|
||||
tone?: UsageWindow["tone"];
|
||||
}): UsageWindow {
|
||||
@@ -107,6 +112,7 @@ 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;
|
||||
@@ -129,11 +135,10 @@ export function windowFromReportedDuration(input: {
|
||||
summary?: boolean;
|
||||
tone?: UsageWindow["tone"];
|
||||
}): UsageWindow {
|
||||
const duration = input.durationSeconds;
|
||||
const name =
|
||||
duration !== null && Number.isFinite(duration) && duration > 0
|
||||
? durationWindowName(duration)
|
||||
: input.unknown;
|
||||
const reported = input.durationSeconds;
|
||||
const duration =
|
||||
reported !== null && Number.isFinite(reported) && reported > 0 ? reported : undefined;
|
||||
const name = duration === undefined ? input.unknown : durationWindowName(duration);
|
||||
const scope = input.scope;
|
||||
return windowFromUsedPct({
|
||||
id: scope ? `${scope.id}:${name.id}` : name.id,
|
||||
@@ -142,6 +147,7 @@ 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,
|
||||
|
||||
@@ -6992,6 +6992,7 @@ 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(),
|
||||
@@ -7054,6 +7055,7 @@ 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,6 +56,17 @@ 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()
|
||||
@@ -129,6 +140,7 @@ 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,6 +263,7 @@ 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),
|
||||
}),
|
||||
@@ -283,6 +284,7 @@ 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),
|
||||
});
|
||||
|
||||
@@ -86,8 +86,10 @@ 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({
|
||||
@@ -112,7 +114,7 @@ export class Usage {
|
||||
{
|
||||
id: "observed",
|
||||
label: "Observed",
|
||||
value: new Date(usage.observedAtMs).toISOString(),
|
||||
value: observedAt,
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
@@ -1505,6 +1505,7 @@ for (const usage of [
|
||||
expect(report).toMatchObject({
|
||||
status: "available",
|
||||
planLabel: "Pro",
|
||||
observedAt: new Date(usage.usage.observedAtMs).toISOString(),
|
||||
windows: [
|
||||
{
|
||||
id: "five_hour",
|
||||
@@ -1800,7 +1801,10 @@ 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.status).toBe("available");
|
||||
expect(reports[0]!.report).toMatchObject({
|
||||
status: "available",
|
||||
observedAt: "2023-11-14T22:13:20.000Z",
|
||||
});
|
||||
}
|
||||
expect(await registry.listReports({ agentId: "muse-unknown" })).toEqual([]);
|
||||
expect((await registry.listReports()).map((report) => report.id)).toEqual(accountIds);
|
||||
|
||||
@@ -616,7 +616,11 @@ 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.
|
||||
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.
|
||||
|
||||
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
|
||||
|
||||
Reference in New Issue
Block a user