mirror of
https://github.com/getpaseo/paseo.git
synced 2026-11-21 07:45:38 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
14e8908d0a | ||
|
|
efb65d7b82 | ||
|
|
27c126d352 | ||
|
|
7e3826ad6c |
@@ -0,0 +1,149 @@
|
||||
import { test, expect, type Page } from "../support/fixtures";
|
||||
import { gotoAppShell } from "../support/helpers/app";
|
||||
import { seedWorkspace, type SeededWorkspace } from "../support/helpers/seed-client";
|
||||
import { selectSidebarStatusGrouping } from "../support/helpers/sidebar";
|
||||
import {
|
||||
createGatedTeardown,
|
||||
pressArchiveShortcut,
|
||||
workspaceRow,
|
||||
} from "../support/helpers/workspace-archive-undo";
|
||||
|
||||
// The archive shortcut used to be registered by the sidebar row itself, so it did nothing whenever
|
||||
// the row was unmounted — a collapsed project section being the common case. It now lives in a
|
||||
// single always-mounted handler keyed on the active route selection, like the pin shortcut.
|
||||
// Returns the workspace route, so the test can assert archiving redirected off it.
|
||||
async function openWorkspace(page: Page, workspaceId: string): Promise<string> {
|
||||
const row = workspaceRow(page, workspaceId);
|
||||
await expect(row).toBeVisible({ timeout: 30_000 });
|
||||
await row.click();
|
||||
await expect(page).toHaveURL((url) => url.pathname.endsWith(`/workspace/${workspaceId}`), {
|
||||
timeout: 30_000,
|
||||
});
|
||||
return page.url();
|
||||
}
|
||||
|
||||
async function collapseProjectSection(page: Page, project: SeededWorkspace): Promise<void> {
|
||||
const header = page
|
||||
.locator('[data-testid^="sidebar-project-row-"]')
|
||||
.filter({ hasText: project.projectDisplayName });
|
||||
await expect(header).toHaveCount(1, { timeout: 30_000 });
|
||||
|
||||
await header.click();
|
||||
await expect(workspaceRow(page, project.workspaceId)).toHaveCount(0, { timeout: 10_000 });
|
||||
}
|
||||
|
||||
async function collapseStatusGroupContaining(page: Page, workspaceId: string): Promise<void> {
|
||||
const rows = page
|
||||
.locator('[data-testid^="sidebar-status-group-rows-"]')
|
||||
.filter({ has: workspaceRow(page, workspaceId) });
|
||||
await expect(rows).toHaveCount(1, { timeout: 30_000 });
|
||||
|
||||
const rowsTestId = await rows.getAttribute("data-testid");
|
||||
const bucket = rowsTestId?.replace("sidebar-status-group-rows-", "");
|
||||
expect(bucket).toBeTruthy();
|
||||
|
||||
await page.getByTestId(`sidebar-status-group-${bucket}`).click();
|
||||
await expect(workspaceRow(page, workspaceId)).toHaveCount(0, { timeout: 10_000 });
|
||||
}
|
||||
|
||||
async function expectArchived(page: Page, workspace: SeededWorkspace, workspaceUrl: string) {
|
||||
await expect(page).not.toHaveURL(workspaceUrl);
|
||||
await expect
|
||||
.poll(async () => {
|
||||
const { entries } = await workspace.client.fetchWorkspaces();
|
||||
return entries.some((entry) => entry.id === workspace.workspaceId);
|
||||
})
|
||||
.toBe(false);
|
||||
}
|
||||
|
||||
test.describe("Archive workspace shortcut", () => {
|
||||
test("archives the active workspace while its row is rendered", async ({ page }) => {
|
||||
const workspace = await seedWorkspace({ repoPrefix: "archive-shortcut-expanded-" });
|
||||
|
||||
try {
|
||||
await gotoAppShell(page);
|
||||
const workspaceUrl = await openWorkspace(page, workspace.workspaceId);
|
||||
|
||||
await pressArchiveShortcut(page);
|
||||
|
||||
await expectArchived(page, workspace, workspaceUrl);
|
||||
} finally {
|
||||
await workspace.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("archives the active workspace while its project section is collapsed", async ({ page }) => {
|
||||
const workspace = await seedWorkspace({ repoPrefix: "archive-shortcut-collapsed-" });
|
||||
|
||||
try {
|
||||
await gotoAppShell(page);
|
||||
const workspaceUrl = await openWorkspace(page, workspace.workspaceId);
|
||||
await collapseProjectSection(page, workspace);
|
||||
|
||||
await pressArchiveShortcut(page);
|
||||
|
||||
await expectArchived(page, workspace, workspaceUrl);
|
||||
} finally {
|
||||
await workspace.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("archives the active workspace while its status group is collapsed", async ({ page }) => {
|
||||
const workspace = await seedWorkspace({ repoPrefix: "archive-shortcut-status-" });
|
||||
|
||||
try {
|
||||
await gotoAppShell(page);
|
||||
const workspaceUrl = await openWorkspace(page, workspace.workspaceId);
|
||||
await selectSidebarStatusGrouping(page);
|
||||
await expect(page.getByTestId("sidebar-status-list-scroll")).toBeVisible({
|
||||
timeout: 10_000,
|
||||
});
|
||||
await collapseStatusGroupContaining(page, workspace.workspaceId);
|
||||
|
||||
await pressArchiveShortcut(page);
|
||||
|
||||
await expectArchived(page, workspace, workspaceUrl);
|
||||
} finally {
|
||||
await workspace.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("archives a different workspace while the first worktree is still tearing down", async ({
|
||||
page,
|
||||
}) => {
|
||||
const teardown = createGatedTeardown();
|
||||
const project = await seedWorkspace({
|
||||
repoPrefix: "archive-shortcut-teardown-",
|
||||
repo: { paseoConfig: teardown.paseoConfig },
|
||||
});
|
||||
const next = await seedWorkspace({ repoPrefix: "archive-shortcut-next-" });
|
||||
|
||||
try {
|
||||
const { workspace: worktree, error } = await project.client.createWorkspace({
|
||||
source: {
|
||||
kind: "worktree",
|
||||
cwd: project.repoPath,
|
||||
worktreeSlug: "archive-shortcut-teardown",
|
||||
},
|
||||
});
|
||||
if (!worktree) throw new Error(error ?? "Could not seed the worktree");
|
||||
await gotoAppShell(page);
|
||||
|
||||
await test.step("start the first archive and wait for its teardown", async () => {
|
||||
await openWorkspace(page, worktree.id);
|
||||
await pressArchiveShortcut(page);
|
||||
await teardown.expectStarted();
|
||||
});
|
||||
|
||||
await test.step("archive the second workspace before the first archive finishes", async () => {
|
||||
const workspaceUrl = await openWorkspace(page, next.workspaceId);
|
||||
await pressArchiveShortcut(page);
|
||||
await expectArchived(page, next, workspaceUrl);
|
||||
});
|
||||
} finally {
|
||||
teardown.release();
|
||||
await project.cleanup();
|
||||
await next.cleanup();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -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 });
|
||||
|
||||
@@ -318,6 +318,37 @@ test.describe("Workspace archive undo", () => {
|
||||
}
|
||||
});
|
||||
|
||||
test("archives a restored workspace while its undo is queued", async ({ page }) => {
|
||||
const teardown = createGatedTeardown();
|
||||
const repo = await createTempGitRepo("archive-undo-archive-", {
|
||||
paseoConfig: teardown.paseoConfig,
|
||||
});
|
||||
|
||||
try {
|
||||
await openProjectViaDaemon(client, repo.path);
|
||||
const worktree = await createWorktreeViaDaemon(client, {
|
||||
cwd: repo.path,
|
||||
slug: "archive-undo-archive",
|
||||
});
|
||||
worktreeDirectories.add(worktree.workspaceDirectory);
|
||||
await gotoAppShell(page);
|
||||
await archiveFromRowButton(page, worktree.workspaceId);
|
||||
await teardown.expectStarted();
|
||||
|
||||
await undoButton(page).click();
|
||||
await workspaceRow(page, worktree.workspaceId).click();
|
||||
await expect(page).toHaveURL(new RegExp(`/workspace/${worktree.workspaceId}$`));
|
||||
|
||||
await pressArchiveShortcut(page);
|
||||
await expectWorkspaceAbsentFromSidebar(page, worktree.workspaceId);
|
||||
teardown.release();
|
||||
await expectDirectoryPresence(worktree.workspaceDirectory, false);
|
||||
} finally {
|
||||
teardown.release();
|
||||
await repo.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("Cmd/Ctrl+Z without an archive to undo leaves the sidebar alone", async ({ page }) => {
|
||||
const worktree = await seedWorktree(page, "archive-undo-none");
|
||||
|
||||
|
||||
@@ -20,6 +20,7 @@ import {
|
||||
} from "../support/helpers/sidebar";
|
||||
import { createTempGitRepo } from "../support/helpers/workspace";
|
||||
import {
|
||||
pressArchiveShortcut,
|
||||
rowArchiveButton,
|
||||
undoButton,
|
||||
workspaceRow,
|
||||
@@ -98,6 +99,18 @@ async function clickRowArchiveButton(page: Page, workspaceId: string): Promise<v
|
||||
await rowArchiveButton(page, workspaceId).click();
|
||||
}
|
||||
|
||||
async function cycleThemeAndWaitForSidebar(page: Page, workspaceId: string): Promise<void> {
|
||||
const rowBeforeThemeChange = await workspaceRow(page, workspaceId).elementHandle();
|
||||
if (!rowBeforeThemeChange)
|
||||
throw new Error("The workspace row must be mounted before cycling the theme");
|
||||
await page.keyboard.press("ControlOrMeta+Alt+t");
|
||||
await expect
|
||||
.poll(() => rowBeforeThemeChange.evaluate((element) => element.isConnected), {
|
||||
message: "the sidebar remounts after the theme changes",
|
||||
})
|
||||
.toBe(false);
|
||||
}
|
||||
|
||||
interface SessionEnvelope {
|
||||
type?: unknown;
|
||||
message?: {
|
||||
@@ -211,18 +224,28 @@ async function relayDaemon(
|
||||
* Holds the app's next checkout status request for `directory` once armed, so a test can act
|
||||
* while the archive waits for the host's answer.
|
||||
*/
|
||||
async function holdCheckoutStatusRequest(page: Page, directory: string) {
|
||||
async function holdCheckoutStatusRequest(
|
||||
page: Page,
|
||||
worktree: { workspaceDirectory: string; workspaceId: string },
|
||||
) {
|
||||
let armed = false;
|
||||
let held: (() => void) | null = null;
|
||||
let archiveRequests = 0;
|
||||
await page.routeWebSocket(daemonWsRoutePattern(), (browser) => {
|
||||
const server = browser.connectToServer();
|
||||
browser.onMessage((message) => {
|
||||
const request = typeof message === "string" ? parseSessionEnvelope(message)?.message : null;
|
||||
if (
|
||||
request?.type === "archive_workspace_request" &&
|
||||
request.workspaceId === worktree.workspaceId
|
||||
) {
|
||||
archiveRequests += 1;
|
||||
}
|
||||
if (
|
||||
armed &&
|
||||
!held &&
|
||||
request?.type === "checkout_status_request" &&
|
||||
request.cwd === directory
|
||||
request.cwd === worktree.workspaceDirectory
|
||||
) {
|
||||
held = () => server.send(message);
|
||||
return;
|
||||
@@ -236,6 +259,7 @@ async function holdCheckoutStatusRequest(page: Page, directory: string) {
|
||||
armed = true;
|
||||
},
|
||||
waitForHeld: () => expect.poll(() => held !== null).toBe(true),
|
||||
archiveRequests: () => archiveRequests,
|
||||
release: () => {
|
||||
if (!held) throw new Error("No checkout status request is held");
|
||||
held();
|
||||
@@ -388,7 +412,7 @@ test.describe("Workspace archive risk warning for worktree backing", () => {
|
||||
): Promise<string> {
|
||||
const serverId = getServerId();
|
||||
const worktree = await createWorktree(slug);
|
||||
const statusRequest = await holdCheckoutStatusRequest(page, worktree.workspaceDirectory);
|
||||
const statusRequest = await holdCheckoutStatusRequest(page, worktree);
|
||||
await openSidebarRow(page, worktree.workspaceId);
|
||||
await workspaceRow(page, worktree.workspaceId).click();
|
||||
await expectAppRoute(page, buildHostWorkspaceRoute(serverId, worktree.workspaceId));
|
||||
@@ -432,6 +456,82 @@ test.describe("Workspace archive risk warning for worktree backing", () => {
|
||||
await expectAppRoute(page, openedRoute);
|
||||
});
|
||||
|
||||
async function openWorktreeWithCheckoutHeld(page: Page, slug: string) {
|
||||
const worktree = await createWorktree(slug);
|
||||
const statusRequest = await holdCheckoutStatusRequest(page, worktree);
|
||||
// Opening the workspace can start a checkout read that the archive reuses.
|
||||
statusRequest.arm();
|
||||
await openSidebarRow(page, worktree.workspaceId);
|
||||
await workspaceRow(page, worktree.workspaceId).click();
|
||||
await expectAppRoute(page, buildHostWorkspaceRoute(getServerId(), worktree.workspaceId));
|
||||
return { worktree, statusRequest };
|
||||
}
|
||||
|
||||
test("the archive shortcut works in another workspace while a checkout check is pending", async ({
|
||||
page,
|
||||
}) => {
|
||||
const { worktree, statusRequest } = await openWorktreeWithCheckoutHeld(
|
||||
page,
|
||||
"archive-risk-switch-shortcut",
|
||||
);
|
||||
|
||||
await pressArchiveShortcut(page);
|
||||
await statusRequest.waitForHeld();
|
||||
try {
|
||||
const otherWorkspaceId = worktree.project.workspaceId;
|
||||
await workspaceRow(page, otherWorkspaceId).click();
|
||||
await expectAppRoute(page, buildHostWorkspaceRoute(getServerId(), otherWorkspaceId));
|
||||
|
||||
await pressArchiveShortcut(page);
|
||||
await expect.poll(() => hostListsWorkspace(otherWorkspaceId)).toBe(false);
|
||||
} finally {
|
||||
statusRequest.release();
|
||||
}
|
||||
await expect.poll(() => hostListsWorkspace(worktree.workspaceId)).toBe(false);
|
||||
});
|
||||
|
||||
test("the row button and shortcut send one archive for the same worktree", async ({ page }) => {
|
||||
const { worktree, statusRequest } = await openWorktreeWithCheckoutHeld(
|
||||
page,
|
||||
"archive-risk-repeat-shortcut",
|
||||
);
|
||||
|
||||
await clickRowArchiveButton(page, worktree.workspaceId);
|
||||
await statusRequest.waitForHeld();
|
||||
try {
|
||||
await pressArchiveShortcut(page);
|
||||
} finally {
|
||||
statusRequest.release();
|
||||
}
|
||||
|
||||
await expect.poll(() => hostListsWorkspace(worktree.workspaceId)).toBe(false);
|
||||
expect(statusRequest.archiveRequests()).toBe(1);
|
||||
});
|
||||
|
||||
test("keeps the newly opened workspace after a theme change during an archive check", async ({
|
||||
page,
|
||||
}) => {
|
||||
const { worktree, statusRequest } = await openWorktreeWithCheckoutHeld(
|
||||
page,
|
||||
"archive-risk-theme",
|
||||
);
|
||||
|
||||
await pressArchiveShortcut(page);
|
||||
await statusRequest.waitForHeld();
|
||||
const otherWorkspaceId = worktree.project.workspaceId;
|
||||
const otherRoute = buildHostWorkspaceRoute(getServerId(), otherWorkspaceId);
|
||||
try {
|
||||
await cycleThemeAndWaitForSidebar(page, otherWorkspaceId);
|
||||
await workspaceRow(page, otherWorkspaceId).click();
|
||||
await expectAppRoute(page, otherRoute);
|
||||
} finally {
|
||||
statusRequest.release();
|
||||
}
|
||||
|
||||
await expect.poll(() => hostListsWorkspace(worktree.workspaceId)).toBe(false);
|
||||
await expectAppRoute(page, otherRoute);
|
||||
});
|
||||
|
||||
test("archiving the open worktree from its git actions leaves it for a new workspace", async ({
|
||||
page,
|
||||
}) => {
|
||||
|
||||
@@ -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",
|
||||
},
|
||||
},
|
||||
|
||||
@@ -40,7 +40,7 @@
|
||||
"dev:ios": "npm --prefix ../.. run build:client && cross-env APP_VARIANT=development expo run:ios",
|
||||
"build:apk": "npm --prefix ../.. run build:apk",
|
||||
"build:apk:arm64": "npm --prefix ../.. run build:apk:arm64",
|
||||
"test:android": "expo prebuild --platform android --no-install && cd android && ./gradlew :paseo-native-trace:testReleaseUnitTest :paseo-hardware-keyboard:testReleaseUnitTest :react-native-enriched-markdown:testReleaseUnitTest --tests '*InlineCodeFormattingTest' --no-daemon --max-workers=2 -Dorg.gradle.parallel=false"
|
||||
"test:android": "expo prebuild --platform android --no-install && cd android && ./gradlew :paseo-native-trace:testReleaseUnitTest :paseo-hardware-keyboard:testReleaseUnitTest :react-native-enriched-markdown:testReleaseUnitTest --tests '*InlineCodeFormattingTest' --tests '*ListBlockquoteMeasurementTest' --no-daemon --max-workers=2 -Dorg.gradle.parallel=false"
|
||||
},
|
||||
"dependencies": {
|
||||
"@codemirror/commands": "6.10.4",
|
||||
|
||||
@@ -54,6 +54,7 @@ import { WindowSidebarMenuToggle } from "@/components/headers/sidebar-menu-toggl
|
||||
import { DesktopWindowControls } from "@/components/desktop/window-controls";
|
||||
import { SidebarModelProvider } from "@/components/sidebar/sidebar-model";
|
||||
import { WorkspacePinShortcutHandler } from "@/components/workspace-pin-shortcut-handler";
|
||||
import { WorkspaceArchiveShortcutHandler } from "@/components/workspace-archive-shortcut-handler";
|
||||
import { WorkspaceRenameHost } from "@/components/workspace-rename-host";
|
||||
import { WorkspaceArchiveUndoShortcutHost } from "@/workspace/archive-undo";
|
||||
import { WorkspaceExplorerOpenGesture } from "@/mobile-panels/explorer-open-gesture";
|
||||
@@ -537,6 +538,7 @@ function AppContainer({ children, chromeEnabled: chromeEnabledOverride }: AppCon
|
||||
<View style={layoutStyles.surfaceFill}>
|
||||
{workspaceChrome}
|
||||
<AddHostFlowHost />
|
||||
<WorkspaceArchiveShortcutHandler />
|
||||
<AppearanceStyleBoundary>
|
||||
{!isCompactLayout && appChromeLayout.sidebarToggleOwner === "window" ? (
|
||||
<WindowChromeRegion corners="top-left">
|
||||
|
||||
@@ -128,7 +128,6 @@ import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip
|
||||
import { Shortcut } from "@/components/ui/shortcut";
|
||||
import type { ShortcutKey } from "@/utils/format-shortcut";
|
||||
import { useShortcutKeys } from "@/hooks/use-shortcut-keys";
|
||||
import { useKeyboardActionHandler } from "@/hooks/use-keyboard-action-handler";
|
||||
import { useWorkspaceReadState } from "@/hooks/use-workspace-read-state";
|
||||
import type { PrHint } from "@/git/use-pr-status-query";
|
||||
import {
|
||||
@@ -1298,17 +1297,6 @@ function WorkspaceRowWithMenu({
|
||||
});
|
||||
}, [markUnread, toast]);
|
||||
|
||||
useKeyboardActionHandler({
|
||||
handlerId: `workspace-archive-${workspace.workspaceKey}`,
|
||||
actions: ["workspace.archive"],
|
||||
enabled: selected && !isArchiving,
|
||||
priority: 0,
|
||||
handle: () => {
|
||||
handleArchive();
|
||||
return true;
|
||||
},
|
||||
});
|
||||
|
||||
return (
|
||||
<>
|
||||
<WorkspaceRowInner
|
||||
|
||||
@@ -42,7 +42,6 @@ import { redirectIfArchivingActiveWorkspace } from "@/utils/sidebar-workspace-ar
|
||||
import { useWorkspaceArchive } from "@/workspace/use-workspace-archive";
|
||||
import type { ShortcutKey } from "@/utils/format-shortcut";
|
||||
import { useShortcutKeys } from "@/hooks/use-shortcut-keys";
|
||||
import { useKeyboardActionHandler } from "@/hooks/use-keyboard-action-handler";
|
||||
import { useWorkspaceReadState } from "@/hooks/use-workspace-read-state";
|
||||
import {
|
||||
SidebarWorkspaceRowFrame,
|
||||
@@ -702,17 +701,6 @@ function StatusWorkspaceRowWithMenu({
|
||||
});
|
||||
}, [markUnread, toast]);
|
||||
|
||||
useKeyboardActionHandler({
|
||||
handlerId: `workspace-archive-${workspace.workspaceKey}`,
|
||||
actions: ["workspace.archive"],
|
||||
enabled: selected && !isArchiving,
|
||||
priority: 0,
|
||||
handle: () => {
|
||||
handleArchive();
|
||||
return true;
|
||||
},
|
||||
});
|
||||
|
||||
return (
|
||||
<>
|
||||
<StatusWorkspaceRowInner
|
||||
|
||||
@@ -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} />
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
import { useGlobalWorkspaceArchiveAction } from "@/hooks/use-global-workspace-archive-action";
|
||||
|
||||
// Headless host for the archive shortcut, kept out of the root layout for the same reason as
|
||||
// WorkspacePinShortcutHandler: the hook subscribes to the active workspace's fields.
|
||||
export function WorkspaceArchiveShortcutHandler() {
|
||||
useGlobalWorkspaceArchiveAction();
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
import { useCallback } from "react";
|
||||
import { useKeyboardActionHandler } from "@/hooks/use-keyboard-action-handler";
|
||||
import type { KeyboardActionId } from "@/keyboard/keyboard-action-dispatcher";
|
||||
import { useActiveWorkspaceSelection } from "@/stores/navigation-active-workspace-store";
|
||||
import { useWorkspaceFields } from "@/stores/session-store-hooks";
|
||||
import { redirectIfArchivingActiveWorkspace } from "@/utils/sidebar-workspace-archive-redirect";
|
||||
import { useWorkspaceArchive } from "@/workspace/use-workspace-archive";
|
||||
import { isWorkspaceListed, type WorkspaceArchiveTarget } from "@/workspace/workspace-archive";
|
||||
|
||||
const WORKSPACE_ARCHIVE_ACTIONS: readonly KeyboardActionId[] = ["workspace.archive"];
|
||||
|
||||
// The archive shortcut used to live on the sidebar row, so it did nothing whenever the row was not
|
||||
// rendered — a collapsed project or status group, a collapsed Pinned section, or focus mode. Like
|
||||
// the pin shortcut (see use-global-workspace-pin-action.ts), it is one registration keyed on the
|
||||
// active route selection.
|
||||
export function useGlobalWorkspaceArchiveAction() {
|
||||
const selection = useActiveWorkspaceSelection();
|
||||
const serverId = selection?.serverId ?? null;
|
||||
const routeWorkspaceId = selection?.workspaceId ?? null;
|
||||
// `id` is the descriptor id, not the route id; see use-global-workspace-pin-action.ts.
|
||||
const fields = useWorkspaceFields(serverId, routeWorkspaceId, (workspace) => ({
|
||||
id: workspace.id,
|
||||
workspaceKind: workspace.workspaceKind,
|
||||
workspaceDirectory: workspace.workspaceDirectory,
|
||||
name: workspace.name,
|
||||
archivingAt: workspace.archivingAt,
|
||||
diffStat: workspace.diffStat,
|
||||
}));
|
||||
|
||||
// useWorkspaceArchive calls the latest render's callback, so `activeWorkspaceId` is whatever is
|
||||
// routed when the archive starts, after any confirmation. It is the descriptor id, which is what
|
||||
// the redirect compares against.
|
||||
const activeWorkspaceId = fields?.id ?? null;
|
||||
const redirectAfterArchive = useCallback(
|
||||
(workspace: WorkspaceArchiveTarget) => {
|
||||
redirectIfArchivingActiveWorkspace({
|
||||
...workspace,
|
||||
activeWorkspaceSelection:
|
||||
serverId && activeWorkspaceId ? { serverId, workspaceId: activeWorkspaceId } : null,
|
||||
});
|
||||
},
|
||||
[activeWorkspaceId, serverId],
|
||||
);
|
||||
|
||||
const archiveController = useWorkspaceArchive({
|
||||
serverId: serverId ?? "",
|
||||
workspaceId: fields?.id ?? "",
|
||||
workspaceKind: fields?.workspaceKind ?? "directory",
|
||||
workspaceDirectory: fields?.workspaceDirectory ?? "",
|
||||
name: fields?.name ?? "",
|
||||
diffStat: fields?.diffStat,
|
||||
onArchiveStarted: redirectAfterArchive,
|
||||
});
|
||||
|
||||
const canArchive = fields !== null && fields.archivingAt === null;
|
||||
|
||||
const handle = useCallback(() => {
|
||||
if (!canArchive || !serverId) {
|
||||
return false;
|
||||
}
|
||||
// Archiving hides its target immediately. Read the store in case the shortcut
|
||||
// runs again before React renders that update.
|
||||
if (!isWorkspaceListed({ serverId, workspaceId: fields.id })) {
|
||||
return false;
|
||||
}
|
||||
archiveController.archive();
|
||||
return true;
|
||||
}, [archiveController, canArchive, fields, serverId]);
|
||||
|
||||
useKeyboardActionHandler({
|
||||
handlerId: "workspace-archive-global",
|
||||
actions: WORKSPACE_ARCHIVE_ACTIONS,
|
||||
enabled: canArchive,
|
||||
priority: 0,
|
||||
handle,
|
||||
});
|
||||
}
|
||||
@@ -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: "刚刚",
|
||||
|
||||
@@ -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 },
|
||||
|
||||
@@ -14,6 +14,7 @@ import { buildWorkspaceTabPersistenceKey } from "@/workspace-tabs/model";
|
||||
import { archiveWorkspaceWithUndo, supportsWorkspaceArchiveUndo } from "@/workspace/archive-undo";
|
||||
import {
|
||||
archiveWorkspaceOptimistically,
|
||||
runWorkspaceArchiveAttempt,
|
||||
type WorkspaceArchiveTarget,
|
||||
} from "@/workspace/workspace-archive";
|
||||
|
||||
@@ -56,7 +57,6 @@ export function useWorkspaceArchive(input: ArchiveWorkspaceInput): WorkspaceArch
|
||||
} = input;
|
||||
const { t } = useTranslation();
|
||||
const toast = useToast();
|
||||
const confirmingRef = useRef(false);
|
||||
// The archive starts after the host answers and you confirm. By then you may have opened another
|
||||
// workspace, so the redirect reads the selection from the latest render.
|
||||
const onArchiveStartedRef = useRef(onArchiveStarted);
|
||||
@@ -119,26 +119,12 @@ export function useWorkspaceArchive(input: ArchiveWorkspaceInput): WorkspaceArch
|
||||
}, [diffStat, name, serverId, t, toast, warningLabels, workspaceDirectory]);
|
||||
|
||||
const archive = useCallback(() => {
|
||||
// A second press while the host answers or the warning is open would ask twice.
|
||||
if (confirmingRef.current) {
|
||||
return;
|
||||
}
|
||||
void (async () => {
|
||||
if (workspaceKind === "worktree") {
|
||||
confirmingRef.current = true;
|
||||
let confirmed: boolean;
|
||||
try {
|
||||
confirmed = await confirmWorktreeArchive();
|
||||
} finally {
|
||||
confirmingRef.current = false;
|
||||
}
|
||||
if (!confirmed) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
await archiveWorkspaceRecord();
|
||||
})();
|
||||
}, [archiveWorkspaceRecord, confirmWorktreeArchive, workspaceKind]);
|
||||
void runWorkspaceArchiveAttempt({
|
||||
workspace: { serverId, workspaceId },
|
||||
confirm: workspaceKind === "worktree" ? confirmWorktreeArchive : undefined,
|
||||
archive: archiveWorkspaceRecord,
|
||||
});
|
||||
}, [archiveWorkspaceRecord, confirmWorktreeArchive, serverId, workspaceId, workspaceKind]);
|
||||
|
||||
return {
|
||||
archive,
|
||||
|
||||
@@ -17,6 +17,30 @@ export interface WorkspaceArchiveTarget {
|
||||
workspaceId: string;
|
||||
}
|
||||
|
||||
const pendingArchiveAttempts = new Set<string>();
|
||||
|
||||
/** Checks and starts one archive at a time for a workspace. */
|
||||
export async function runWorkspaceArchiveAttempt(input: {
|
||||
workspace: WorkspaceArchiveTarget;
|
||||
confirm?: () => Promise<boolean>;
|
||||
archive: () => Promise<void>;
|
||||
}): Promise<void> {
|
||||
const { serverId, workspaceId } = input.workspace;
|
||||
const key = JSON.stringify([serverId, workspaceId]);
|
||||
if (pendingArchiveAttempts.has(key)) return;
|
||||
|
||||
pendingArchiveAttempts.add(key);
|
||||
try {
|
||||
if (input.confirm && !(await input.confirm())) return;
|
||||
if (!isWorkspaceListed(input.workspace)) return;
|
||||
// Archive hides the row synchronously. Undo can restore it and start a new
|
||||
// archive while the previous daemon request is still settling.
|
||||
return input.archive();
|
||||
} finally {
|
||||
pendingArchiveAttempts.delete(key);
|
||||
}
|
||||
}
|
||||
|
||||
interface WorkspaceArchiveClient {
|
||||
archiveWorkspace: (workspaceId: string) => Promise<{ error: string | null; canceled?: boolean }>;
|
||||
}
|
||||
|
||||
@@ -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(),
|
||||
|
||||
@@ -350,10 +350,18 @@ index b849f78..24c06f3 100644
|
||||
factory: RendererFactory,
|
||||
) {
|
||||
diff --git a/node_modules/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/renderer/ListRenderer.kt b/node_modules/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/renderer/ListRenderer.kt
|
||||
index 2bac5b1..ff2d2c2 100644
|
||||
index 2bac5b1..021debd 100644
|
||||
--- a/node_modules/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/renderer/ListRenderer.kt
|
||||
+++ b/node_modules/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/renderer/ListRenderer.kt
|
||||
@@ -16,7 +16,7 @@ class ListRenderer(
|
||||
@@ -6,6 +6,7 @@ import com.swmansion.enriched.markdown.spans.ListItemSpacingSpan
|
||||
import com.swmansion.enriched.markdown.spans.MarginBottomSpan
|
||||
import com.swmansion.enriched.markdown.styles.ListStyle
|
||||
import com.swmansion.enriched.markdown.utils.text.span.SPAN_FLAGS_EXCLUSIVE_EXCLUSIVE
|
||||
+import com.swmansion.enriched.markdown.utils.text.span.SPAN_FLAGS_LINE_HEIGHT_PRIORITY
|
||||
import com.swmansion.enriched.markdown.utils.text.span.applyLineHeightSkippingImages
|
||||
import com.swmansion.enriched.markdown.utils.text.span.applyMarginTop
|
||||
|
||||
@@ -16,7 +17,7 @@ class ListRenderer(
|
||||
override fun render(
|
||||
node: MarkdownASTNode,
|
||||
builder: SpannableStringBuilder,
|
||||
@@ -362,6 +370,23 @@ index 2bac5b1..ff2d2c2 100644
|
||||
onLinkLongPress: ((String) -> Unit)?,
|
||||
factory: RendererFactory,
|
||||
) {
|
||||
@@ -68,7 +69,15 @@ class ListRenderer(
|
||||
// TODO: LineHeightSpan may also clip superscript/subscript glyphs that extend
|
||||
// outside the normal line bounds. A similar "skip" strategy as for images may
|
||||
// be needed here once super/subscript usage in practice is better understood.
|
||||
- applyLineHeightSkippingImages(builder, start, builder.length, style.lineHeight)
|
||||
+ // Priority flag so the list-wide line height iterates before inner block spacer
|
||||
+ // spans (blockquote padding/margin, heading margin) instead of inflating them.
|
||||
+ applyLineHeightSkippingImages(
|
||||
+ builder,
|
||||
+ start,
|
||||
+ builder.length,
|
||||
+ style.lineHeight,
|
||||
+ SPAN_FLAGS_LINE_HEIGHT_PRIORITY,
|
||||
+ )
|
||||
|
||||
// Item spacing and external bottom margin are only handled by the root-level list
|
||||
if (depth == 0) {
|
||||
diff --git a/node_modules/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/renderer/NodeRenderer.kt b/node_modules/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/renderer/NodeRenderer.kt
|
||||
index 354b31a..77b1e14 100644
|
||||
--- a/node_modules/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/renderer/NodeRenderer.kt
|
||||
@@ -3006,10 +3031,18 @@ index 0000000..11911c8
|
||||
+ }
|
||||
+}
|
||||
diff --git a/node_modules/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/MeasurementStore.kt b/node_modules/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/MeasurementStore.kt
|
||||
index f4840e4..e36b444 100644
|
||||
index f4840e4..6b7e61f 100644
|
||||
--- a/node_modules/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/MeasurementStore.kt
|
||||
+++ b/node_modules/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/MeasurementStore.kt
|
||||
@@ -66,9 +66,11 @@ object MeasurementStore {
|
||||
@@ -45,6 +45,7 @@ import com.swmansion.enriched.markdown.utils.common.parseLinkPillContent
|
||||
import com.swmansion.enriched.markdown.utils.common.parseLinkRecognition
|
||||
import com.swmansion.enriched.markdown.utils.text.extensions.replaceMathSpansWithPlaceholders
|
||||
import com.swmansion.enriched.markdown.utils.text.span.prepareWidthAwareSpans
|
||||
+import com.swmansion.enriched.markdown.utils.text.view.wrapForInsertionOrderedLayout
|
||||
import java.util.concurrent.ConcurrentHashMap
|
||||
import kotlin.math.ceil
|
||||
|
||||
@@ -66,9 +67,11 @@ object MeasurementStore {
|
||||
val spannable: CharSequence?,
|
||||
val paintParams: PaintParams,
|
||||
val markdownHash: Int,
|
||||
@@ -3021,7 +3054,7 @@ index f4840e4..e36b444 100644
|
||||
|
||||
// Store font scaling settings per view ID
|
||||
private data class FontScalingSettings(
|
||||
@@ -133,7 +135,10 @@ object MeasurementStore {
|
||||
@@ -133,7 +136,10 @@ object MeasurementStore {
|
||||
YogaMeasureOutput.getHeight(newSize) + PixelUtil.toDIPFromPixel(trailingMarginBottomPx),
|
||||
)
|
||||
}
|
||||
@@ -3033,7 +3066,7 @@ index f4840e4..e36b444 100644
|
||||
return oldSize != newSize
|
||||
}
|
||||
|
||||
@@ -144,7 +149,7 @@ object MeasurementStore {
|
||||
@@ -144,7 +150,7 @@ object MeasurementStore {
|
||||
}
|
||||
|
||||
fun invalidate(id: Int) {
|
||||
@@ -3042,7 +3075,7 @@ index f4840e4..e36b444 100644
|
||||
}
|
||||
|
||||
// Content-box width (px) the measure pass last wrapped at; the display view insets to match (#805).
|
||||
@@ -212,7 +217,7 @@ object MeasurementStore {
|
||||
@@ -212,7 +218,7 @@ object MeasurementStore {
|
||||
val previous = fontScalingSettings[viewId]
|
||||
fontScalingSettings[viewId] = FontScalingSettings(allowFontScaling, maxFontSizeMultiplier)
|
||||
if (previous != null && (previous.allowFontScaling != allowFontScaling || previous.maxFontSizeMultiplier != maxFontSizeMultiplier)) {
|
||||
@@ -3051,7 +3084,7 @@ index f4840e4..e36b444 100644
|
||||
}
|
||||
}
|
||||
|
||||
@@ -285,7 +290,43 @@ object MeasurementStore {
|
||||
@@ -285,7 +291,43 @@ object MeasurementStore {
|
||||
|
||||
val fontScale = checkAndUpdateFontScale(context, allowFontScaling, maxFontSizeMultiplier)
|
||||
|
||||
@@ -3096,7 +3129,7 @@ index f4840e4..e36b444 100644
|
||||
if (splitTableSegments) {
|
||||
return measureAndCacheSplit(context, id, width, props, allowFontScaling, fontScale, maxFontSizeMultiplier)
|
||||
}
|
||||
@@ -295,7 +336,7 @@ object MeasurementStore {
|
||||
@@ -295,7 +337,7 @@ object MeasurementStore {
|
||||
|
||||
val currentHash = computePropsHash(props, allowFontScaling, fontScale, maxFontSizeMultiplier)
|
||||
|
||||
@@ -3105,7 +3138,7 @@ index f4840e4..e36b444 100644
|
||||
return measureAndCache(context, safeId, width, props, allowFontScaling, fontScale, maxFontSizeMultiplier)
|
||||
}
|
||||
|
||||
@@ -332,8 +373,11 @@ object MeasurementStore {
|
||||
@@ -332,8 +374,11 @@ object MeasurementStore {
|
||||
val imageRequestHeaders = parseImageRequestHeaders(props.getArrayOrNull("imageRequestHeaders"))
|
||||
val linkPillContent = parseLinkPillContent(props.getArrayOrNull("linkPillContent"))
|
||||
var result = markdown.hashCode()
|
||||
@@ -3119,7 +3152,7 @@ index f4840e4..e36b444 100644
|
||||
result = 31 * result + parseLinkRecognition(props.getMapOrNull("linkRecognition")).hashCode()
|
||||
result = 31 * result + fontScale.toBits()
|
||||
result = 31 * result + allowFontScaling.hashCode()
|
||||
@@ -356,6 +400,7 @@ object MeasurementStore {
|
||||
@@ -356,6 +401,7 @@ object MeasurementStore {
|
||||
if (lastKnownFontScale != 1.0f) {
|
||||
lastKnownFontScale = 1.0f
|
||||
data.clear()
|
||||
@@ -3127,7 +3160,7 @@ index f4840e4..e36b444 100644
|
||||
}
|
||||
return 1.0f
|
||||
}
|
||||
@@ -368,6 +413,7 @@ object MeasurementStore {
|
||||
@@ -368,6 +414,7 @@ object MeasurementStore {
|
||||
if (currentFontScale != lastKnownFontScale) {
|
||||
lastKnownFontScale = currentFontScale
|
||||
data.clear()
|
||||
@@ -3135,6 +3168,52 @@ index f4840e4..e36b444 100644
|
||||
}
|
||||
return currentFontScale
|
||||
}
|
||||
@@ -635,7 +682,7 @@ object MeasurementStore {
|
||||
}
|
||||
}
|
||||
|
||||
- private fun createStaticLayout(
|
||||
+ internal fun createStaticLayout(
|
||||
text: CharSequence,
|
||||
fontSize: Float,
|
||||
widthPx: Int,
|
||||
@@ -643,8 +690,9 @@ object MeasurementStore {
|
||||
): StaticLayout {
|
||||
measurePaint.textSize = fontSize
|
||||
prepareWidthAwareSpans(text, widthPx)
|
||||
+ val measuredText = wrapForInsertionOrderedLayout(text)
|
||||
return StaticLayout.Builder
|
||||
- .obtain(text, 0, text.length, measurePaint, widthPx)
|
||||
+ .obtain(measuredText, 0, measuredText.length, measurePaint, widthPx)
|
||||
.setIncludePad(false)
|
||||
.setLineSpacing(0f, 1f)
|
||||
.apply {
|
||||
@@ -730,10 +778,11 @@ object MeasurementStore {
|
||||
val content = text ?: ""
|
||||
val safeWidth = ceil(maxWidth).toInt().coerceAtLeast(1)
|
||||
prepareWidthAwareSpans(content, safeWidth)
|
||||
+ val measuredText = wrapForInsertionOrderedLayout(content)
|
||||
|
||||
val builder =
|
||||
StaticLayout.Builder
|
||||
- .obtain(content, 0, content.length, paint, safeWidth)
|
||||
+ .obtain(measuredText, 0, measuredText.length, paint, safeWidth)
|
||||
.setIncludePad(false)
|
||||
.setLineSpacing(0f, 1f)
|
||||
|
||||
@@ -836,10 +885,11 @@ object MeasurementStore {
|
||||
val content = text ?: ""
|
||||
val widthPx = ceil(maxWidth).toInt().coerceAtLeast(1)
|
||||
prepareWidthAwareSpans(content, widthPx)
|
||||
+ val measuredText = wrapForInsertionOrderedLayout(content)
|
||||
|
||||
val layout =
|
||||
StaticLayout.Builder
|
||||
- .obtain(content, 0, content.length, paint, widthPx)
|
||||
+ .obtain(measuredText, 0, measuredText.length, paint, widthPx)
|
||||
.setIncludePad(false)
|
||||
.setLineSpacing(0f, 1f)
|
||||
.apply {
|
||||
diff --git a/node_modules/react-native-enriched-markdown/android/src/test/java/com/swmansion/enriched/markdown/MeasurementSizeCacheTest.kt b/node_modules/react-native-enriched-markdown/android/src/test/java/com/swmansion/enriched/markdown/MeasurementSizeCacheTest.kt
|
||||
new file mode 100644
|
||||
index 0000000..b3394c4
|
||||
@@ -3996,3 +4075,290 @@ diff --git a/node_modules/react-native-enriched-markdown/lib/module/web/utils.js
|
||||
+}
|
||||
//# sourceMappingURL=utils.js.map
|
||||
\ No newline at end of file
|
||||
diff --git a/node_modules/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/utils/text/view/TextViewSetup.kt b/node_modules/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/utils/text/view/TextViewSetup.kt
|
||||
index 4b2ad01..8742c0c 100644
|
||||
--- a/node_modules/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/utils/text/view/TextViewSetup.kt
|
||||
+++ b/node_modules/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/utils/text/view/TextViewSetup.kt
|
||||
@@ -11,6 +11,9 @@ import androidx.appcompat.widget.AppCompatTextView
|
||||
import androidx.core.view.ViewCompat
|
||||
import com.swmansion.enriched.markdown.accessibility.AccessibleMarkdownTextView
|
||||
|
||||
+internal fun wrapForInsertionOrderedLayout(source: CharSequence): CharSequence =
|
||||
+ if (source is SpannableStringBuilder) InsertionOrderedSpannable(source) else source
|
||||
+
|
||||
/**
|
||||
* Adopts the renderer's buffer instead of copying it: the default factory's copy is
|
||||
* quadratic in span count. Safe because each segment's buffer is owned by one view.
|
||||
diff --git a/node_modules/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/segments/SegmentHeightMeasurer.kt b/node_modules/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/segments/SegmentHeightMeasurer.kt
|
||||
index 162ebfb..6e40bd8 100644
|
||||
--- a/node_modules/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/segments/SegmentHeightMeasurer.kt
|
||||
+++ b/node_modules/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/segments/SegmentHeightMeasurer.kt
|
||||
@@ -9,6 +9,7 @@ import android.text.TextPaint
|
||||
import com.swmansion.enriched.markdown.styles.StyleConfig
|
||||
import com.swmansion.enriched.markdown.utils.text.extensions.replaceMathSpansWithPlaceholders
|
||||
import com.swmansion.enriched.markdown.utils.text.span.prepareWidthAwareSpans
|
||||
+import com.swmansion.enriched.markdown.utils.text.view.wrapForInsertionOrderedLayout
|
||||
import kotlin.math.ceil
|
||||
|
||||
/**
|
||||
@@ -105,8 +106,9 @@ object SegmentHeightMeasurer {
|
||||
textSize = fontSizePx
|
||||
}
|
||||
prepareWidthAwareSpans(text, widthPx)
|
||||
+ val measuredText = wrapForInsertionOrderedLayout(text)
|
||||
return StaticLayout.Builder
|
||||
- .obtain(text, 0, text.length, paint, widthPx)
|
||||
+ .obtain(measuredText, 0, measuredText.length, paint, widthPx)
|
||||
.setIncludePad(false)
|
||||
.setLineSpacing(0f, 1f)
|
||||
.apply {
|
||||
diff --git a/b/node_modules/react-native-enriched-markdown/android/src/test/java/com/swmansion/enriched/markdown/ListBlockquoteMeasurementTest.kt b/node_modules/react-native-enriched-markdown/android/src/test/java/com/swmansion/enriched/markdown/ListBlockquoteMeasurementTest.kt
|
||||
new file mode 100644
|
||||
index 0000000..6115a30
|
||||
--- /dev/null
|
||||
+++ b/node_modules/react-native-enriched-markdown/android/src/test/java/com/swmansion/enriched/markdown/ListBlockquoteMeasurementTest.kt
|
||||
@@ -0,0 +1,244 @@
|
||||
+package com.swmansion.enriched.markdown
|
||||
+
|
||||
+import android.graphics.Paint
|
||||
+import android.text.Layout
|
||||
+import android.text.SpannableStringBuilder
|
||||
+import android.text.style.LineHeightSpan as AndroidLineHeightSpan
|
||||
+import android.util.TypedValue
|
||||
+import android.view.View.MeasureSpec
|
||||
+import com.facebook.react.bridge.JavaOnlyArray
|
||||
+import com.facebook.react.bridge.JavaOnlyMap
|
||||
+import com.facebook.react.uimanager.DisplayMetricsHolder
|
||||
+import com.swmansion.enriched.markdown.parser.MarkdownASTNode
|
||||
+import com.swmansion.enriched.markdown.parser.MarkdownASTNode.NodeType
|
||||
+import com.swmansion.enriched.markdown.renderer.Renderer
|
||||
+import com.swmansion.enriched.markdown.segments.SegmentHeightMeasurer
|
||||
+import com.swmansion.enriched.markdown.spans.LineHeightSpan
|
||||
+import com.swmansion.enriched.markdown.styles.StyleConfig
|
||||
+import com.swmansion.enriched.markdown.utils.text.span.SPAN_FLAGS_EXCLUSIVE_EXCLUSIVE
|
||||
+import org.junit.Assert.assertEquals
|
||||
+import org.junit.Test
|
||||
+import org.junit.runner.RunWith
|
||||
+import org.robolectric.RobolectricTestRunner
|
||||
+import org.robolectric.RuntimeEnvironment
|
||||
+import org.robolectric.annotation.Config
|
||||
+import org.robolectric.annotation.GraphicsMode
|
||||
+
|
||||
+@RunWith(RobolectricTestRunner::class)
|
||||
+@GraphicsMode(GraphicsMode.Mode.NATIVE)
|
||||
+@Config(manifest = Config.NONE, sdk = [34])
|
||||
+class ListBlockquoteMeasurementTest {
|
||||
+ private fun styleConfig(): StyleConfig {
|
||||
+ val context = RuntimeEnvironment.getApplication()
|
||||
+ DisplayMetricsHolder.initDisplayMetricsIfNotInitialized(context)
|
||||
+ val base =
|
||||
+ JavaOnlyMap.of(
|
||||
+ "fontFamily", "",
|
||||
+ "fontWeight", "normal",
|
||||
+ "fontStyle", "normal",
|
||||
+ "fontSize", 16.0,
|
||||
+ "lineHeight", 22.0,
|
||||
+ "color", -16777216.0,
|
||||
+ "backgroundColor", 0.0,
|
||||
+ "borderColor", 0.0,
|
||||
+ "borderWidth", 3.0,
|
||||
+ "borderRadius", 0.0,
|
||||
+ "padding", 12.0,
|
||||
+ "gapWidth", 8.0,
|
||||
+ "marginTop", 0.0,
|
||||
+ "marginBottom", 12.0,
|
||||
+ "marginLeft", 20.0,
|
||||
+ "itemSpacing", 4.0,
|
||||
+ "bulletColor", -16777216.0,
|
||||
+ "bulletSize", 6.0,
|
||||
+ "markerMinWidth", 0.0,
|
||||
+ "markerColor", -16777216.0,
|
||||
+ "markerFontWeight", "normal",
|
||||
+ "textAlign", "left",
|
||||
+ "underline", false,
|
||||
+ "checkedColor", 0.0,
|
||||
+ "checkmarkColor", 0.0,
|
||||
+ "checkedTextColor", 0.0,
|
||||
+ "checkboxSize", 18.0,
|
||||
+ "checkboxBorderRadius", 2.0,
|
||||
+ "checkedStrikethrough", false,
|
||||
+ "particles", JavaOnlyMap.of("density", 1.0, "speed", 1.0),
|
||||
+ "solid", JavaOnlyMap.of("borderRadius", 0.0),
|
||||
+ "fontScale", 0.7,
|
||||
+ "baselineOffsetScale", 0.3,
|
||||
+ )
|
||||
+ val styles = JavaOnlyMap()
|
||||
+ listOf(
|
||||
+ "paragraph",
|
||||
+ "h1",
|
||||
+ "h2",
|
||||
+ "h3",
|
||||
+ "h4",
|
||||
+ "h5",
|
||||
+ "h6",
|
||||
+ "strong",
|
||||
+ "em",
|
||||
+ "strikethrough",
|
||||
+ "underline",
|
||||
+ "link",
|
||||
+ "code",
|
||||
+ "blockquote",
|
||||
+ "list",
|
||||
+ "codeBlock",
|
||||
+ "thematicBreak",
|
||||
+ "image",
|
||||
+ "inlineImage",
|
||||
+ "video",
|
||||
+ "table",
|
||||
+ "taskList",
|
||||
+ "math",
|
||||
+ "inlineMath",
|
||||
+ "spoiler",
|
||||
+ "superscript",
|
||||
+ "subscript",
|
||||
+ "highlight",
|
||||
+ ).forEach { styles.putMap(it, base) }
|
||||
+ styles.putArray("linkVariants", JavaOnlyArray())
|
||||
+ return StyleConfig(styles, context, allowFontScaling = false, maxFontSizeMultiplier = 1f)
|
||||
+ }
|
||||
+
|
||||
+ private fun measureTextView(
|
||||
+ text: CharSequence,
|
||||
+ fontSizePx: Float,
|
||||
+ widthPx: Int,
|
||||
+ ): EnrichedMarkdownInternalText {
|
||||
+ val context = RuntimeEnvironment.getApplication()
|
||||
+ return EnrichedMarkdownInternalText(context).apply {
|
||||
+ setTextSize(TypedValue.COMPLEX_UNIT_PX, fontSizePx)
|
||||
+ breakStrategy = Layout.BREAK_STRATEGY_HIGH_QUALITY
|
||||
+ applyStyledText(text)
|
||||
+ measure(
|
||||
+ MeasureSpec.makeMeasureSpec(widthPx, MeasureSpec.EXACTLY),
|
||||
+ MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
|
||||
+ )
|
||||
+ }
|
||||
+ }
|
||||
+
|
||||
+ @Test
|
||||
+ fun listNestedBlockquotesMatchMeasurementAndKeepSpacerHeights() {
|
||||
+ val context = RuntimeEnvironment.getApplication()
|
||||
+ val style = styleConfig()
|
||||
+ val widthPx = 640
|
||||
+ val fontSizePx = style.paragraphStyle.fontSize
|
||||
+
|
||||
+ val ast =
|
||||
+ MarkdownASTNode(
|
||||
+ NodeType.Document,
|
||||
+ children =
|
||||
+ listOf(
|
||||
+ MarkdownASTNode(
|
||||
+ NodeType.OrderedList,
|
||||
+ attributes = mapOf("start" to "1"),
|
||||
+ children =
|
||||
+ listOf(
|
||||
+ MarkdownASTNode(
|
||||
+ NodeType.ListItem,
|
||||
+ children =
|
||||
+ listOf(
|
||||
+ MarkdownASTNode(NodeType.Paragraph, children = listOf(MarkdownASTNode(NodeType.Text, "First item"))),
|
||||
+ MarkdownASTNode(
|
||||
+ NodeType.Blockquote,
|
||||
+ children =
|
||||
+ listOf(
|
||||
+ MarkdownASTNode(NodeType.Paragraph, children = listOf(MarkdownASTNode(NodeType.Text, "First quote"))),
|
||||
+ ),
|
||||
+ ),
|
||||
+ ),
|
||||
+ ),
|
||||
+ MarkdownASTNode(
|
||||
+ NodeType.ListItem,
|
||||
+ children =
|
||||
+ listOf(
|
||||
+ MarkdownASTNode(NodeType.Paragraph, children = listOf(MarkdownASTNode(NodeType.Text, "Second item"))),
|
||||
+ MarkdownASTNode(
|
||||
+ NodeType.Blockquote,
|
||||
+ children =
|
||||
+ listOf(
|
||||
+ MarkdownASTNode(NodeType.Paragraph, children = listOf(MarkdownASTNode(NodeType.Text, "Second quote"))),
|
||||
+ ),
|
||||
+ ),
|
||||
+ ),
|
||||
+ ),
|
||||
+ ),
|
||||
+ ),
|
||||
+ MarkdownASTNode(NodeType.Paragraph, children = listOf(MarkdownASTNode(NodeType.Text, "Trailing paragraph"))),
|
||||
+ ),
|
||||
+ )
|
||||
+
|
||||
+ val renderer = Renderer().apply { configure(style, context) }
|
||||
+ val rendered = renderer.renderDocument(ast)
|
||||
+
|
||||
+ val storeLayout = MeasurementStore.createStaticLayout(rendered, fontSizePx, widthPx, null)
|
||||
+ val segmentLayout =
|
||||
+ SegmentHeightMeasurer.createStaticLayout(rendered, fontSizePx, widthPx, Layout.BREAK_STRATEGY_HIGH_QUALITY)
|
||||
+ val textView = measureTextView(rendered, fontSizePx, widthPx)
|
||||
+
|
||||
+ assertEquals("MeasurementStore and TextView must agree on height", textView.measuredHeight, storeLayout.height)
|
||||
+ assertEquals("SegmentHeightMeasurer and TextView must agree on height", textView.measuredHeight, segmentLayout.height)
|
||||
+
|
||||
+ // Verify blockquote top-padding and bottom-margin spacer lines keep their configured
|
||||
+ // heights instead of being inflated to list.lineHeight (22dp).
|
||||
+ val paddingPx = style.blockquoteStyle.padding.toInt()
|
||||
+ val marginBottomPx = style.blockquoteStyle.marginBottom.toInt()
|
||||
+ val itemSpacingPx = style.listStyle.itemSpacing.toInt()
|
||||
+ val spacerLineHeights =
|
||||
+ (0 until storeLayout.lineCount)
|
||||
+ .filter { line ->
|
||||
+ val start = storeLayout.getLineStart(line)
|
||||
+ val end = storeLayout.getLineEnd(line)
|
||||
+ end - start == 1 && rendered[start] == '\n'
|
||||
+ }.map { line -> storeLayout.getLineBottom(line) - storeLayout.getLineTop(line) }
|
||||
+
|
||||
+ assertEquals(
|
||||
+ listOf(paddingPx, marginBottomPx + itemSpacingPx, paddingPx, marginBottomPx, marginBottomPx),
|
||||
+ spacerLineHeights,
|
||||
+ )
|
||||
+ }
|
||||
+
|
||||
+ @Test
|
||||
+ fun measurementStaticLayoutUsesInsertionOrderLikeTextView() {
|
||||
+ val context = RuntimeEnvironment.getApplication()
|
||||
+ DisplayMetricsHolder.initDisplayMetricsIfNotInitialized(context)
|
||||
+ val widthPx = 400
|
||||
+ val fontSizePx = 16f
|
||||
+
|
||||
+ // Inner priority-0 spacer inserted before outer priority-0 LineHeightSpan:
|
||||
+ // SpannableStringBuilder's unsorted fast path orders by start offset (outer first),
|
||||
+ // while InsertionOrderedSpannable orders by insertion order (inner first, so outer inflates it).
|
||||
+ val builder = SpannableStringBuilder("first\n\nsecond")
|
||||
+ builder.setSpan(
|
||||
+ object : AndroidLineHeightSpan {
|
||||
+ override fun chooseHeight(
|
||||
+ text: CharSequence,
|
||||
+ start: Int,
|
||||
+ end: Int,
|
||||
+ spanstartv: Int,
|
||||
+ v: Int,
|
||||
+ fm: Paint.FontMetricsInt,
|
||||
+ ) {
|
||||
+ fm.top = 0
|
||||
+ fm.ascent = 0
|
||||
+ fm.descent = 12
|
||||
+ fm.bottom = 12
|
||||
+ }
|
||||
+ },
|
||||
+ 6,
|
||||
+ 7,
|
||||
+ SPAN_FLAGS_EXCLUSIVE_EXCLUSIVE,
|
||||
+ )
|
||||
+ builder.setSpan(LineHeightSpan(40f), 0, builder.length, SPAN_FLAGS_EXCLUSIVE_EXCLUSIVE)
|
||||
+
|
||||
+ val storeLayout = MeasurementStore.createStaticLayout(builder, fontSizePx, widthPx, null)
|
||||
+ val segmentLayout =
|
||||
+ SegmentHeightMeasurer.createStaticLayout(builder, fontSizePx, widthPx, Layout.BREAK_STRATEGY_HIGH_QUALITY)
|
||||
+ val textView = measureTextView(builder, fontSizePx, widthPx)
|
||||
+
|
||||
+ assertEquals(textView.measuredHeight, storeLayout.height)
|
||||
+ assertEquals(textView.measuredHeight, segmentLayout.height)
|
||||
+ }
|
||||
+}
|
||||
|
||||
@@ -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