mirror of
https://github.com/getpaseo/paseo.git
synced 2026-11-21 07:45:38 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
59a21245bd | ||
|
|
6b1311d3b2 | ||
|
|
b9196fa259 | ||
|
|
c086c8a5ad | ||
|
|
af2498ae99 | ||
|
|
5a16dd0c13 | ||
|
|
a85695679a | ||
|
|
e7245e0883 |
@@ -1,149 +0,0 @@
|
||||
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,34 +503,6 @@ test.describe("terminal history with a finger", () => {
|
||||
await expectMouseWheelScrollsHistory(page);
|
||||
});
|
||||
|
||||
test("finger scrolling leaves terminal input unfocused until a tap", async ({ page }) => {
|
||||
await openPhoneTerminalHistory(page);
|
||||
await blurTerminalInput(page);
|
||||
|
||||
await expectSingleFingerScroll(page, 24);
|
||||
await expect(input(page)).not.toBeFocused();
|
||||
await expectSingleFingerScroll(page, 1);
|
||||
await expect(input(page)).not.toBeFocused();
|
||||
|
||||
await tapTerminalScreen(page);
|
||||
await expect(input(page)).toBeFocused();
|
||||
});
|
||||
|
||||
test("finger scrolling keeps a floating keyboard's input focused", async ({ page }) => {
|
||||
await openPhoneTerminalHistory(page);
|
||||
await tapTerminalScreen(page);
|
||||
await expect(input(page)).toBeFocused();
|
||||
|
||||
// A floating keyboard leaves the visual viewport unchanged.
|
||||
await expectSingleFingerScroll(page, 24);
|
||||
await expect(input(page)).toBeFocused();
|
||||
await expect(input(page)).toHaveAttribute("virtualkeyboardpolicy", "manual");
|
||||
|
||||
// Android Back also leaves the input focused. A tap restores automatic keyboard opening.
|
||||
await tapTerminalScreen(page);
|
||||
await expect(input(page)).not.toHaveAttribute("virtualkeyboardpolicy");
|
||||
});
|
||||
|
||||
for (const mode of ["alternate", "mouse"] as const) {
|
||||
test(`preserves finger navigation in ${mode} input mode`, async ({ page }) => {
|
||||
await openPhoneInputCapture(page, mode);
|
||||
@@ -559,26 +531,6 @@ async function openPhoneTerminalHistory(page: Page) {
|
||||
});
|
||||
await openPhoneTerminal(page);
|
||||
await expect.poll(() => getTerminalBufferText(page)).toContain("HISTORY_150");
|
||||
await expect
|
||||
.poll(() => page.evaluate(() => window.__paseoTerminal!.buffer.active.baseY))
|
||||
.toBeGreaterThan(0);
|
||||
await page.evaluate(() => window.__paseoTerminal!.scrollToBottom());
|
||||
await expect.poll(() => viewport(page)).toBeGreaterThan(0);
|
||||
}
|
||||
|
||||
function terminalScreen(page: Page) {
|
||||
return page.getByTestId("terminal-surface").filter({ visible: true }).locator(".xterm-screen");
|
||||
}
|
||||
|
||||
async function tapTerminalScreen(page: Page) {
|
||||
const box = await terminalScreen(page).boundingBox();
|
||||
expect(box).not.toBeNull();
|
||||
await page.touchscreen.tap(box!.x + box!.width / 2, box!.y + box!.height / 3);
|
||||
}
|
||||
|
||||
async function blurTerminalInput(page: Page) {
|
||||
await input(page).evaluate((element) => element.blur());
|
||||
await expect(input(page)).not.toBeFocused();
|
||||
}
|
||||
|
||||
async function openPhoneInputCapture(page: Page, mode: "alternate" | "mouse") {
|
||||
@@ -618,20 +570,6 @@ async function openPhoneTerminal(page: Page) {
|
||||
await page.getByTestId(`sidebar-workspace-row-${getServerId()}:${harness.workspaceId}`).click();
|
||||
await expect(page.getByRole("textbox", { name: "Terminal input" })).toBeVisible();
|
||||
await expect(page.getByTestId("terminal-surface").filter({ visible: true })).toBeVisible();
|
||||
// The terminal stays mounted while the sidebar's closing backdrop still intercepts input.
|
||||
await expect
|
||||
.poll(() =>
|
||||
page
|
||||
.getByTestId("terminal-surface")
|
||||
.filter({ visible: true })
|
||||
.evaluate((root) => {
|
||||
const box = root.querySelector(".xterm-screen")!.getBoundingClientRect();
|
||||
return root.contains(
|
||||
document.elementFromPoint(box.x + box.width / 2, box.y + box.height / 3),
|
||||
);
|
||||
}),
|
||||
)
|
||||
.toBe(true);
|
||||
}
|
||||
|
||||
async function expectMouseWheelScrollsHistory(page: Page) {
|
||||
|
||||
@@ -2,14 +2,13 @@ import { tmpdir } from "node:os";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import path from "node:path";
|
||||
import type { Page } from "@playwright/test";
|
||||
import type { UsageReport, UsageReportEntry } from "@getpaseo/protocol/messages";
|
||||
import type { UsageReportEntry } from "@getpaseo/protocol/messages";
|
||||
import { expect, test } from "../support/fixtures";
|
||||
import { gotoAppShell, openSettings } from "../support/helpers/app";
|
||||
import { addConnectedHostAndReload } from "../support/helpers/hosts";
|
||||
import { startIsolatedHostDaemon } from "../support/helpers/isolated-host-daemon";
|
||||
import { openSettingsSection } from "../support/helpers/settings";
|
||||
import { gate } from "../support/helpers/context-window";
|
||||
import { installDaemonWebSocketGate } from "../support/helpers/daemon-websocket-gate";
|
||||
import { getServerId } from "../support/helpers/server-id";
|
||||
import { seedSidebarFooterPreferences } from "../support/helpers/sidebar-nav-settings";
|
||||
import {
|
||||
@@ -46,7 +45,6 @@ import {
|
||||
refreshAllUsage,
|
||||
togglePin,
|
||||
usageItem,
|
||||
usageModal,
|
||||
} from "../support/helpers/usage-sidebar-item";
|
||||
|
||||
const emptyHome = path.join(tmpdir(), `paseo-usage-empty-${randomUUID()}`);
|
||||
@@ -867,106 +865,6 @@ test("open usage clocks advance without refreshing or reopening", async ({ page
|
||||
}
|
||||
});
|
||||
|
||||
test("Refresh all keeps quota visible and restores the forecast after a timeout", async ({
|
||||
page,
|
||||
}) => {
|
||||
const reading = new Date();
|
||||
const login = await installLoginUsage(usageReading(reading, 40));
|
||||
try {
|
||||
const transport = await installDaemonWebSocketGate(page);
|
||||
await openCompactUsageWithClock(page, reading);
|
||||
await expectQuota(page, "40% used", /runs out in /);
|
||||
|
||||
await timeOutUsageRefresh(page, transport);
|
||||
await expectQuota(page, "40% used", null);
|
||||
await expectUsageRefreshError(page).toBeVisible();
|
||||
|
||||
await login.setReport(usageReading(reading, 10));
|
||||
transport.releaseHeldClientRequest();
|
||||
await refreshAllUsage(page);
|
||||
await expectQuota(page, "10% used", "~50% left at reset");
|
||||
await expectUsageRefreshError(page).toBeHidden();
|
||||
} finally {
|
||||
await login.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("a card refresh timeout is visible alongside a newer quota forecast", async ({ page }) => {
|
||||
const reading = new Date();
|
||||
const login = await installLoginUsage(usageReading(reading, 40));
|
||||
try {
|
||||
const transport = await installDaemonWebSocketGate(page);
|
||||
await openCompactUsageWithClock(page, reading);
|
||||
await expectQuota(page, "40% used", /runs out in /);
|
||||
|
||||
await delayCardRefreshResponse(page, transport);
|
||||
await login.setReport(usageReading(reading, 10));
|
||||
await refreshAllUsage(page);
|
||||
await expectQuota(page, "10% used", "~50% left at reset");
|
||||
|
||||
await advanceUsageClock(page, 61_000);
|
||||
await expectUsageRefreshError(page).toBeVisible();
|
||||
await expectQuota(page, "10% used", "~50% left at reset");
|
||||
} finally {
|
||||
await login.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
function expectUsageRefreshError(page: Page) {
|
||||
return expect(usageModal(page).getByText("Unable to refresh usage", { exact: true }));
|
||||
}
|
||||
|
||||
async function delayCardRefreshResponse(
|
||||
page: Page,
|
||||
transport: Awaited<ReturnType<typeof installDaemonWebSocketGate>>,
|
||||
) {
|
||||
await expect(page.getByRole("button", { name: "Refresh all", exact: true })).toBeEnabled();
|
||||
transport.holdNextServerMessage("usage.list_reports.response");
|
||||
await refreshLoginUsage(page);
|
||||
await transport.waitForHeldServerMessage("usage.list_reports.response");
|
||||
}
|
||||
|
||||
function usageReading(observed: Date, usedPct: number): UsageReport {
|
||||
return {
|
||||
status: "available",
|
||||
observedAt: observed.toISOString(),
|
||||
windows: [
|
||||
{
|
||||
id: "session",
|
||||
label: "Session",
|
||||
usedPct,
|
||||
durationSeconds: 18_000,
|
||||
resetsAt: new Date(observed.getTime() + 4 * 3_600_000).toISOString(),
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
async function expectQuota(page: Page, amount: string, forecast: string | RegExp | null) {
|
||||
const usage = usageModal(page);
|
||||
await expect(usage.getByText(amount, { exact: true })).toBeVisible();
|
||||
await expect(usage.getByText(/^resets in /)).toBeVisible();
|
||||
if (forecast === null) {
|
||||
await expect(usage.getByText(/^runs out in /)).toBeHidden();
|
||||
return;
|
||||
}
|
||||
await expect(usage.getByText(forecast)).toBeVisible();
|
||||
}
|
||||
|
||||
async function timeOutUsageRefresh(
|
||||
page: Page,
|
||||
transport: Awaited<ReturnType<typeof installDaemonWebSocketGate>>,
|
||||
) {
|
||||
const refresh = page.getByRole("button", { name: "Refresh all", exact: true });
|
||||
await expect(refresh).toBeEnabled();
|
||||
transport.holdNextClientRequest("usage.list_reports.request");
|
||||
await refreshAllUsage(page);
|
||||
await transport.waitForHeldClientRequest();
|
||||
await expect(refresh).toBeDisabled();
|
||||
await advanceUsageClock(page, 61_000);
|
||||
await expect(refresh).toBeEnabled();
|
||||
}
|
||||
|
||||
async function openCompactUsageWithClock(page: Page, now: Date) {
|
||||
await page.setViewportSize({ width: 390, height: 844 });
|
||||
await page.clock.install({ time: now });
|
||||
|
||||
@@ -318,37 +318,6 @@ 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,7 +20,6 @@ import {
|
||||
} from "../support/helpers/sidebar";
|
||||
import { createTempGitRepo } from "../support/helpers/workspace";
|
||||
import {
|
||||
pressArchiveShortcut,
|
||||
rowArchiveButton,
|
||||
undoButton,
|
||||
workspaceRow,
|
||||
@@ -99,18 +98,6 @@ 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?: {
|
||||
@@ -224,28 +211,18 @@ 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,
|
||||
worktree: { workspaceDirectory: string; workspaceId: string },
|
||||
) {
|
||||
async function holdCheckoutStatusRequest(page: Page, directory: 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 === worktree.workspaceDirectory
|
||||
request.cwd === directory
|
||||
) {
|
||||
held = () => server.send(message);
|
||||
return;
|
||||
@@ -259,7 +236,6 @@ async function holdCheckoutStatusRequest(
|
||||
armed = true;
|
||||
},
|
||||
waitForHeld: () => expect.poll(() => held !== null).toBe(true),
|
||||
archiveRequests: () => archiveRequests,
|
||||
release: () => {
|
||||
if (!held) throw new Error("No checkout status request is held");
|
||||
held();
|
||||
@@ -412,7 +388,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);
|
||||
const statusRequest = await holdCheckoutStatusRequest(page, worktree.workspaceDirectory);
|
||||
await openSidebarRow(page, worktree.workspaceId);
|
||||
await workspaceRow(page, worktree.workspaceId).click();
|
||||
await expectAppRoute(page, buildHostWorkspaceRoute(serverId, worktree.workspaceId));
|
||||
@@ -456,82 +432,6 @@ 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,15 +185,13 @@ function onLogin(report: UsageReportEntry, login: string): UsageReportEntry {
|
||||
}
|
||||
|
||||
export function expiredLogin(report: UsageReportEntry): UsageReportEntry {
|
||||
const fetchedAt = Date.now();
|
||||
return {
|
||||
...report,
|
||||
fetchedAt: new Date(fetchedAt).toISOString(),
|
||||
report: {
|
||||
status: "unavailable",
|
||||
problem: {
|
||||
kind: "expired",
|
||||
expiresAt: new Date(fetchedAt - 2 * 60 * 60_000).toISOString(),
|
||||
expiresAt: new Date(Date.now() - 2 * 60 * 60_000).toISOString(),
|
||||
refreshedBy: "claude",
|
||||
},
|
||||
},
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { expect, test, type Page } from "@playwright/test";
|
||||
import { expect, type Page } from "@playwright/test";
|
||||
import { openChangesPanel } from "./branch-switcher";
|
||||
|
||||
export async function restoreArchivedWorkspace(page: Page): Promise<void> {
|
||||
@@ -32,11 +32,7 @@ export async function expectCommittedFile(page: Page, filename: string): Promise
|
||||
}
|
||||
|
||||
export async function expectCommittedFileAfterReload(page: Page, filename: string): Promise<void> {
|
||||
await test.step("See the committed file immediately after Restore", async () => {
|
||||
await expectCommittedFile(page, filename);
|
||||
});
|
||||
await test.step("Reload and see the same committed file", async () => {
|
||||
await page.reload();
|
||||
await expectCommittedFile(page, filename);
|
||||
});
|
||||
await expectCommittedFile(page, filename);
|
||||
await page.reload();
|
||||
await expectCommittedFile(page, filename);
|
||||
}
|
||||
|
||||
@@ -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' --tests '*ListBlockquoteMeasurementTest' --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' --no-daemon --max-workers=2 -Dorg.gradle.parallel=false"
|
||||
},
|
||||
"dependencies": {
|
||||
"@codemirror/commands": "6.10.4",
|
||||
|
||||
@@ -66,7 +66,6 @@
|
||||
[role="slider"],
|
||||
[role="menuitem"],
|
||||
[tabindex],
|
||||
[data-window-no-drag],
|
||||
[contenteditable="true"] {
|
||||
-webkit-app-region: no-drag !important;
|
||||
}
|
||||
|
||||
@@ -54,7 +54,6 @@ 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";
|
||||
@@ -538,7 +537,6 @@ function AppContainer({ children, chromeEnabled: chromeEnabledOverride }: AppCon
|
||||
<View style={layoutStyles.surfaceFill}>
|
||||
{workspaceChrome}
|
||||
<AddHostFlowHost />
|
||||
<WorkspaceArchiveShortcutHandler />
|
||||
<AppearanceStyleBoundary>
|
||||
{!isCompactLayout && appChromeLayout.sidebarToggleOwner === "window" ? (
|
||||
<WindowChromeRegion corners="top-left">
|
||||
|
||||
@@ -24,9 +24,6 @@ import { isNative } from "@/constants/platform";
|
||||
*/
|
||||
export const WINDOW_CONTENT_DATASET = { "window-content": "" };
|
||||
|
||||
/** Reserves a clickable area for a control mounted outside the titlebar rail. */
|
||||
export const WINDOW_NO_DRAG_DATASET = { "window-no-drag": "" };
|
||||
|
||||
export const titlebarDragSurfaceStyle: React.CSSProperties = {
|
||||
cursor: "default",
|
||||
// @ts-expect-error — WebkitAppRegion is not in CSSProperties
|
||||
|
||||
@@ -27,7 +27,6 @@ const NO_SHORTCUT: ShortcutKey[] = [];
|
||||
interface CompactHeaderProps {
|
||||
/** The leading island: the sidebar menu, or a back button. */
|
||||
navigation: "menu" | "back";
|
||||
inDesktopTitlebar?: boolean;
|
||||
/** Back button action. Defaults to navigating back. */
|
||||
onBack?: () => void;
|
||||
title?: string;
|
||||
@@ -50,7 +49,6 @@ interface CompactHeaderProps {
|
||||
*/
|
||||
export function CompactHeader({
|
||||
navigation,
|
||||
inDesktopTitlebar = false,
|
||||
onBack,
|
||||
title,
|
||||
titleTestID,
|
||||
@@ -60,28 +58,22 @@ export function CompactHeader({
|
||||
}: CompactHeaderProps) {
|
||||
const insets = useSafeAreaInsets();
|
||||
const inTopBand = useTopBand() !== null;
|
||||
const usesTitlebarHeight = inTopBand || inDesktopTitlebar;
|
||||
const rootStyle = useMemo(
|
||||
() => [
|
||||
styles.root,
|
||||
{
|
||||
paddingTop: insets.top + (usesTitlebarHeight ? 0 : HEADER_TOP_PADDING_MOBILE),
|
||||
paddingTop: insets.top + (inTopBand ? 0 : HEADER_TOP_PADDING_MOBILE),
|
||||
marginLeft: insets.left,
|
||||
marginRight: insets.right,
|
||||
},
|
||||
],
|
||||
[usesTitlebarHeight, insets.top, insets.left, insets.right],
|
||||
[inTopBand, insets.top, insets.left, insets.right],
|
||||
);
|
||||
|
||||
return (
|
||||
<IconButtonChromeProvider value="header-island">
|
||||
<View style={rootStyle}>
|
||||
<View
|
||||
style={[
|
||||
usesTitlebarHeight ? styles.titlebarRow : styles.row,
|
||||
inDesktopTitlebar && styles.desktopTitlebarDividerSpace,
|
||||
]}
|
||||
>
|
||||
<View style={inTopBand ? styles.topBandRow : styles.row}>
|
||||
<View style={styles.island}>
|
||||
{navigation === "menu" ? <SidebarMenuToggle /> : <BackButton onBack={onBack} />}
|
||||
</View>
|
||||
@@ -163,16 +155,12 @@ const styles = StyleSheet.create((theme) => ({
|
||||
alignItems: "center",
|
||||
gap: theme.spacing[2],
|
||||
},
|
||||
titlebarRow: {
|
||||
topBandRow: {
|
||||
height: HEADER_INNER_HEIGHT,
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: theme.spacing[2],
|
||||
},
|
||||
desktopTitlebarDividerSpace: {
|
||||
borderBottomWidth: theme.borderWidth[1],
|
||||
borderBottomColor: "transparent",
|
||||
},
|
||||
titleGroup: {
|
||||
flex: 1,
|
||||
minWidth: 0,
|
||||
|
||||
@@ -128,6 +128,7 @@ 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 {
|
||||
@@ -1297,6 +1298,17 @@ 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,6 +42,7 @@ 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,
|
||||
@@ -701,6 +702,17 @@ 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,7 +13,6 @@ import {
|
||||
useRef,
|
||||
type CSSProperties,
|
||||
type MouseEvent as ReactMouseEvent,
|
||||
type PointerEvent as ReactPointerEvent,
|
||||
type Ref,
|
||||
} from "react";
|
||||
import type { DOMProps } from "expo/dom";
|
||||
@@ -64,12 +63,6 @@ const HOST_DIV_STYLE: CSSProperties = {
|
||||
paddingRight: 0,
|
||||
};
|
||||
|
||||
interface TerminalTouchFocus {
|
||||
pointerId: number;
|
||||
x: number;
|
||||
y: number;
|
||||
}
|
||||
|
||||
function buildXtermThemeKey(theme: ITheme): string {
|
||||
const values: Array<string> = [
|
||||
theme.background,
|
||||
@@ -560,46 +553,10 @@ export default function TerminalEmulator({
|
||||
});
|
||||
}, []);
|
||||
|
||||
const touchFocusRef = useRef<TerminalTouchFocus | null>(null);
|
||||
|
||||
const handleRootPointerDown = useCallback(
|
||||
(event: ReactPointerEvent) => {
|
||||
onFocus?.();
|
||||
touchFocusRef.current = null;
|
||||
if (event.pointerType !== "touch") {
|
||||
runtimeRef.current?.focus();
|
||||
return;
|
||||
}
|
||||
// Focusing before a touch becomes a tap opens the keyboard during a scroll.
|
||||
if (event.isPrimary) {
|
||||
touchFocusRef.current = {
|
||||
pointerId: event.pointerId,
|
||||
x: event.clientX,
|
||||
y: event.clientY,
|
||||
};
|
||||
}
|
||||
},
|
||||
[onFocus],
|
||||
);
|
||||
|
||||
const handleRootPointerMove = useCallback((event: ReactPointerEvent) => {
|
||||
const touch = touchFocusRef.current;
|
||||
if (touch?.pointerId !== event.pointerId) return;
|
||||
if (Math.hypot(event.clientX - touch.x, event.clientY - touch.y) > 8) {
|
||||
touchFocusRef.current = null;
|
||||
runtimeRef.current?.suppressAutomaticKeyboard();
|
||||
}
|
||||
}, []);
|
||||
|
||||
const handleRootPointerUp = useCallback((event: ReactPointerEvent) => {
|
||||
const touch = touchFocusRef.current;
|
||||
touchFocusRef.current = null;
|
||||
if (touch?.pointerId === event.pointerId) runtimeRef.current?.focus();
|
||||
}, []);
|
||||
|
||||
const handleRootPointerCancel = useCallback(() => {
|
||||
touchFocusRef.current = null;
|
||||
}, []);
|
||||
const handleRootPointerDown = useCallback(() => {
|
||||
onFocus?.();
|
||||
runtimeRef.current?.focus();
|
||||
}, [onFocus]);
|
||||
|
||||
const handleRootContextMenu = useCallback(
|
||||
(event: ReactMouseEvent) => {
|
||||
@@ -631,9 +588,6 @@ export default function TerminalEmulator({
|
||||
data-terminal-scrollbar-root="true"
|
||||
style={rootDivStyle}
|
||||
onPointerDown={handleRootPointerDown}
|
||||
onPointerMove={handleRootPointerMove}
|
||||
onPointerUp={handleRootPointerUp}
|
||||
onPointerCancel={handleRootPointerCancel}
|
||||
onContextMenu={handleRootContextMenu}
|
||||
>
|
||||
<div ref={hostRef} style={HOST_DIV_STYLE} />
|
||||
|
||||
@@ -1,8 +0,0 @@
|
||||
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;
|
||||
}
|
||||
@@ -1,77 +0,0 @@
|
||||
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,9 +2323,6 @@ export const ar: TranslationResources = {
|
||||
resetsIn: "تتم إعادة التعيين خلال {{duration}}",
|
||||
resetsAtWeekday: "{{weekday}} {{time}}",
|
||||
resetsAtDate: "{{date}}، {{time}}",
|
||||
projectedLeftAtReset: "نحو {{percentage}} متبقية عند إعادة التعيين",
|
||||
limitReached: "تم بلوغ الحد",
|
||||
mayHaveRunOut: "ربما نفدت الحصة",
|
||||
runsOutNow: "ينفد الآن",
|
||||
runsOutIn: "ينفد خلال {{duration}}",
|
||||
justNow: "الآن",
|
||||
|
||||
@@ -2333,9 +2333,6 @@ export const en = {
|
||||
resetsIn: "resets in {{duration}}",
|
||||
resetsAtWeekday: "{{weekday}} {{time}}",
|
||||
resetsAtDate: "{{date}}, {{time}}",
|
||||
projectedLeftAtReset: "~{{percentage}} left at reset",
|
||||
limitReached: "Limit reached",
|
||||
mayHaveRunOut: "May have run out",
|
||||
runsOutNow: "runs out now",
|
||||
runsOutIn: "runs out in {{duration}}",
|
||||
justNow: "just now",
|
||||
|
||||
@@ -2354,9 +2354,6 @@ export const es: TranslationResources = {
|
||||
resetsIn: "se restablece en {{duration}}",
|
||||
resetsAtWeekday: "{{weekday}} {{time}}",
|
||||
resetsAtDate: "{{date}}, {{time}}",
|
||||
projectedLeftAtReset: "~{{percentage}} restante al restablecerse",
|
||||
limitReached: "Límite alcanzado",
|
||||
mayHaveRunOut: "Puede que ya se haya agotado",
|
||||
runsOutNow: "se agota ahora",
|
||||
runsOutIn: "se agota en {{duration}}",
|
||||
justNow: "ahora mismo",
|
||||
|
||||
@@ -2355,9 +2355,6 @@ export const fr: TranslationResources = {
|
||||
resetsIn: "se réinitialise dans {{duration}}",
|
||||
resetsAtWeekday: "{{weekday}} {{time}}",
|
||||
resetsAtDate: "{{date}}, {{time}}",
|
||||
projectedLeftAtReset: "~{{percentage}} restant à la réinitialisation",
|
||||
limitReached: "Limite atteinte",
|
||||
mayHaveRunOut: "Le quota est peut-être épuisé",
|
||||
runsOutNow: "s’épuise maintenant",
|
||||
runsOutIn: "s’épuise dans {{duration}}",
|
||||
justNow: "à l’instant",
|
||||
|
||||
@@ -2328,9 +2328,6 @@ export const ja: TranslationResources = {
|
||||
resetsIn: "{{duration}}後にリセット",
|
||||
resetsAtWeekday: "{{weekday}} {{time}}",
|
||||
resetsAtDate: "{{date}} {{time}}",
|
||||
projectedLeftAtReset: "リセット時に約{{percentage}}残る見込み",
|
||||
limitReached: "上限に達しました",
|
||||
mayHaveRunOut: "上限に達した可能性があります",
|
||||
runsOutNow: "まもなく上限に到達",
|
||||
runsOutIn: "{{duration}}後に上限に到達",
|
||||
justNow: "たった今",
|
||||
|
||||
@@ -2316,9 +2316,6 @@ export const ko: TranslationResources = {
|
||||
resetsIn: "{{duration}} 후 재설정",
|
||||
resetsAtWeekday: "{{weekday}} {{time}}",
|
||||
resetsAtDate: "{{date}} {{time}}",
|
||||
projectedLeftAtReset: "초기화 시 약 {{percentage}} 남을 예정",
|
||||
limitReached: "한도에 도달함",
|
||||
mayHaveRunOut: "한도를 소진했을 수 있음",
|
||||
runsOutNow: "지금 한도에 도달",
|
||||
runsOutIn: "{{duration}} 후 한도에 도달",
|
||||
justNow: "방금",
|
||||
|
||||
@@ -2339,9 +2339,6 @@ export const ptBR: TranslationResources = {
|
||||
resetsIn: "redefine em {{duration}}",
|
||||
resetsAtWeekday: "{{weekday}} {{time}}",
|
||||
resetsAtDate: "{{date}}, {{time}}",
|
||||
projectedLeftAtReset: "~{{percentage}} restará na renovação",
|
||||
limitReached: "Limite atingido",
|
||||
mayHaveRunOut: "A cota pode ter se esgotado",
|
||||
runsOutNow: "esgota agora",
|
||||
runsOutIn: "esgota em {{duration}}",
|
||||
justNow: "agora mesmo",
|
||||
|
||||
@@ -2341,9 +2341,6 @@ export const ru: TranslationResources = {
|
||||
resetsIn: "сброс через {{duration}}",
|
||||
resetsAtWeekday: "{{weekday}} {{time}}",
|
||||
resetsAtDate: "{{date}}, {{time}}",
|
||||
projectedLeftAtReset: "К сбросу останется ~{{percentage}}",
|
||||
limitReached: "Лимит исчерпан",
|
||||
mayHaveRunOut: "Лимит мог уже исчерпаться",
|
||||
runsOutNow: "закончится сейчас",
|
||||
runsOutIn: "закончится через {{duration}}",
|
||||
justNow: "только что",
|
||||
|
||||
@@ -2282,9 +2282,6 @@ export const zhCN: TranslationResources = {
|
||||
resetsIn: "将在 {{duration}}后重置",
|
||||
resetsAtWeekday: "{{weekday}} {{time}}",
|
||||
resetsAtDate: "{{date}} {{time}}",
|
||||
projectedLeftAtReset: "重置时约剩余 {{percentage}}",
|
||||
limitReached: "已达到上限",
|
||||
mayHaveRunOut: "额度可能已用完",
|
||||
runsOutNow: "即将用尽",
|
||||
runsOutIn: "将在 {{duration}}后用尽",
|
||||
justNow: "刚刚",
|
||||
|
||||
@@ -20,6 +20,8 @@ afterEach(async () => {
|
||||
await act(async () => root.render(null));
|
||||
usePanelStore.setState(initialPanel, true);
|
||||
});
|
||||
const noop = () => {};
|
||||
const explorerState = { expanded: false };
|
||||
const geometry: WindowLayout = {
|
||||
bounds: { x: 0, y: 0, width: window.innerWidth, height: window.innerHeight },
|
||||
verticalBarEdge: "trailing",
|
||||
@@ -40,8 +42,9 @@ it("updates compact header actions on panel changes without rendering the worksp
|
||||
title="Workspace"
|
||||
subtitle="Project"
|
||||
isSubtitleDistinct
|
||||
explorerAction={null}
|
||||
inDesktopTitlebar={false}
|
||||
onToggleExplorer={noop}
|
||||
explorerToggleLabel="Explorer"
|
||||
explorerToggleAccessibilityState={explorerState}
|
||||
tabSwitcher={null}
|
||||
headerVariant="full"
|
||||
>
|
||||
|
||||
@@ -1,6 +1,11 @@
|
||||
import { Fragment, useMemo, type ReactNode } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { usePanelStore } from "@/stores/panel-store";
|
||||
import { CompactHeader } from "@/components/headers/compact-header";
|
||||
import {
|
||||
EXPLORER_TOGGLE_KEYS,
|
||||
WorkspaceExplorerToggle,
|
||||
} from "@/screens/workspace/workspace-explorer-toggle";
|
||||
import { WorkspaceHeaderProjectRow } from "@/screens/workspace/workspace-header-project-row";
|
||||
import {
|
||||
useWindowLayout,
|
||||
@@ -18,9 +23,10 @@ interface CompactWorkspaceHeaderProps {
|
||||
title: string;
|
||||
subtitle: string;
|
||||
isSubtitleDistinct: boolean;
|
||||
explorerAction: ReactNode;
|
||||
onToggleExplorer: () => void;
|
||||
explorerToggleLabel: string;
|
||||
explorerToggleAccessibilityState: { expanded: boolean };
|
||||
tabSwitcher: ReactNode;
|
||||
inDesktopTitlebar: boolean;
|
||||
/** Workspace overflow menu. */
|
||||
children: ReactNode;
|
||||
headerVariant: "compact" | "full";
|
||||
@@ -34,15 +40,17 @@ export function CompactWorkspaceHeader({
|
||||
title,
|
||||
subtitle,
|
||||
isSubtitleDistinct,
|
||||
explorerAction,
|
||||
onToggleExplorer,
|
||||
explorerToggleLabel,
|
||||
explorerToggleAccessibilityState,
|
||||
children,
|
||||
tabSwitcher,
|
||||
inDesktopTitlebar,
|
||||
serverId,
|
||||
headerVariant,
|
||||
isRouteFocused,
|
||||
isCompact,
|
||||
}: CompactWorkspaceHeaderProps) {
|
||||
const { t } = useTranslation();
|
||||
const actionsInBar = resolveWorkspaceActionPlacement(useWindowLayout()) === "vertical-bar";
|
||||
const projectRow = useMemo(
|
||||
() => (
|
||||
@@ -57,7 +65,16 @@ export function CompactWorkspaceHeader({
|
||||
const symbols = {
|
||||
"tab-count": tabSwitcher,
|
||||
overflow: children,
|
||||
explorer: explorerAction,
|
||||
explorer: (
|
||||
<WorkspaceExplorerToggle
|
||||
onPress={onToggleExplorer}
|
||||
label={explorerToggleLabel}
|
||||
tooltipLabel={t("workspace.tabs.explorerSidebar.toggle")}
|
||||
tooltipKeys={EXPLORER_TOGGLE_KEYS}
|
||||
accessibilityState={explorerToggleAccessibilityState}
|
||||
mobile
|
||||
/>
|
||||
),
|
||||
};
|
||||
const actions = resolveWorkspaceBarActions(headerVariant).map((symbol) => (
|
||||
<Fragment key={symbol}>{symbols[symbol]}</Fragment>
|
||||
@@ -68,7 +85,6 @@ export function CompactWorkspaceHeader({
|
||||
{headerVariant === "compact" ? (
|
||||
<CompactHeader
|
||||
navigation="menu"
|
||||
inDesktopTitlebar={inDesktopTitlebar}
|
||||
title={title}
|
||||
titleTestID="workspace-header-title"
|
||||
subtitle={projectRow}
|
||||
|
||||
@@ -1,37 +1,47 @@
|
||||
import { useMemo } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { PanelRight } from "lucide-react-native";
|
||||
import { View, type StyleProp, type ViewStyle } from "react-native";
|
||||
import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
||||
import { WINDOW_NO_DRAG_DATASET } from "@/components/desktop/titlebar-drag-region";
|
||||
import { HeaderToggleButton, headerIconSlotStyle } from "@/components/headers/header-toggle-button";
|
||||
import { type StyleProp, type ViewStyle } from "react-native";
|
||||
import { withUnistyles } from "react-native-unistyles";
|
||||
import { HeaderToggleButton } from "@/components/headers/header-toggle-button";
|
||||
import { SidebarCloseButton } from "@/components/headers/sidebar-close-button";
|
||||
import {
|
||||
extraMutedIconColorMapping,
|
||||
iconButtonChromeGlyphSize,
|
||||
mutedIconColorMapping,
|
||||
} from "@/components/ui/icon-button-chrome";
|
||||
import { WORKSPACE_SECONDARY_HEADER_HEIGHT } from "@/constants/layout";
|
||||
import { useHasWindowChromeObstruction } from "@/utils/desktop-window";
|
||||
import type { ShortcutKey } from "@/utils/format-shortcut";
|
||||
|
||||
const ThemedPanelRight = withUnistyles(PanelRight);
|
||||
|
||||
const EXPLORER_TOGGLE_KEYS: ShortcutKey[] = ["mod", "E"];
|
||||
export const EXPLORER_TOGGLE_KEYS: ShortcutKey[] = ["mod", "E"];
|
||||
|
||||
interface WorkspaceExplorerToggleProps {
|
||||
onPress: () => void;
|
||||
label: string;
|
||||
tooltipLabel: string;
|
||||
tooltipKeys: ShortcutKey[];
|
||||
accessibilityState: { expanded: boolean };
|
||||
mobile: boolean;
|
||||
style?: StyleProp<ViewStyle>;
|
||||
}
|
||||
|
||||
function WorkspaceExplorerToggle({
|
||||
export type WorkspaceExplorerToggleOwner = "mobile" | "header" | "window";
|
||||
|
||||
export function resolveWorkspaceExplorerToggleOwner({
|
||||
isMobile,
|
||||
hasMacTrafficLights,
|
||||
}: {
|
||||
isMobile: boolean;
|
||||
hasMacTrafficLights: boolean;
|
||||
}): WorkspaceExplorerToggleOwner {
|
||||
if (isMobile) return "mobile";
|
||||
return hasMacTrafficLights ? "window" : "header";
|
||||
}
|
||||
|
||||
export function WorkspaceExplorerToggle({
|
||||
onPress,
|
||||
label,
|
||||
tooltipLabel,
|
||||
tooltipKeys,
|
||||
accessibilityState,
|
||||
mobile,
|
||||
style,
|
||||
@@ -41,7 +51,7 @@ function WorkspaceExplorerToggle({
|
||||
testID="workspace-explorer-toggle"
|
||||
onPress={onPress}
|
||||
tooltipLabel={tooltipLabel}
|
||||
tooltipKeys={EXPLORER_TOGGLE_KEYS}
|
||||
tooltipKeys={tooltipKeys}
|
||||
tooltipSide="left"
|
||||
style={style}
|
||||
accessible
|
||||
@@ -58,97 +68,42 @@ function WorkspaceExplorerToggle({
|
||||
);
|
||||
}
|
||||
|
||||
export function useWorkspaceExplorerControls({
|
||||
hasWorkspace,
|
||||
compact,
|
||||
focusMode,
|
||||
expanded,
|
||||
onToggle,
|
||||
}: {
|
||||
hasWorkspace: boolean;
|
||||
compact: boolean;
|
||||
focusMode: boolean;
|
||||
expanded: boolean;
|
||||
onToggle: () => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const hasLeadingWindowControls = useHasWindowChromeObstruction("top-left");
|
||||
const inDesktopTitlebar = hasLeadingWindowControls && hasWorkspace && !compact && !focusMode;
|
||||
|
||||
return useMemo(() => {
|
||||
const props = {
|
||||
label: expanded
|
||||
? t("workspace.tabs.explorerSidebar.close")
|
||||
: t("workspace.tabs.explorerSidebar.open"),
|
||||
tooltipLabel: t("workspace.tabs.explorerSidebar.toggle"),
|
||||
onPress: onToggle,
|
||||
accessibilityState: { expanded },
|
||||
};
|
||||
|
||||
if (inDesktopTitlebar) {
|
||||
// Keep the button in the header Tab order. The active rail carves its slot out of the drag region.
|
||||
const headerSlot = expanded ? null : (
|
||||
<View
|
||||
pointerEvents="none"
|
||||
style={[headerIconSlotStyle.slot, styles.headerAction]}
|
||||
dataSet={WINDOW_NO_DRAG_DATASET}
|
||||
/>
|
||||
);
|
||||
return {
|
||||
inDesktopTitlebar,
|
||||
headerAction: headerSlot,
|
||||
compactAction: headerSlot,
|
||||
dockAction: (
|
||||
<View
|
||||
pointerEvents="none"
|
||||
style={[headerIconSlotStyle.slot, styles.dockAction]}
|
||||
dataSet={WINDOW_NO_DRAG_DATASET}
|
||||
/>
|
||||
),
|
||||
titlebarAction: (
|
||||
<View pointerEvents="box-none" style={styles.titlebarSlot}>
|
||||
<WorkspaceExplorerToggle {...props} mobile={false} />
|
||||
</View>
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
inDesktopTitlebar,
|
||||
headerAction: compact ? null : (
|
||||
<WorkspaceExplorerToggle {...props} mobile={false} style={styles.headerAction} />
|
||||
),
|
||||
compactAction: <WorkspaceExplorerToggle {...props} mobile />,
|
||||
dockAction: compact ? (
|
||||
<SidebarCloseButton
|
||||
label={props.label}
|
||||
onPress={onToggle}
|
||||
testID="workspace-explorer-toggle"
|
||||
accessibilityState={props.accessibilityState}
|
||||
/>
|
||||
) : null,
|
||||
titlebarAction: null,
|
||||
};
|
||||
}, [compact, expanded, inDesktopTitlebar, onToggle, t]);
|
||||
interface DesktopWorkspaceExplorerToggleProps extends Omit<WorkspaceExplorerToggleProps, "mobile"> {
|
||||
owner: WorkspaceExplorerToggleOwner;
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
headerAction: {
|
||||
marginRight: { xs: 0, md: -theme.spacing[2] },
|
||||
},
|
||||
dockAction: {
|
||||
// The dock divider is absolutely positioned. Match the other headers' content center.
|
||||
marginBottom: theme.borderWidth[1],
|
||||
},
|
||||
titlebarSlot: {
|
||||
position: "absolute",
|
||||
top: 0,
|
||||
right: theme.spacing[1],
|
||||
height: WORKSPACE_SECONDARY_HEADER_HEIGHT,
|
||||
// Center with the bordered workspace header and Explorer tabs row.
|
||||
borderBottomWidth: theme.borderWidth[1],
|
||||
borderBottomColor: "transparent",
|
||||
justifyContent: "center",
|
||||
zIndex: 1,
|
||||
},
|
||||
}));
|
||||
export function WorkspaceHeaderExplorerToggle({
|
||||
owner,
|
||||
accessibilityState,
|
||||
style,
|
||||
...toggleProps
|
||||
}: DesktopWorkspaceExplorerToggleProps) {
|
||||
if (owner === "mobile" || (owner === "window" && accessibilityState.expanded)) return null;
|
||||
return (
|
||||
<WorkspaceExplorerToggle
|
||||
{...toggleProps}
|
||||
accessibilityState={accessibilityState}
|
||||
mobile={false}
|
||||
style={style}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function WorkspaceExplorerSidebarToggle({
|
||||
owner,
|
||||
...toggleProps
|
||||
}: DesktopWorkspaceExplorerToggleProps) {
|
||||
if (owner === "header") return null;
|
||||
if (owner === "mobile") {
|
||||
// The compact Explorer is an overlay like the compact agent list, so it closes with the same X.
|
||||
return (
|
||||
<SidebarCloseButton
|
||||
label={toggleProps.label}
|
||||
onPress={toggleProps.onPress}
|
||||
testID="workspace-explorer-toggle"
|
||||
accessibilityState={toggleProps.accessibilityState}
|
||||
/>
|
||||
);
|
||||
}
|
||||
return <WorkspaceExplorerToggle {...toggleProps} mobile={false} />;
|
||||
}
|
||||
|
||||
@@ -157,8 +157,17 @@ import {
|
||||
} from "@/screens/workspace/workspace-desktop-tabs-row";
|
||||
import { useDesktopBrowserNewTabRequests } from "@/desktop/browser/new-tab-requests";
|
||||
import type { WorkspaceTabDescriptor } from "@/screens/workspace/workspace-tabs-types";
|
||||
import { useWorkspaceExplorerControls } from "@/screens/workspace/workspace-explorer-toggle";
|
||||
import { WindowChromeRegion, WindowChromeSafeArea } from "@/utils/desktop-window";
|
||||
import {
|
||||
resolveWorkspaceExplorerToggleOwner,
|
||||
EXPLORER_TOGGLE_KEYS,
|
||||
WorkspaceExplorerSidebarToggle,
|
||||
WorkspaceHeaderExplorerToggle,
|
||||
} from "@/screens/workspace/workspace-explorer-toggle";
|
||||
import {
|
||||
useHasWindowChromeObstruction,
|
||||
WindowChromeRegion,
|
||||
WindowChromeSafeArea,
|
||||
} from "@/utils/desktop-window";
|
||||
import {
|
||||
resolveWorkspaceHeaderRenderState,
|
||||
type WorkspaceHeaderCheckoutState,
|
||||
@@ -1049,8 +1058,12 @@ function WorkspaceScreenContent({
|
||||
const isMobile = useIsCompactFormFactor();
|
||||
const canRenderDesktopPaneSplits = supportsDesktopPaneSplits();
|
||||
const layoutMode = useWorkspaceLayoutStore((state) => state.layoutMode);
|
||||
const hasMacTrafficLights = useHasWindowChromeObstruction("top-left");
|
||||
const explorerToggleOwner = resolveWorkspaceExplorerToggleOwner({
|
||||
isMobile,
|
||||
hasMacTrafficLights,
|
||||
});
|
||||
const isFocusModeEnabled = usePanelStore((state) => state.desktop.focusModeEnabled);
|
||||
const desktopFocusModeEnabled = isFocusModeEnabled && !isMobile;
|
||||
const toggleFocusMode = usePanelStore((state) => state.toggleFocusMode);
|
||||
|
||||
const normalizedServerId = useMemo(() => trimNonEmpty(decodeSegment(serverId)) ?? "", [serverId]);
|
||||
@@ -1295,6 +1308,11 @@ function WorkspaceScreenContent({
|
||||
explorerOpen: isExplorerSidebarShowing,
|
||||
});
|
||||
|
||||
const explorerSidebarToggleAccessibilityState = useMemo(
|
||||
() => ({ expanded: isExplorerSidebarShowing }),
|
||||
[isExplorerSidebarShowing],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
// Back dismisses the compact overlay only. On a wide native layout the
|
||||
// explorer is a tab, `showMobileAgent` has no rendered consumer, and
|
||||
@@ -1802,6 +1820,9 @@ function WorkspaceScreenContent({
|
||||
}),
|
||||
[t],
|
||||
);
|
||||
const explorerSidebarToggleLabel = isExplorerSidebarShowing
|
||||
? t("workspace.tabs.explorerSidebar.close")
|
||||
: t("workspace.tabs.explorerSidebar.open");
|
||||
|
||||
const activeTabKey = useMemo(() => activeTabId ?? "", [activeTabId]);
|
||||
const handleCreateDraftTab = useCallback(
|
||||
@@ -3207,13 +3228,6 @@ function WorkspaceScreenContent({
|
||||
workspaceKey: persistenceKey,
|
||||
});
|
||||
|
||||
const explorerControls = useWorkspaceExplorerControls({
|
||||
hasWorkspace: !!workspaceDirectory,
|
||||
compact: isMobile,
|
||||
focusMode: desktopFocusModeEnabled,
|
||||
expanded: isExplorerSidebarShowing,
|
||||
onToggle: handleToggleExplorerSidebar,
|
||||
});
|
||||
const headerRight = useMemo(
|
||||
() => (
|
||||
<View style={styles.headerRight}>
|
||||
@@ -3240,7 +3254,17 @@ function WorkspaceScreenContent({
|
||||
{workspaceDirectory ? (
|
||||
<>
|
||||
<WorkspaceActions serverId={normalizedServerId} cwd={workspaceDirectory} />
|
||||
{workspaceActionsInBar ? null : explorerControls.headerAction}
|
||||
{workspaceActionsInBar ? null : (
|
||||
<WorkspaceHeaderExplorerToggle
|
||||
owner={explorerToggleOwner}
|
||||
onPress={handleToggleExplorerSidebar}
|
||||
label={explorerSidebarToggleLabel}
|
||||
tooltipLabel={t("workspace.tabs.explorerSidebar.toggle")}
|
||||
tooltipKeys={EXPLORER_TOGGLE_KEYS}
|
||||
style={styles.compactHeaderActionButton}
|
||||
accessibilityState={explorerSidebarToggleAccessibilityState}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
) : null}
|
||||
</View>
|
||||
@@ -3255,8 +3279,12 @@ function WorkspaceScreenContent({
|
||||
scriptActions,
|
||||
handleViewScriptTerminal,
|
||||
handleOpenUrlInBrowserTab,
|
||||
explorerControls.headerAction,
|
||||
handleToggleExplorerSidebar,
|
||||
explorerSidebarToggleLabel,
|
||||
explorerSidebarToggleAccessibilityState,
|
||||
explorerToggleOwner,
|
||||
workspaceActionsInBar,
|
||||
t,
|
||||
],
|
||||
);
|
||||
|
||||
@@ -3264,6 +3292,25 @@ function WorkspaceScreenContent({
|
||||
() => shouldShowWorkspaceScreenHeader({ isFocusModeEnabled, isMobile }),
|
||||
[isFocusModeEnabled, isMobile],
|
||||
);
|
||||
const renderExplorerSidebarHeaderAction = useCallback(
|
||||
() => (
|
||||
<WorkspaceExplorerSidebarToggle
|
||||
owner={explorerToggleOwner}
|
||||
onPress={handleToggleExplorerSidebar}
|
||||
label={explorerSidebarToggleLabel}
|
||||
tooltipLabel={t("workspace.tabs.explorerSidebar.toggle")}
|
||||
tooltipKeys={EXPLORER_TOGGLE_KEYS}
|
||||
accessibilityState={explorerSidebarToggleAccessibilityState}
|
||||
/>
|
||||
),
|
||||
[
|
||||
explorerSidebarToggleAccessibilityState,
|
||||
explorerSidebarToggleLabel,
|
||||
explorerToggleOwner,
|
||||
handleToggleExplorerSidebar,
|
||||
t,
|
||||
],
|
||||
);
|
||||
const createTerminalDisabled = useMemo(
|
||||
() => createTerminalMutation.isPending || pendingTerminalCreateInput !== null,
|
||||
[createTerminalMutation.isPending, pendingTerminalCreateInput],
|
||||
@@ -3286,6 +3333,10 @@ function WorkspaceScreenContent({
|
||||
],
|
||||
);
|
||||
const focusedPaneIdOrUndefined = useMemo(() => focusedPaneId ?? undefined, [focusedPaneId]);
|
||||
const desktopFocusModeEnabled = useMemo(
|
||||
() => isFocusModeEnabled && !isMobile,
|
||||
[isFocusModeEnabled, isMobile],
|
||||
);
|
||||
const workspaceFloatingPanelPortalHostName = useMemo(
|
||||
() =>
|
||||
`${WORKSPACE_FLOATING_PANEL_PORTAL_HOST_PREFIX}:${normalizedServerId}:${normalizedWorkspaceId}`,
|
||||
@@ -3409,13 +3460,14 @@ function WorkspaceScreenContent({
|
||||
isRouteFocused={isRouteFocused}
|
||||
isCompact={isMobile}
|
||||
tabSwitcher={tabSwitcher}
|
||||
inDesktopTitlebar={explorerControls.inDesktopTitlebar}
|
||||
explorerAction={explorerControls.compactAction}
|
||||
isLoading={isWorkspaceHeaderLoading}
|
||||
title={workspaceHeaderTitle}
|
||||
subtitle={workspaceHeaderSubtitle}
|
||||
isSubtitleDistinct={isWorkspaceHeaderSubtitleDistinct}
|
||||
serverId={normalizedServerId}
|
||||
onToggleExplorer={handleToggleExplorerSidebar}
|
||||
explorerToggleLabel={explorerSidebarToggleLabel}
|
||||
explorerToggleAccessibilityState={explorerSidebarToggleAccessibilityState}
|
||||
>
|
||||
<WorkspaceHeaderMenuMobile
|
||||
pane={paneTabs?.actions.pane}
|
||||
@@ -3441,19 +3493,20 @@ function WorkspaceScreenContent({
|
||||
},
|
||||
[
|
||||
renderWorkspaceTabSwitcher,
|
||||
explorerControls.inDesktopTitlebar,
|
||||
explorerControls.compactAction,
|
||||
isFocusModeEnabled,
|
||||
toggleFocusMode,
|
||||
canOpenImportSheet,
|
||||
compactHeaderScripts,
|
||||
createTerminalDisabled,
|
||||
currentBranchName,
|
||||
explorerSidebarToggleAccessibilityState,
|
||||
explorerSidebarToggleLabel,
|
||||
handleCopyBranchName,
|
||||
handleCopyWorkspacePath,
|
||||
handleCreateBrowserTab,
|
||||
handleCreateTerminalWithProfile,
|
||||
handleOpenSetupTab,
|
||||
handleToggleExplorerSidebar,
|
||||
isMobile,
|
||||
isRouteFocused,
|
||||
isWorkspaceHeaderLoading,
|
||||
@@ -3681,7 +3734,7 @@ function WorkspaceScreenContent({
|
||||
onExitFocusMode={toggleFocusMode}
|
||||
onReorderTabsInPane={handleReorderTabsInPane}
|
||||
buildPaneContentModel={buildDesktopPaneContentModel}
|
||||
headerAction={explorerControls.dockAction}
|
||||
headerAction={renderExplorerSidebarHeaderAction()}
|
||||
/>
|
||||
);
|
||||
return (
|
||||
@@ -3722,7 +3775,7 @@ function WorkspaceScreenContent({
|
||||
toggleFocusMode,
|
||||
handleReorderTabsInPane,
|
||||
buildDesktopPaneContentModel,
|
||||
explorerControls.dockAction,
|
||||
renderExplorerSidebarHeaderAction,
|
||||
desktopFocusModeEnabled,
|
||||
]);
|
||||
|
||||
@@ -3796,7 +3849,6 @@ function WorkspaceScreenContent({
|
||||
onReorderTabsInPane={handleReorderTabsInPane}
|
||||
onSplitPane={handleSplitPane}
|
||||
>
|
||||
{explorerControls.titlebarAction}
|
||||
{workspaceCenterColumn}
|
||||
{sharedExplorer}
|
||||
</WorkspaceTabDragScope>
|
||||
@@ -3934,6 +3986,12 @@ const styles = StyleSheet.create((theme) => ({
|
||||
md: theme.spacing[2],
|
||||
},
|
||||
},
|
||||
compactHeaderActionButton: {
|
||||
marginRight: {
|
||||
xs: 0,
|
||||
md: -theme.spacing[2],
|
||||
},
|
||||
},
|
||||
compactHeaderMenuCluster: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
import { buildDesktopFrameStyle } from "@/components/ui/combobox-frame-style";
|
||||
import {
|
||||
WorkspaceHeaderExplorerToggle,
|
||||
WorkspaceExplorerSidebarToggle,
|
||||
} from "./workspace-explorer-toggle";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { SidebarCloseButton } from "@/components/headers/sidebar-close-button";
|
||||
import { resolveWorkspaceTabChipBackdrop } from "@/screens/workspace/workspace-tab-chip-backdrop";
|
||||
import { darkPureBlackTheme, darkTheme, lightTheme } from "@/styles/theme";
|
||||
import {
|
||||
@@ -185,6 +190,37 @@ describe("retainWorkspaceTabMeasuredWidth", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("Explorer toggle ownership", () => {
|
||||
const toggleProps = {
|
||||
onPress: () => {},
|
||||
label: "Close Explorer sidebar",
|
||||
tooltipLabel: "Toggle Explorer sidebar",
|
||||
tooltipKeys: [],
|
||||
accessibilityState: { expanded: true },
|
||||
};
|
||||
|
||||
it("keeps only the header toggle when window controls do not obstruct it", () => {
|
||||
expect(WorkspaceHeaderExplorerToggle({ ...toggleProps, owner: "header" })).not.toBeNull();
|
||||
expect(WorkspaceExplorerSidebarToggle({ ...toggleProps, owner: "header" })).toBeNull();
|
||||
});
|
||||
|
||||
it("keeps the dock toggle for window-owned and compact overlay chrome", () => {
|
||||
for (const owner of ["window", "mobile"] as const) {
|
||||
expect(WorkspaceHeaderExplorerToggle({ ...toggleProps, owner })).toBeNull();
|
||||
expect(WorkspaceExplorerSidebarToggle({ ...toggleProps, owner })).not.toBeNull();
|
||||
}
|
||||
});
|
||||
|
||||
it("closes the compact overlay with the same X as the compact agent list", () => {
|
||||
expect(WorkspaceExplorerSidebarToggle({ ...toggleProps, owner: "mobile" })?.type).toBe(
|
||||
SidebarCloseButton,
|
||||
);
|
||||
expect(WorkspaceExplorerSidebarToggle({ ...toggleProps, owner: "window" })?.type).not.toBe(
|
||||
SidebarCloseButton,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveWorkspaceTabChipBackdrop", () => {
|
||||
const themes = { light: lightTheme, dark: darkTheme, pureBlack: darkPureBlackTheme };
|
||||
const rails = {
|
||||
|
||||
@@ -1053,19 +1053,12 @@ export class TerminalEmulatorRuntime {
|
||||
if (!terminal) {
|
||||
return;
|
||||
}
|
||||
terminal.textarea?.removeAttribute("virtualkeyboardpolicy");
|
||||
if (input?.forceRefocus) {
|
||||
terminal.blur();
|
||||
}
|
||||
terminal.focus();
|
||||
}
|
||||
|
||||
suppressAutomaticKeyboard(): void {
|
||||
// Android Chrome can reopen the keyboard during a drag after Back leaves the input
|
||||
// focused. Manual policy prevents that without closing an already open keyboard.
|
||||
this.terminal?.textarea?.setAttribute("virtualkeyboardpolicy", "manual");
|
||||
}
|
||||
|
||||
blur(): void {
|
||||
this.terminal?.blur();
|
||||
}
|
||||
|
||||
@@ -32,7 +32,6 @@ it("translates mounted usage rows when the language changes", async () => {
|
||||
<>
|
||||
<UsageWindowBar
|
||||
window={window}
|
||||
forecastAt={null}
|
||||
displayAs="used"
|
||||
pinnable={false}
|
||||
pinned={false}
|
||||
@@ -52,44 +51,3 @@ it("translates mounted usage rows when the language changes", async () => {
|
||||
expect(container.textContent).toContain("セッション70% 使用済み");
|
||||
expect(container.textContent).toContain("クレジット");
|
||||
});
|
||||
|
||||
const narrowReadingMs = Date.now();
|
||||
const narrowForecastAt = new Date(narrowReadingMs).toISOString();
|
||||
const narrowWindow: UsageWindow = {
|
||||
id: "weekly",
|
||||
label: "Weekly",
|
||||
usedPct: 0.2,
|
||||
durationSeconds: 604_800,
|
||||
resetsAt: new Date(narrowReadingMs + 165.5 * 3_600_000).toISOString(),
|
||||
};
|
||||
|
||||
it("keeps the French reset countdown and forecast apart in a narrow card", async () => {
|
||||
await i18n.changeLanguage("fr");
|
||||
container.style.width = "272px";
|
||||
act(() =>
|
||||
root.render(
|
||||
<UsageWindowBar
|
||||
window={narrowWindow}
|
||||
forecastAt={narrowForecastAt}
|
||||
displayAs="used"
|
||||
pinnable={false}
|
||||
pinned={false}
|
||||
onTogglePin={ignorePin}
|
||||
pinLabel=""
|
||||
pinTestID=""
|
||||
/>,
|
||||
),
|
||||
);
|
||||
|
||||
function textBounds(prefix: string) {
|
||||
const element = Array.from(container.querySelectorAll("*")).find(
|
||||
(node) => node.childElementCount === 0 && node.textContent.startsWith(prefix),
|
||||
);
|
||||
expect(element).toBeDefined();
|
||||
const range = document.createRange();
|
||||
range.selectNodeContents(element!);
|
||||
return range.getBoundingClientRect();
|
||||
}
|
||||
|
||||
expect(textBounds("se réinitialise").right).toBeLessThan(textBounds("~").left);
|
||||
});
|
||||
|
||||
@@ -70,7 +70,7 @@ export function UsageCard({
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const isCompact = useIsCompactFormFactor();
|
||||
const { refresh, refreshState } = useReportRefresh(serverId, entry, agentId);
|
||||
const { refresh, refreshState } = useReportRefresh(serverId, entry.id, agentId);
|
||||
// Where there is no hover the freshness is printed on the card; elsewhere the Refresh tooltip.
|
||||
const showsFreshnessInline = isNative || isCompact || !refreshable;
|
||||
const usage = entry.report;
|
||||
@@ -176,7 +176,7 @@ function UsageCardBody({
|
||||
refreshState: UsageRefresh;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const { windows, balances, details, retained, successfulAt, forecastAt, messages } = report;
|
||||
const { windows, balances, details, retained, successfulAt, messages } = report;
|
||||
const footer = entry.account.label ?? null;
|
||||
return (
|
||||
<>
|
||||
@@ -194,7 +194,6 @@ function UsageCardBody({
|
||||
entry={entry}
|
||||
window={window}
|
||||
retained={retained}
|
||||
forecastAt={forecastAt}
|
||||
display={display}
|
||||
pinnable={pinnable}
|
||||
/>
|
||||
@@ -268,10 +267,8 @@ function CardWindowBar({
|
||||
display,
|
||||
pinnable,
|
||||
retained,
|
||||
forecastAt,
|
||||
}: {
|
||||
retained: boolean;
|
||||
forecastAt: string | null;
|
||||
entry: UsageReportEntry;
|
||||
window: UsageWindow;
|
||||
display: UsageDisplay;
|
||||
@@ -288,7 +285,6 @@ function CardWindowBar({
|
||||
<UsageWindowBar
|
||||
window={window}
|
||||
retained={retained}
|
||||
forecastAt={forecastAt}
|
||||
displayAs={display.displayAs}
|
||||
pinnable={pinnable}
|
||||
pinned={display.isPinned(pin)}
|
||||
|
||||
@@ -2,7 +2,6 @@ import { afterEach, describe, expect, it } from "vitest";
|
||||
import { i18n } from "@/i18n/i18next";
|
||||
import {
|
||||
resolveUsageReport,
|
||||
markUsageRefreshFailure,
|
||||
displayPercent,
|
||||
resolveAgentUsageView,
|
||||
replaceReport,
|
||||
@@ -83,7 +82,7 @@ describe("resolveUsageView", () => {
|
||||
expect(resolveUsageView({ ...base, query: undefined })).toEqual({ kind: "loading" });
|
||||
expect(
|
||||
resolveUsageView({ ...base, query: { data: [], error: null, isFetching: true } }),
|
||||
).toEqual({ kind: "ready", reports: [], isRefreshing: true, refreshFailed: false });
|
||||
).toEqual({ kind: "ready", reports: [], isRefreshing: true });
|
||||
expect(
|
||||
resolveUsageView({
|
||||
...base,
|
||||
@@ -91,19 +90,6 @@ describe("resolveUsageView", () => {
|
||||
}),
|
||||
).toEqual({ kind: "error", message: "boom" });
|
||||
});
|
||||
|
||||
it("shows a failed Refresh all alongside the reports still on screen", () => {
|
||||
const reports = [entry({})];
|
||||
expect(
|
||||
resolveUsageView({
|
||||
hostLabel: "Laptop",
|
||||
isConnected: true,
|
||||
supportsUsage: true,
|
||||
query: ready(reports),
|
||||
refreshState: "failed",
|
||||
}),
|
||||
).toEqual({ kind: "ready", reports, isRefreshing: false, refreshFailed: true });
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
@@ -217,12 +203,15 @@ describe("displayPercent", () => {
|
||||
|
||||
describe("resolveUsageRefresh", () => {
|
||||
it("is pending while a refresh runs, even after an earlier failure", () => {
|
||||
expect(resolveUsageRefresh({ isPending: true, isError: true })).toBe("pending");
|
||||
expect(resolveUsageRefresh({ isPending: true, error: new Error("boom") })).toBe("pending");
|
||||
});
|
||||
|
||||
it("reports the request outcome independently of the reading", () => {
|
||||
expect(resolveUsageRefresh({ isPending: false, isError: true })).toBe("failed");
|
||||
expect(resolveUsageRefresh({ isPending: false, isError: false })).toBe("idle");
|
||||
it("is failed after a refresh errors", () => {
|
||||
expect(resolveUsageRefresh({ isPending: false, error: new Error("boom") })).toBe("failed");
|
||||
});
|
||||
|
||||
it("is idle before and after a successful refresh", () => {
|
||||
expect(resolveUsageRefresh({ isPending: false, error: null })).toBe("idle");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -363,7 +352,6 @@ it("resolves retained usage and successful time without inventing old-daemon his
|
||||
details: [],
|
||||
planLabel: null,
|
||||
successfulAt: success.fetchedAt,
|
||||
forecastAt: null,
|
||||
retained: true,
|
||||
messages: ["Rate limited"],
|
||||
});
|
||||
@@ -373,7 +361,6 @@ it("resolves retained usage and successful time without inventing old-daemon his
|
||||
details: [],
|
||||
planLabel: null,
|
||||
successfulAt: null,
|
||||
forecastAt: null,
|
||||
retained: false,
|
||||
messages: ["Rate limited"],
|
||||
});
|
||||
@@ -383,48 +370,11 @@ it("resolves retained usage and successful time without inventing old-daemon his
|
||||
details: [],
|
||||
planLabel: null,
|
||||
successfulAt: success.fetchedAt,
|
||||
forecastAt: success.fetchedAt,
|
||||
retained: false,
|
||||
messages: [],
|
||||
});
|
||||
});
|
||||
|
||||
it("uses the quota observation time for pace and keeps the reading after a failed request", () => {
|
||||
const success = entry({ windows: [{ id: "weekly", label: "Weekly", usedPct: 42 }] });
|
||||
if (success.report.status !== "available") throw new Error("fixture must be available");
|
||||
const observedAt = success.fetchedAt;
|
||||
const successfulAt = "2026-01-01T00:15:00.000Z";
|
||||
const report = { ...success, successfulAt, report: { ...success.report, observedAt } };
|
||||
expect(resolveUsageReport(report, i18n.t)).toMatchObject({
|
||||
successfulAt,
|
||||
forecastAt: observedAt,
|
||||
});
|
||||
expect(resolveUsageReport({ ...report, forecastStale: true }, i18n.t)).toMatchObject({
|
||||
windows: success.report.windows,
|
||||
successfulAt,
|
||||
forecastAt: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps cached quota and hides its forecast when Refresh all fails before a new report arrives", () => {
|
||||
const before = entry({ windows: [{ id: "weekly", label: "Weekly", usedPct: 42 }] });
|
||||
const other = entry({ sourceId: "other" });
|
||||
const refreshedAt = "2026-01-01T00:06:00.000Z";
|
||||
const streamed = { ...other, fetchedAt: refreshedAt };
|
||||
const attempted = [before, other];
|
||||
const failed = markUsageRefreshFailure([before, streamed], attempted)!;
|
||||
|
||||
expect(resolveUsageReport(failed[0]!, i18n.t)).toMatchObject({
|
||||
forecastAt: null,
|
||||
windows: before.report.status === "available" ? before.report.windows : [],
|
||||
});
|
||||
expect(resolveUsageReport(failed[1]!, i18n.t).forecastAt).toBe(refreshedAt);
|
||||
expect(resolveUsageReport(upsertReport(failed, before)[0]!, i18n.t).forecastAt).toBeNull();
|
||||
|
||||
const retried = settleReports(failed, [{ ...before, fetchedAt: refreshedAt }, streamed]);
|
||||
expect(resolveUsageReport(retried[0]!, i18n.t).forecastAt).toBe(refreshedAt);
|
||||
});
|
||||
|
||||
it("orders failed polls by attempt time even when successful data is older", () => {
|
||||
const success = entry({});
|
||||
if (success.report.status !== "available") throw new Error("fixture must be available");
|
||||
|
||||
@@ -38,31 +38,18 @@ export function usageWindowRowLabel(input: {
|
||||
return `${input.pinLabel}, ${summary}`;
|
||||
}
|
||||
|
||||
/** The outcome of a user-requested usage refresh. */
|
||||
/** A user-requested refresh of one report. The previous report stays on screen throughout. */
|
||||
export type UsageRefresh = "idle" | "pending" | "failed";
|
||||
|
||||
export function resolveUsageRefresh(mutation: {
|
||||
isPending: boolean;
|
||||
isError: boolean;
|
||||
error: unknown;
|
||||
}): UsageRefresh {
|
||||
if (mutation.isPending) return "pending";
|
||||
if (mutation.isError) return "failed";
|
||||
if (mutation.error) return "failed";
|
||||
return "idle";
|
||||
}
|
||||
|
||||
/** Keep quota readings after a failed refresh and attach the outcome to the readings it targeted. */
|
||||
export function markUsageRefreshFailure(
|
||||
current: UsageReportEntry[] | undefined,
|
||||
attempted: readonly UsageReportEntry[],
|
||||
): UsageReportEntry[] | undefined {
|
||||
const attemptedAt = new Map(attempted.map((entry) => [entry.id, entry.fetchedAt]));
|
||||
return current?.map((entry) =>
|
||||
attemptedAt.get(entry.id) === entry.fetchedAt && !entry.forecastStale
|
||||
? { ...entry, forecastStale: true }
|
||||
: entry,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* A host's report list with one report swapped for its refreshed copy, in place.
|
||||
* `null` means the daemon no longer knows the ID, so the report leaves the list.
|
||||
@@ -73,9 +60,7 @@ export function replaceReport(
|
||||
refreshed: UsageReportEntry | null,
|
||||
): UsageReportEntry[] {
|
||||
if (!refreshed) return reports.filter((report) => report.id !== reportId);
|
||||
return reports.map((report) =>
|
||||
report.id === reportId ? laterFetched(report, refreshed) : report,
|
||||
);
|
||||
return reports.map((report) => (report.id === reportId ? refreshed : report));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -83,9 +68,7 @@ export function replaceReport(
|
||||
* started, so a Refresh that lands while it streams is newer than what the request still delivers.
|
||||
*/
|
||||
function laterFetched(shown: UsageReportEntry, arriving: UsageReportEntry): UsageReportEntry {
|
||||
const shownAt = Date.parse(shown.fetchedAt);
|
||||
const arrivingAt = Date.parse(arriving.fetchedAt);
|
||||
return shownAt > arrivingAt || (shownAt === arrivingAt && shown.forecastStale) ? shown : arriving;
|
||||
return Date.parse(shown.fetchedAt) > Date.parse(arriving.fetchedAt) ? shown : arriving;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -134,11 +117,10 @@ export function resolveUsageView(
|
||||
isConnected: boolean;
|
||||
supportsUsage: boolean;
|
||||
query: UsageQueryState | undefined;
|
||||
refreshState?: UsageRefresh;
|
||||
},
|
||||
t: TFunction = i18n.t,
|
||||
): UsageView {
|
||||
const { hostLabel, isConnected, supportsUsage, query, refreshState } = input;
|
||||
const { hostLabel, isConnected, supportsUsage, query } = input;
|
||||
if (!isConnected)
|
||||
return {
|
||||
kind: "unavailable",
|
||||
@@ -153,12 +135,7 @@ export function resolveUsageView(
|
||||
if (input.enabled === false)
|
||||
return { kind: "off", message: t("providerUsage.off", { host: hostLabel }) };
|
||||
if (query?.data) {
|
||||
return {
|
||||
kind: "ready",
|
||||
reports: query.data,
|
||||
isRefreshing: query.isFetching || refreshState === "pending",
|
||||
refreshFailed: refreshState === "failed",
|
||||
};
|
||||
return { kind: "ready", reports: query.data, isRefreshing: query.isFetching };
|
||||
}
|
||||
if (query?.error) {
|
||||
return {
|
||||
@@ -273,12 +250,7 @@ export function resolveUsageReport(entry: UsageReportEntry, t: TFunction) {
|
||||
// COMPAT(usageLoginErrors): added in v0.11.0, remove after 2027-04-05 once daemon floor >= v0.11.0.
|
||||
else messages.push(usageProblemText(entry.report, t));
|
||||
}
|
||||
const forecastAt =
|
||||
snapshot && !snapshot.retained && !entry.forecastStale
|
||||
? (snapshot.report.observedAt ?? snapshot.successfulAt)
|
||||
: null;
|
||||
return {
|
||||
forecastAt,
|
||||
windows: snapshot?.report.windows ?? [],
|
||||
balances: snapshot?.report.balances ?? [],
|
||||
details: snapshot?.report.details ?? [],
|
||||
|
||||
@@ -1,45 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { usagePace } from "./pace";
|
||||
import type { UsageWindow } from "./types";
|
||||
|
||||
const day = "2026-11-20T";
|
||||
const reading = (time: string) => `${day}${time}:00.000Z`;
|
||||
const window: UsageWindow = {
|
||||
id: "five_hour",
|
||||
label: "Session",
|
||||
durationSeconds: 18_000,
|
||||
usedPct: 65,
|
||||
resetsAt: reading("15:00"),
|
||||
};
|
||||
|
||||
describe("usage pace", () => {
|
||||
it("projects the limit from the sample time and keeps it fixed between readings", () => {
|
||||
const sampledAt = reading("12:00");
|
||||
const estimate = { kind: "runsOut", at: `${day}13:04:36.923Z` };
|
||||
expect(usagePace(window, sampledAt, Date.parse(sampledAt))).toEqual(estimate);
|
||||
expect(usagePace(window, sampledAt, Date.parse(reading("12:30")))).toEqual(estimate);
|
||||
});
|
||||
|
||||
it("updates after a later reading and works with a remaining percentage", () => {
|
||||
const close = reading("13:30");
|
||||
const safe = reading("14:00");
|
||||
const forecast = usagePace(window, close, Date.parse(close));
|
||||
expect(forecast.kind).toBe("remaining");
|
||||
if (forecast.kind === "remaining") expect(forecast.remainingAtResetPct).toBeCloseTo(7.14);
|
||||
expect(
|
||||
usagePace({ ...window, usedPct: undefined, remainingPct: 35 }, safe, Date.parse(safe)),
|
||||
).toEqual({ kind: "remaining", remainingAtResetPct: 18.75 });
|
||||
});
|
||||
|
||||
it("only forecasts with timing and an active, usable reading", () => {
|
||||
const sampledAt = reading("12:00");
|
||||
const now = Date.parse(sampledAt);
|
||||
expect(usagePace({ ...window, durationSeconds: undefined }, sampledAt, now)).toEqual({
|
||||
kind: "unknown",
|
||||
});
|
||||
expect(usagePace(window, null, now)).toEqual({ kind: "unknown" });
|
||||
expect(usagePace(window, reading("10:01"), now)).toEqual({ kind: "unknown" });
|
||||
expect(usagePace(window, sampledAt, Date.parse(window.resetsAt!))).toEqual({ kind: "unknown" });
|
||||
expect(usagePace({ ...window, usedPct: 100 }, sampledAt, now)).toEqual({ kind: "reached" });
|
||||
});
|
||||
});
|
||||
@@ -1,45 +0,0 @@
|
||||
import { usedPercent } from "./model";
|
||||
import type { UsageWindow } from "./types";
|
||||
|
||||
type UsagePace =
|
||||
| { kind: "unknown" }
|
||||
| { kind: "reached" }
|
||||
| { kind: "runsOut"; at: string }
|
||||
| { kind: "remaining"; remainingAtResetPct: number };
|
||||
|
||||
/** Estimate from the window's average pace as of the reading. The clock only expires the estimate. */
|
||||
export function usagePace(window: UsageWindow, observedAt: string | null, now: number): UsagePace {
|
||||
if (observedAt === null) return { kind: "unknown" };
|
||||
const reset = Date.parse(window.resetsAt ?? "");
|
||||
if (reset <= now) return { kind: "unknown" };
|
||||
|
||||
const used = usedPercent(window);
|
||||
if (used != null && used >= 100) return { kind: "reached" };
|
||||
|
||||
const supplied = window.runsOutAt;
|
||||
const suppliedAt = Date.parse(supplied ?? "");
|
||||
if (supplied && Number.isFinite(suppliedAt) && (!Number.isFinite(reset) || suppliedAt < reset)) {
|
||||
return { kind: "runsOut", at: supplied };
|
||||
}
|
||||
|
||||
const duration = (window.durationSeconds ?? 0) * 1_000;
|
||||
const sampled = Date.parse(observedAt);
|
||||
const elapsed = sampled - (reset - duration);
|
||||
if (
|
||||
used == null ||
|
||||
!Number.isFinite(used) ||
|
||||
used < 0 ||
|
||||
!Number.isFinite(elapsed) ||
|
||||
sampled >= reset ||
|
||||
elapsed < Math.max(60_000, duration * 0.01)
|
||||
) {
|
||||
return { kind: "unknown" };
|
||||
}
|
||||
|
||||
const projectedAtReset = (used / elapsed) * duration;
|
||||
if (projectedAtReset > 100) {
|
||||
const runsOut = sampled + ((100 - used) / used) * elapsed;
|
||||
return { kind: "runsOut", at: new Date(runsOut).toISOString() };
|
||||
}
|
||||
return { kind: "remaining", remainingAtResetPct: 100 - projectedAtReset };
|
||||
}
|
||||
@@ -20,7 +20,6 @@ import { useSessionStore, type SessionState } from "@/stores/session-store";
|
||||
import { useUsageSetting } from "./setting";
|
||||
import { usageCopy } from "./copy";
|
||||
import {
|
||||
markUsageRefreshFailure,
|
||||
replaceReport,
|
||||
resolveAgentUsageView,
|
||||
resolveUsageRefresh,
|
||||
@@ -98,32 +97,17 @@ async function streamReports(input: {
|
||||
return settleReports(queryClient.getQueryData<UsageReportEntry[]>(queryKey), reports);
|
||||
}
|
||||
|
||||
async function listReports(
|
||||
function listReports(
|
||||
queryClient: QueryClient,
|
||||
serverId: string,
|
||||
forceRefresh = false,
|
||||
): Promise<UsageReportEntry[]> {
|
||||
const queryKey = usageReportsQueryKey(serverId);
|
||||
const attempted = queryClient.getQueryData<UsageReportEntry[]>(queryKey) ?? [];
|
||||
try {
|
||||
return await streamReports({ queryClient, queryKey, serverId, forceRefresh });
|
||||
} catch (error) {
|
||||
recordUsageRefreshFailure(queryClient, queryKey, attempted);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
function recordUsageRefreshFailure(
|
||||
queryClient: QueryClient,
|
||||
queryKey: QueryKey,
|
||||
attempted: readonly UsageReportEntry[],
|
||||
): void {
|
||||
const { dataUpdatedAt } = queryClient.getQueryState(queryKey) ?? {};
|
||||
queryClient.setQueryData<UsageReportEntry[]>(
|
||||
queryKey,
|
||||
(current) => markUsageRefreshFailure(current, attempted),
|
||||
{ updatedAt: dataUpdatedAt },
|
||||
);
|
||||
return streamReports({
|
||||
queryClient,
|
||||
queryKey: usageReportsQueryKey(serverId),
|
||||
serverId,
|
||||
forceRefresh,
|
||||
});
|
||||
}
|
||||
|
||||
async function getReport(
|
||||
@@ -174,12 +158,9 @@ export function useHostUsage(serverId: string): { view: UsageView; refresh: () =
|
||||
dataShape: "value",
|
||||
staleTimeMs: REPORTS_STALE_TIME_MS,
|
||||
});
|
||||
const mutation = useMutation({
|
||||
mutationKey: [...usageReportsQueryKey(serverId), "refresh"],
|
||||
mutationFn: (hostId: string) => refreshReports(queryClient, hostId),
|
||||
});
|
||||
const { mutate, variables } = mutation;
|
||||
const refresh = useCallback(() => mutate(serverId), [mutate, serverId]);
|
||||
const refresh = useCallback(() => {
|
||||
void refreshReports(queryClient, serverId).catch(() => undefined);
|
||||
}, [queryClient, serverId]);
|
||||
const { t } = useTranslation();
|
||||
const hostLabel = useHosts().find((host) => host.serverId === serverId)?.label ?? serverId;
|
||||
const view = resolveUsageView(
|
||||
@@ -189,7 +170,6 @@ export function useHostUsage(serverId: string): { view: UsageView; refresh: () =
|
||||
isConnected,
|
||||
supportsUsage: isSupported,
|
||||
query: toQueryState(query),
|
||||
refreshState: variables === serverId ? resolveUsageRefresh(mutation) : "idle",
|
||||
},
|
||||
t,
|
||||
);
|
||||
@@ -285,26 +265,23 @@ export function useUsageHosts(): UsageHost[] {
|
||||
*/
|
||||
export function useReportRefresh(
|
||||
serverId: string,
|
||||
entry: UsageReportEntry,
|
||||
reportId: string,
|
||||
agentId?: string,
|
||||
): { refresh: () => void; refreshState: UsageRefresh } {
|
||||
const queryClient = useQueryClient();
|
||||
const usageScopeKey = useAgentUsageScopeKey(serverId, agentId);
|
||||
const queryKey =
|
||||
agentId === undefined
|
||||
? usageReportsQueryKey(serverId)
|
||||
: agentUsageQueryKey(serverId, agentId, usageScopeKey);
|
||||
const mutation = useMutation({
|
||||
mutationKey: [...queryKey, "refresh", entry.id],
|
||||
mutationFn: (attempted: UsageReportEntry) => getReport(serverId, attempted.id, true, agentId),
|
||||
onSuccess: (report, attempted) => {
|
||||
queryClient.setQueryData<UsageReportEntry[]>(queryKey, (reports) =>
|
||||
reports ? replaceReport(reports, attempted.id, report) : reports,
|
||||
mutationFn: () => getReport(serverId, reportId, true, agentId),
|
||||
onSuccess: (report) => {
|
||||
queryClient.setQueryData<UsageReportEntry[]>(
|
||||
agentId === undefined
|
||||
? usageReportsQueryKey(serverId)
|
||||
: agentUsageQueryKey(serverId, agentId, usageScopeKey),
|
||||
(reports) => (reports ? replaceReport(reports, reportId, report) : reports),
|
||||
);
|
||||
},
|
||||
onError: (_error, attempted) => recordUsageRefreshFailure(queryClient, queryKey, [attempted]),
|
||||
});
|
||||
const { mutate } = mutation;
|
||||
const refresh = useCallback(() => mutate(entry), [mutate, entry]);
|
||||
const refresh = useCallback(() => mutate(), [mutate]);
|
||||
return { refresh, refreshState: resolveUsageRefresh(mutation) };
|
||||
}
|
||||
|
||||
@@ -3,21 +3,24 @@ import { StyleSheet } from "react-native-unistyles";
|
||||
|
||||
/**
|
||||
* The reset data of a window or balance: the countdown first, then the exact time. When the line
|
||||
* is too narrow the exact time truncates and the countdown wraps within its column.
|
||||
* is too narrow the exact time gives way (truncates) and the countdown stays whole.
|
||||
*/
|
||||
export function UsageResetLine({
|
||||
countdown,
|
||||
exactTime,
|
||||
atRisk = false,
|
||||
testID,
|
||||
}: {
|
||||
countdown: string | null;
|
||||
exactTime: string | null;
|
||||
/** The countdown is a runs-out warning rather than a reset. */
|
||||
atRisk?: boolean;
|
||||
testID?: string;
|
||||
}) {
|
||||
if (!countdown) return null;
|
||||
return (
|
||||
<View style={styles.line} testID={testID}>
|
||||
<Text style={[styles.text, styles.countdown]}>{countdown}</Text>
|
||||
<Text style={atRisk ? styles.atRisk : styles.text}>{countdown}</Text>
|
||||
{exactTime ? (
|
||||
<Text style={[styles.text, styles.exactTime]} numberOfLines={1} ellipsizeMode="tail">
|
||||
{`\u00a0·\u00a0${exactTime}`}
|
||||
@@ -28,13 +31,18 @@ export function UsageResetLine({
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
line: { flexDirection: "row", alignItems: "baseline" },
|
||||
line: { flexDirection: "row", alignItems: "center" },
|
||||
text: {
|
||||
flexShrink: 0,
|
||||
color: theme.colors.foregroundMuted,
|
||||
fontSize: theme.fontSize.sm,
|
||||
fontWeight: theme.fontWeight.normal,
|
||||
},
|
||||
countdown: { maxWidth: "100%" },
|
||||
exactTime: { flexShrink: 1, minWidth: 0 },
|
||||
atRisk: {
|
||||
flexShrink: 0,
|
||||
color: theme.colors.statusDanger,
|
||||
fontSize: theme.fontSize.sm,
|
||||
fontWeight: theme.fontWeight.normal,
|
||||
},
|
||||
exactTime: { flexShrink: 1 },
|
||||
}));
|
||||
|
||||
@@ -1,12 +1,6 @@
|
||||
import type {
|
||||
ProviderUsageTone,
|
||||
UsageReportEntry as WireUsageReportEntry,
|
||||
} from "@getpaseo/protocol/messages";
|
||||
import type { ProviderUsageTone, UsageReportEntry } from "@getpaseo/protocol/messages";
|
||||
|
||||
export interface UsageReportEntry extends WireUsageReportEntry {
|
||||
/** A refresh failed while this reading was cached. */
|
||||
forecastStale?: true;
|
||||
}
|
||||
export type { UsageReportEntry };
|
||||
export type UsageReport = UsageReportEntry["report"];
|
||||
export type UsageTone = ProviderUsageTone;
|
||||
export type AvailableUsageReport = Extract<UsageReport, { status: "available" }>;
|
||||
@@ -20,4 +14,4 @@ export type UsageView =
|
||||
| { kind: "unavailable"; message: string }
|
||||
| { kind: "loading" }
|
||||
| { kind: "error"; message: string }
|
||||
| { kind: "ready"; reports: UsageReportEntry[]; isRefreshing: boolean; refreshFailed: boolean };
|
||||
| { kind: "ready"; reports: UsageReportEntry[]; isRefreshing: boolean };
|
||||
|
||||
@@ -84,18 +84,11 @@ export function UsageBody({
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<View style={styles.reports}>
|
||||
{view.refreshFailed ? (
|
||||
<Alert size="sm" variant="error" title={t("providerUsage.refreshFailed")} />
|
||||
) : null}
|
||||
{view.reports.length === 0 ? (
|
||||
<UsageMessage text={t("providerUsage.empty")} />
|
||||
) : (
|
||||
<UsageList serverId={serverId} reports={view.reports} display={display} />
|
||||
)}
|
||||
</View>
|
||||
);
|
||||
if (view.reports.length === 0) {
|
||||
return <UsageMessage text={t("providerUsage.empty")} />;
|
||||
}
|
||||
|
||||
return <UsageList serverId={serverId} reports={view.reports} display={display} />;
|
||||
}
|
||||
|
||||
export function UsageMessage({ text }: { text: string }) {
|
||||
@@ -107,7 +100,6 @@ export function UsageMessage({ text }: { text: string }) {
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
reports: { gap: theme.spacing[3] },
|
||||
emptyCard: {
|
||||
padding: theme.spacing[4],
|
||||
alignItems: "center",
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import type { TFunction } from "i18next";
|
||||
import { Pin } from "lucide-react-native";
|
||||
import { useMemo } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
@@ -7,7 +6,6 @@ import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
|
||||
import {
|
||||
formatDisplayPct,
|
||||
formatPct,
|
||||
formatProviderUsageLabel,
|
||||
formatResetLabel,
|
||||
formatResetTime,
|
||||
@@ -15,9 +13,9 @@ import {
|
||||
} from "./format";
|
||||
import { UsageMeter } from "./meter";
|
||||
import { displayPercent, usageWindowRowLabel } from "./model";
|
||||
import { usagePace } from "./pace";
|
||||
import { UsageResetLine } from "./reset-line";
|
||||
import type { UsageDisplayAs } from "./preferences";
|
||||
import { windowTone } from "./tone";
|
||||
import type { UsageTone, UsageWindow } from "./types";
|
||||
import { useRelativeTimeTick } from "./use-relative-time-tick";
|
||||
|
||||
@@ -30,10 +28,8 @@ export function UsageWindowBar({
|
||||
pinLabel,
|
||||
pinTestID,
|
||||
retained = false,
|
||||
forecastAt,
|
||||
}: {
|
||||
retained?: boolean;
|
||||
forecastAt: string | null;
|
||||
window: UsageWindow;
|
||||
displayAs: UsageDisplayAs;
|
||||
/** Whether the row pins the window to the sidebar. When false the row is a plain bar. */
|
||||
@@ -46,11 +42,19 @@ export function UsageWindowBar({
|
||||
}) {
|
||||
const { t, i18n } = useTranslation();
|
||||
const shownPct = displayPercent(window, displayAs);
|
||||
const tone = windowTone(window);
|
||||
|
||||
const now = useRelativeTimeTick({ enabled: window.runsOutAt != null || window.resetsAt != null });
|
||||
const pace = usagePace(window, forecastAt, now);
|
||||
const forecast = formatPace(pace, now, t);
|
||||
const countdown = formatResetLabel(window.resetsAt, retained, now, t);
|
||||
const exactTime = formatResetTime(window.resetsAt, now, t);
|
||||
const isAtRisk =
|
||||
window.runsOutAt != null &&
|
||||
window.shortfallPct != null &&
|
||||
(!retained || Date.parse(window.runsOutAt) > now);
|
||||
const countdown = isAtRisk
|
||||
? formatRunsOutLabel(window.runsOutAt, now, t)
|
||||
: formatResetLabel(window.resetsAt, retained, now, t);
|
||||
// The exact time belongs to the reset; beside a runs-out warning it would read as the moment
|
||||
// the quota runs out.
|
||||
const exactTime = isAtRisk ? null : formatResetTime(window.resetsAt, now, t);
|
||||
|
||||
const value =
|
||||
shownPct != null ? formatDisplayPct(shownPct, displayAs, i18n.resolvedLanguage, t) : "—";
|
||||
@@ -60,8 +64,9 @@ export function UsageWindowBar({
|
||||
value,
|
||||
countdown,
|
||||
exactTime,
|
||||
forecast,
|
||||
isAtRisk,
|
||||
percent: shownPct ?? 0,
|
||||
tone,
|
||||
pinned,
|
||||
};
|
||||
|
||||
@@ -81,7 +86,7 @@ export function UsageWindowBar({
|
||||
accessibilityLabel={usageWindowRowLabel({
|
||||
pinLabel,
|
||||
value,
|
||||
trailing: [countdown, exactTime, forecast?.label].filter(Boolean).join(" · "),
|
||||
trailing: [countdown, exactTime].filter(Boolean).join(" · "),
|
||||
})}
|
||||
accessibilityState={accessibilityState}
|
||||
aria-checked={pinned}
|
||||
@@ -98,8 +103,9 @@ function WindowRowContent({
|
||||
value,
|
||||
countdown,
|
||||
exactTime,
|
||||
forecast,
|
||||
isAtRisk,
|
||||
percent,
|
||||
tone,
|
||||
pinnable,
|
||||
pinned,
|
||||
}: {
|
||||
@@ -107,8 +113,9 @@ function WindowRowContent({
|
||||
value: string;
|
||||
countdown: string | null;
|
||||
exactTime: string | null;
|
||||
forecast: PaceLabel | null;
|
||||
isAtRisk: boolean;
|
||||
percent: number;
|
||||
tone: UsageTone;
|
||||
pinnable: boolean;
|
||||
pinned: boolean;
|
||||
}) {
|
||||
@@ -123,51 +130,12 @@ function WindowRowContent({
|
||||
</Text>
|
||||
{pinnable ? <UsagePinGlyph pinned={pinned} /> : null}
|
||||
</View>
|
||||
<UsageMeter percent={percent} tone={forecast?.tone ?? "default"} />
|
||||
{countdown || forecast ? (
|
||||
<View style={styles.timingRow}>
|
||||
<View style={styles.resetTiming}>
|
||||
<UsageResetLine countdown={countdown} exactTime={exactTime} />
|
||||
</View>
|
||||
{forecast ? <Text style={styles.forecast(forecast.tone)}>{forecast.label}</Text> : null}
|
||||
</View>
|
||||
) : null}
|
||||
<UsageMeter percent={percent} tone={tone} />
|
||||
<UsageResetLine countdown={countdown} exactTime={exactTime} atRisk={isAtRisk} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
interface PaceLabel {
|
||||
label: string;
|
||||
tone: UsageTone;
|
||||
}
|
||||
|
||||
function formatPace(
|
||||
pace: ReturnType<typeof usagePace>,
|
||||
now: number,
|
||||
t: TFunction,
|
||||
): PaceLabel | null {
|
||||
switch (pace.kind) {
|
||||
case "reached":
|
||||
return { label: t("providerUsage.timing.limitReached"), tone: "danger" };
|
||||
case "runsOut": {
|
||||
const label =
|
||||
Date.parse(pace.at) <= now
|
||||
? t("providerUsage.timing.mayHaveRunOut")
|
||||
: formatRunsOutLabel(pace.at, now, t);
|
||||
return label ? { label, tone: "danger" } : null;
|
||||
}
|
||||
case "remaining":
|
||||
return {
|
||||
label: t("providerUsage.timing.projectedLeftAtReset", {
|
||||
percentage: formatPct(pace.remainingAtResetPct),
|
||||
}),
|
||||
tone: pace.remainingAtResetPct <= 10 ? "warning" : "default",
|
||||
};
|
||||
case "unknown":
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
const ThemedPin = withUnistyles(Pin);
|
||||
|
||||
function UsagePinGlyph({ pinned }: { pinned: boolean }) {
|
||||
@@ -199,23 +167,6 @@ function UsagePinGlyph({ pinned }: { pinned: boolean }) {
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
timingRow: {
|
||||
flexDirection: "row",
|
||||
alignItems: "flex-start",
|
||||
gap: theme.spacing[2],
|
||||
},
|
||||
resetTiming: { flex: 1, minWidth: 0 },
|
||||
forecast: (tone: UsageTone) => ({
|
||||
color: {
|
||||
danger: theme.colors.statusDanger,
|
||||
warning: theme.colors.statusWarning,
|
||||
default: theme.colors.foregroundMuted,
|
||||
ok: theme.colors.statusSuccess,
|
||||
}[tone],
|
||||
fontSize: theme.fontSize.sm,
|
||||
maxWidth: "50%",
|
||||
textAlign: "right",
|
||||
}),
|
||||
row: { gap: 3, paddingVertical: theme.spacing[1.5] },
|
||||
pin: { width: 12, alignItems: "center" },
|
||||
tooltipText: { color: theme.colors.popoverForeground, fontSize: theme.fontSize.sm },
|
||||
|
||||
@@ -14,7 +14,6 @@ import { buildWorkspaceTabPersistenceKey } from "@/workspace-tabs/model";
|
||||
import { archiveWorkspaceWithUndo, supportsWorkspaceArchiveUndo } from "@/workspace/archive-undo";
|
||||
import {
|
||||
archiveWorkspaceOptimistically,
|
||||
runWorkspaceArchiveAttempt,
|
||||
type WorkspaceArchiveTarget,
|
||||
} from "@/workspace/workspace-archive";
|
||||
|
||||
@@ -57,6 +56,7 @@ 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,12 +119,26 @@ export function useWorkspaceArchive(input: ArchiveWorkspaceInput): WorkspaceArch
|
||||
}, [diffStat, name, serverId, t, toast, warningLabels, workspaceDirectory]);
|
||||
|
||||
const archive = useCallback(() => {
|
||||
void runWorkspaceArchiveAttempt({
|
||||
workspace: { serverId, workspaceId },
|
||||
confirm: workspaceKind === "worktree" ? confirmWorktreeArchive : undefined,
|
||||
archive: archiveWorkspaceRecord,
|
||||
});
|
||||
}, [archiveWorkspaceRecord, confirmWorktreeArchive, serverId, workspaceId, workspaceKind]);
|
||||
// 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]);
|
||||
|
||||
return {
|
||||
archive,
|
||||
|
||||
@@ -17,30 +17,6 @@ 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 }>;
|
||||
}
|
||||
|
||||
@@ -1,164 +0,0 @@
|
||||
import type { Locator, Page } from "@playwright/test";
|
||||
import { expect, test } from "../../app/e2e/support/fixtures";
|
||||
import { gotoWorkspace } from "../../app/e2e/support/helpers/launcher";
|
||||
|
||||
function explorerSidebar(page: Page) {
|
||||
return page.getByTestId("workspace-explorer-sidebar").filter({ visible: true });
|
||||
}
|
||||
|
||||
async function useDesktopWindowChrome(page: Page, mode: "native-mac" | "custom-windows") {
|
||||
await page.addInitScript((windowChromeMode) => {
|
||||
Object.assign(window, {
|
||||
paseoDesktop: {
|
||||
platform: windowChromeMode === "native-mac" ? "darwin" : "win32",
|
||||
windowChromeMode,
|
||||
invoke: async () => null,
|
||||
events: { on: async () => () => undefined },
|
||||
getPendingOpenProject: async () => null,
|
||||
window: {
|
||||
getCurrentWindow: () => ({
|
||||
isFullscreen: async () => false,
|
||||
onResized: async () => () => undefined,
|
||||
}),
|
||||
},
|
||||
},
|
||||
});
|
||||
}, mode);
|
||||
}
|
||||
|
||||
function explorerToggle(page: Page, expanded: boolean) {
|
||||
return page.getByRole("button", {
|
||||
name: expanded ? "Close Explorer sidebar" : "Open Explorer sidebar",
|
||||
exact: true,
|
||||
expanded,
|
||||
});
|
||||
}
|
||||
|
||||
async function recordExplorerToggle(button: Locator) {
|
||||
const recording = await button.evaluateHandle((target) => {
|
||||
const measure = () => {
|
||||
const glyph = target.querySelector("svg")?.getBoundingClientRect();
|
||||
return {
|
||||
connected: target.isConnected,
|
||||
x: glyph?.x,
|
||||
y: glyph?.y,
|
||||
width: glyph?.width,
|
||||
height: glyph?.height,
|
||||
};
|
||||
};
|
||||
const before = measure();
|
||||
const frames: ReturnType<typeof measure>[] = [];
|
||||
const done = new Promise<void>((resolve) => {
|
||||
target.addEventListener(
|
||||
"click",
|
||||
() => {
|
||||
const start = performance.now();
|
||||
const sample = () => {
|
||||
frames.push(measure());
|
||||
if (performance.now() - start < 300) requestAnimationFrame(sample);
|
||||
else resolve();
|
||||
};
|
||||
requestAnimationFrame(sample);
|
||||
},
|
||||
{ once: true },
|
||||
);
|
||||
});
|
||||
return { before, frames, done };
|
||||
});
|
||||
try {
|
||||
await button.click();
|
||||
return await recording.evaluate(async ({ before, frames, done }) => {
|
||||
await done;
|
||||
return { before, frames };
|
||||
});
|
||||
} finally {
|
||||
await recording.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
async function expectExplorerToggleHasNativeClickArea(toggle: Locator) {
|
||||
const regions = await toggle.evaluate((button) => {
|
||||
const rect = button.getBoundingClientRect();
|
||||
const x = rect.x + rect.width / 2;
|
||||
const y = rect.y + rect.height / 2;
|
||||
return [
|
||||
...document.querySelectorAll('[style*="app-region"], [data-window-no-drag], [role="button"]'),
|
||||
]
|
||||
.filter((element) => {
|
||||
const bounds = element.getBoundingClientRect();
|
||||
return bounds.left <= x && x < bounds.right && bounds.top <= y && y < bounds.bottom;
|
||||
})
|
||||
.map((element) => getComputedStyle(element).getPropertyValue("-webkit-app-region"))
|
||||
.filter((region) => region === "drag" || region === "no-drag");
|
||||
});
|
||||
expect(regions).toContain("drag");
|
||||
expect(regions.at(-1)).toBe("no-drag");
|
||||
}
|
||||
|
||||
async function expectExplorerToggleInHeaderTabOrder(page: Page, expanded: boolean) {
|
||||
const toggle = explorerToggle(page, expanded);
|
||||
await toggle.focus();
|
||||
await page.keyboard.press("Tab");
|
||||
await expect(page.getByRole("button", { name: "Workspace actions", exact: true })).toBeFocused();
|
||||
await page.keyboard.press("Shift+Tab");
|
||||
await expect(toggle).toBeFocused();
|
||||
}
|
||||
|
||||
async function expectExplorerToggleToHoldPosition(page: Page, expanded: boolean) {
|
||||
const toggle = explorerToggle(page, expanded);
|
||||
await expect(toggle).toBeVisible();
|
||||
await expectExplorerToggleHasNativeClickArea(toggle);
|
||||
const { before, frames } = await recordExplorerToggle(toggle);
|
||||
await expect(explorerToggle(page, !expanded)).toBeVisible();
|
||||
expect(before.width).toBeGreaterThan(0);
|
||||
expect(frames.find((frame) => JSON.stringify(frame) !== JSON.stringify(before))).toBeUndefined();
|
||||
}
|
||||
|
||||
test("keeps the Mac Explorer toggle in place across open and close", async ({
|
||||
page,
|
||||
withWorkspace,
|
||||
}) => {
|
||||
await page.setViewportSize({ width: 1440, height: 900 });
|
||||
await useDesktopWindowChrome(page, "native-mac");
|
||||
|
||||
const { workspaceId } = await withWorkspace();
|
||||
await gotoWorkspace(page, workspaceId);
|
||||
await expectExplorerToggleInHeaderTabOrder(page, false);
|
||||
await expectExplorerToggleToHoldPosition(page, false);
|
||||
await expectExplorerToggleInHeaderTabOrder(page, true);
|
||||
await expectExplorerToggleToHoldPosition(page, true);
|
||||
|
||||
await page.setViewportSize({ width: 930, height: 900 });
|
||||
await expectExplorerToggleToHoldPosition(page, false);
|
||||
await expectExplorerToggleToHoldPosition(page, true);
|
||||
});
|
||||
|
||||
async function expectClearOfWindowControls(page: Page, action: Locator) {
|
||||
const minimize = page.getByRole("button", { name: "Minimize window", exact: true });
|
||||
await expect(minimize).toBeVisible();
|
||||
await expect(action).toBeVisible();
|
||||
const controlBounds = await minimize.boundingBox();
|
||||
const actionBounds = await action.boundingBox();
|
||||
expect(actionBounds!.x + actionBounds!.width).toBeLessThanOrEqual(controlBounds!.x);
|
||||
}
|
||||
|
||||
test("keeps the Explorer actions clear of Windows controls", async ({ page, withWorkspace }) => {
|
||||
await page.setViewportSize({ width: 1440, height: 900 });
|
||||
await useDesktopWindowChrome(page, "custom-windows");
|
||||
|
||||
const { workspaceId } = await withWorkspace();
|
||||
await gotoWorkspace(page, workspaceId);
|
||||
const open = explorerToggle(page, false);
|
||||
await expectClearOfWindowControls(page, open);
|
||||
await open.click();
|
||||
|
||||
const close = explorerToggle(page, true);
|
||||
const newExplorerTab = explorerSidebar(page).getByRole("button", {
|
||||
name: "New tab",
|
||||
exact: true,
|
||||
});
|
||||
await expectClearOfWindowControls(page, close);
|
||||
await expectClearOfWindowControls(page, newExplorerTab);
|
||||
await close.click();
|
||||
await expect(open).toBeVisible();
|
||||
});
|
||||
@@ -96,12 +96,12 @@ test.each([
|
||||
])(
|
||||
"duration %s owns the window's identity and both names",
|
||||
(durationSeconds, id, label, shortLabel) => {
|
||||
const window = windowFromReportedDuration({
|
||||
durationSeconds: durationSeconds as number | null,
|
||||
unknown: { id: "primary", label: "Primary limit", shortLabel: "" },
|
||||
utilizationPct: 11,
|
||||
});
|
||||
expect(window).toMatchObject({ id, label, shortLabel, usedPct: 11 });
|
||||
expect(window.durationSeconds).toBe(durationSeconds ?? undefined);
|
||||
expect(
|
||||
windowFromReportedDuration({
|
||||
durationSeconds: durationSeconds as number | null,
|
||||
unknown: { id: "primary", label: "Primary limit", shortLabel: "" },
|
||||
utilizationPct: 11,
|
||||
}),
|
||||
).toMatchObject({ id, label, shortLabel, usedPct: 11 });
|
||||
},
|
||||
);
|
||||
|
||||
@@ -16,8 +16,6 @@ export interface UsageWindow {
|
||||
usedPct?: number | null;
|
||||
remainingPct?: number | null;
|
||||
resetsAt?: string | null;
|
||||
/** Full length of the quota window when known. */
|
||||
durationSeconds?: number;
|
||||
runsOutAt?: string | null;
|
||||
shortfallPct?: number | null;
|
||||
tone?: "default" | "ok" | "warning" | "danger";
|
||||
@@ -50,8 +48,6 @@ export type UsageReport =
|
||||
| {
|
||||
status: "available";
|
||||
planLabel?: string;
|
||||
/** When the provider measured the quota, if the report returns a previous reading. */
|
||||
observedAt?: string;
|
||||
windows: UsageWindow[];
|
||||
balances?: UsageBalance[];
|
||||
details?: UsageDetail[];
|
||||
@@ -100,7 +96,6 @@ export function windowFromUsedPct(input: {
|
||||
shortLabel?: string;
|
||||
summary?: boolean;
|
||||
utilizationPct: number | null | undefined;
|
||||
durationSeconds?: number;
|
||||
resetsAt?: string | null;
|
||||
tone?: UsageWindow["tone"];
|
||||
}): UsageWindow {
|
||||
@@ -112,7 +107,6 @@ export function windowFromUsedPct(input: {
|
||||
remainingPct: usedPct === null ? null : Math.max(0, 100 - usedPct),
|
||||
resetsAt: input.resetsAt ?? null,
|
||||
};
|
||||
if (input.durationSeconds !== undefined) window.durationSeconds = input.durationSeconds;
|
||||
if (input.shortLabel !== undefined) window.shortLabel = input.shortLabel;
|
||||
if (input.summary) window.summary = true;
|
||||
if (input.tone) window.tone = input.tone;
|
||||
@@ -135,10 +129,11 @@ export function windowFromReportedDuration(input: {
|
||||
summary?: boolean;
|
||||
tone?: UsageWindow["tone"];
|
||||
}): UsageWindow {
|
||||
const reported = input.durationSeconds;
|
||||
const duration =
|
||||
reported !== null && Number.isFinite(reported) && reported > 0 ? reported : undefined;
|
||||
const name = duration === undefined ? input.unknown : durationWindowName(duration);
|
||||
const duration = input.durationSeconds;
|
||||
const name =
|
||||
duration !== null && Number.isFinite(duration) && duration > 0
|
||||
? durationWindowName(duration)
|
||||
: input.unknown;
|
||||
const scope = input.scope;
|
||||
return windowFromUsedPct({
|
||||
id: scope ? `${scope.id}:${name.id}` : name.id,
|
||||
@@ -147,7 +142,6 @@ export function windowFromReportedDuration(input: {
|
||||
? `${scope.label}${name.shortLabel ? ` ${name.shortLabel}` : ""}`
|
||||
: name.shortLabel,
|
||||
utilizationPct: input.utilizationPct,
|
||||
durationSeconds: duration,
|
||||
resetsAt: input.resetsAt,
|
||||
summary: input.summary,
|
||||
tone: input.tone,
|
||||
|
||||
@@ -6992,7 +6992,6 @@ export const ProviderUsageWindowSchema = z.object({
|
||||
usedPct: z.number().nullable().optional(),
|
||||
remainingPct: z.number().nullable().optional(),
|
||||
resetsAt: z.string().nullable().optional(),
|
||||
durationSeconds: z.number().optional(),
|
||||
runsOutAt: z.string().nullable().optional(),
|
||||
shortfallPct: z.number().nullable().optional(),
|
||||
tone: ProviderUsageToneSchema.optional(),
|
||||
@@ -7055,7 +7054,6 @@ export const UsageProblemSchema = z.discriminatedUnion("kind", [
|
||||
const AvailableUsageReportSchema = z.object({
|
||||
status: z.literal("available"),
|
||||
planLabel: z.string().optional(),
|
||||
observedAt: z.string().optional(),
|
||||
windows: z.array(ProviderUsageWindowSchema),
|
||||
balances: z.array(ProviderUsageBalanceSchema).optional(),
|
||||
details: z.array(ProviderUsageDetailSchema).optional(),
|
||||
|
||||
@@ -1,12 +1,11 @@
|
||||
import { readFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { FORGE_IDS } from "@getpaseo/protocol/forge-manifest";
|
||||
import type { Logger } from "pino";
|
||||
import { z } from "zod";
|
||||
import type { ChangeRequestRouter } from "../../../services/change-request-router.js";
|
||||
import {
|
||||
changeRequestStatusSchema,
|
||||
type ChangeRequestSnapshot,
|
||||
type ChangeRequestSource,
|
||||
} from "../../../services/change-request-source.js";
|
||||
import type { AgentMessageDelivery } from "../agent-messages/index.js";
|
||||
import type {
|
||||
@@ -16,17 +15,13 @@ import type {
|
||||
import { writeJsonFileAtomic } from "../../atomic-file.js";
|
||||
|
||||
const DIGEST_WINDOW_MS = 30_000;
|
||||
const LEGACY_DEFAULT_FORGE = "github";
|
||||
const LEGACY_INFERENCE_FORGES = ["github", "gitlab"] as const;
|
||||
const persistedWatchGroupSchema = z.object({
|
||||
forge: z.string().min(1).optional(),
|
||||
const watchGroupSchema = z.object({
|
||||
url: z.url(),
|
||||
snapshot: changeRequestStatusSchema,
|
||||
seenActivity: z.array(z.string()),
|
||||
watchers: z.array(z.object({ agentId: z.string(), startedAt: z.string().optional() })),
|
||||
});
|
||||
type PersistedWatchGroup = z.infer<typeof persistedWatchGroupSchema>;
|
||||
type WatchGroup = Omit<PersistedWatchGroup, "forge"> & { forge: string };
|
||||
type WatchGroup = z.infer<typeof watchGroupSchema>;
|
||||
type Watcher = WatchGroup["watchers"][number];
|
||||
interface DigestWindow {
|
||||
dueAt: number;
|
||||
@@ -40,7 +35,7 @@ interface Observation {
|
||||
release(): void;
|
||||
}
|
||||
interface Dependencies {
|
||||
router: ChangeRequestRouter;
|
||||
source: ChangeRequestSource;
|
||||
paseoHome: string;
|
||||
logger: Logger;
|
||||
isActive(agentId: string): Promise<boolean>;
|
||||
@@ -78,7 +73,7 @@ function describeUpdate(group: WatchGroup, next: ChangeRequestSnapshot) {
|
||||
}
|
||||
for (const activity of next.activity) {
|
||||
if (seen.has(activity.id)) continue;
|
||||
changes.push(activity.message ?? `New ${activity.kind}: ${activity.url}`);
|
||||
changes.push(`New ${activity.kind}: ${activity.url}`);
|
||||
seen.add(activity.id);
|
||||
}
|
||||
if (next.state !== "open") changes.push(`Change request ${next.state}.`);
|
||||
@@ -90,7 +85,6 @@ export type ChangeRequestWatches = ReturnType<typeof createChangeRequestWatches>
|
||||
export function createChangeRequestWatches(deps: Dependencies) {
|
||||
const file = join(deps.paseoHome, "change-request-watches.json");
|
||||
const groups = new Map<string, WatchGroup>();
|
||||
const unrestored: WatchGroup[] = [];
|
||||
const observations = new Map<string, Observation>();
|
||||
const registrations = new Map<string, number>();
|
||||
let mutations = Promise.resolve();
|
||||
@@ -162,47 +156,32 @@ export function createChangeRequestWatches(deps: Dependencies) {
|
||||
}
|
||||
}
|
||||
|
||||
function withdraw(agentId: string, matches: (url: string) => boolean): string | undefined {
|
||||
let withdrawn: string | undefined;
|
||||
for (const [url, window] of windows) {
|
||||
if (!window.recipients.has(agentId) || !matches(url)) continue;
|
||||
window.recipients.delete(agentId);
|
||||
withdrawn ??= url;
|
||||
function withdraw(agentId: string, url?: string): boolean {
|
||||
let removed = false;
|
||||
for (const [address, window] of windows) {
|
||||
if (url && address !== url) continue;
|
||||
removed = window.recipients.delete(agentId) || removed;
|
||||
if (!window.recipients.size) {
|
||||
clearTimeout(window.timer);
|
||||
windows.delete(url);
|
||||
windows.delete(address);
|
||||
}
|
||||
}
|
||||
deps.messages().withdrawPending(agentId, (source) => {
|
||||
if (source.kind !== "change-request-update" || !matches(source.url)) return false;
|
||||
withdrawn ??= source.url;
|
||||
return true;
|
||||
});
|
||||
return withdrawn;
|
||||
}
|
||||
|
||||
function withdrawByInput(agentId: string, input: string): string | undefined {
|
||||
const trimmed = input.trim();
|
||||
const candidates = new Set([trimmed]);
|
||||
for (const forge of FORGE_IDS) {
|
||||
const source = deps.router.source(forge);
|
||||
if (!source) continue;
|
||||
try {
|
||||
candidates.add(source.resolve(trimmed));
|
||||
} catch {
|
||||
// This source does not recognize the URL.
|
||||
}
|
||||
}
|
||||
return withdraw(agentId, (url) => candidates.has(url));
|
||||
const queued = deps
|
||||
.messages()
|
||||
.withdrawPending(
|
||||
agentId,
|
||||
(source) => source.kind === "change-request-update" && (!url || source.url === url),
|
||||
);
|
||||
return removed || queued > 0;
|
||||
}
|
||||
|
||||
async function commit(...updates: WatchGroup[]): Promise<void> {
|
||||
const next = new Map(groups);
|
||||
for (const group of updates) next.set(group.url, group);
|
||||
await writeJsonFileAtomic(file, [
|
||||
...[...next.values()].filter(({ watchers }) => watchers.length),
|
||||
...unrestored,
|
||||
]);
|
||||
await writeJsonFileAtomic(
|
||||
file,
|
||||
[...next.values()].filter(({ watchers }) => watchers.length),
|
||||
);
|
||||
for (const group of updates) {
|
||||
const previous = groups.get(group.url);
|
||||
// An in-flight subscription still needs the committed baseline and its observation.
|
||||
@@ -216,20 +195,7 @@ export function createChangeRequestWatches(deps: Dependencies) {
|
||||
}
|
||||
}
|
||||
|
||||
function describeWatch(forge: string, url: string): string {
|
||||
const source = deps.router.source(forge);
|
||||
if (!source) return url;
|
||||
try {
|
||||
return source.describe(url);
|
||||
} catch {
|
||||
return url;
|
||||
}
|
||||
}
|
||||
|
||||
function syncBackgroundWork(
|
||||
{ forge, url, watchers }: WatchGroup,
|
||||
previous: Watcher[] = [],
|
||||
): void {
|
||||
function syncBackgroundWork({ url, watchers }: WatchGroup, previous: Watcher[] = []): void {
|
||||
if (previous === watchers) return;
|
||||
const current = new Set(watchers);
|
||||
for (const watcher of previous) {
|
||||
@@ -243,7 +209,7 @@ export function createChangeRequestWatches(deps: Dependencies) {
|
||||
deps.backgroundWork.setDaemonBackgroundWork({
|
||||
...backgroundWorkKey(watcher.agentId, url),
|
||||
kind: "monitor",
|
||||
description: describeWatch(forge, url),
|
||||
description: deps.source.describe(url),
|
||||
startedAt: watcher.startedAt ?? new Date().toISOString(),
|
||||
stop: async () => {
|
||||
await unsubscribe(watcher.agentId, url, watcher);
|
||||
@@ -252,13 +218,9 @@ export function createChangeRequestWatches(deps: Dependencies) {
|
||||
}
|
||||
}
|
||||
|
||||
function observe(forge: string, url: string): Observation {
|
||||
function observe(url: string): Observation {
|
||||
const existing = observations.get(url);
|
||||
if (existing) return existing;
|
||||
const source = deps.router.source(forge);
|
||||
if (!source) {
|
||||
throw new Error(`Change request watches are not supported for ${forge}.`);
|
||||
}
|
||||
let resolve!: (snapshot: ChangeRequestSnapshot) => void;
|
||||
let reject!: (error: unknown) => void;
|
||||
const ready = new Promise<ChangeRequestSnapshot>((accept, fail) => {
|
||||
@@ -266,7 +228,7 @@ export function createChangeRequestWatches(deps: Dependencies) {
|
||||
reject = fail;
|
||||
});
|
||||
void ready.catch(() => undefined);
|
||||
const release = source.observe(url, {
|
||||
const release = deps.source.observe(url, {
|
||||
knownActivity: () => new Set(groups.get(url)?.seenActivity),
|
||||
snapshot: (snapshot) =>
|
||||
serialize(async () => {
|
||||
@@ -304,14 +266,14 @@ export function createChangeRequestWatches(deps: Dependencies) {
|
||||
}),
|
||||
error(error) {
|
||||
if (!observation.stale) {
|
||||
deps.logger.warn({ err: error, url, forge }, "Change request observation became stale");
|
||||
deps.logger.warn({ err: error, url }, "Change request observation became stale");
|
||||
}
|
||||
observation.stale = true;
|
||||
if (!groups.has(url)) {
|
||||
reject(error);
|
||||
stopObserving(url);
|
||||
}
|
||||
deps.logger.debug({ err: error, url, forge }, "Change request observation failed");
|
||||
deps.logger.debug({ err: error, url }, "Change request observation failed");
|
||||
},
|
||||
});
|
||||
const observation: Observation = {
|
||||
@@ -326,62 +288,16 @@ export function createChangeRequestWatches(deps: Dependencies) {
|
||||
return observation;
|
||||
}
|
||||
|
||||
function matchActiveGroup(input: string): { forge: string; url: string } | null {
|
||||
const trimmed = input.trim();
|
||||
const direct = groups.get(trimmed);
|
||||
if (direct) return { forge: direct.forge, url: direct.url };
|
||||
const sourcesTried = new Set<string>();
|
||||
for (const group of groups.values()) {
|
||||
if (sourcesTried.has(group.forge)) continue;
|
||||
sourcesTried.add(group.forge);
|
||||
const source = deps.router.source(group.forge);
|
||||
if (!source) continue;
|
||||
try {
|
||||
const canonical = source.resolve(trimmed);
|
||||
const matched = groups.get(canonical);
|
||||
if (matched && matched.forge === group.forge) {
|
||||
return { forge: matched.forge, url: matched.url };
|
||||
}
|
||||
} catch {
|
||||
// Input did not belong to this forge.
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function subscribe(agentId: string, input: string) {
|
||||
if (closed) return Promise.reject(new Error("Change request watches are closed"));
|
||||
if (recoveryError) {
|
||||
return Promise.reject(
|
||||
new Error("Change request watches could not recover.", { cause: recoveryError }),
|
||||
);
|
||||
}
|
||||
const active = matchActiveGroup(input);
|
||||
if (active) {
|
||||
return subscribeResolved(agentId, active.forge, active.url);
|
||||
}
|
||||
return deps.router
|
||||
.resolve(input)
|
||||
.then(({ forge, url }) => subscribeResolved(agentId, forge, url));
|
||||
}
|
||||
|
||||
function subscribeResolved(agentId: string, forge: string, url: string) {
|
||||
async function subscribe(agentId: string, input: string) {
|
||||
if (closed) throw new Error("Change request watches are closed");
|
||||
const url = deps.source.resolve(input);
|
||||
if (recoveryError)
|
||||
throw new Error("Change request watches could not recover.", { cause: recoveryError });
|
||||
registrations.set(url, (registrations.get(url) ?? 0) + 1);
|
||||
const existing = groups.get(url);
|
||||
const finish = () => {
|
||||
const remaining = registrations.get(url)! - 1;
|
||||
if (remaining) {
|
||||
registrations.set(url, remaining);
|
||||
} else {
|
||||
registrations.delete(url);
|
||||
if (!groups.get(url)?.watchers.length) {
|
||||
groups.delete(url);
|
||||
stopObserving(url);
|
||||
}
|
||||
}
|
||||
};
|
||||
const commitSubscription = (initial: ChangeRequestSnapshot) =>
|
||||
serialize(async () => {
|
||||
try {
|
||||
const existing = groups.get(url);
|
||||
const initial = existing ? { ...existing.snapshot, activity: [] } : await observe(url).ready;
|
||||
return await serialize(async () => {
|
||||
if (closed || !(await deps.isActive(agentId))) throw new Error("Agent is no longer active");
|
||||
const group = groups.get(url);
|
||||
const { activity, ...initialStatus } = initial;
|
||||
@@ -389,7 +305,6 @@ export function createChangeRequestWatches(deps: Dependencies) {
|
||||
const subscribed = snapshot.state === "open";
|
||||
if (subscribed && !group?.watchers.some((watcher) => watcher.agentId === agentId)) {
|
||||
await commit({
|
||||
forge: group?.forge ?? forge,
|
||||
url,
|
||||
snapshot,
|
||||
seenActivity: group?.seenActivity ?? activity.map(({ id }) => id),
|
||||
@@ -407,13 +322,21 @@ export function createChangeRequestWatches(deps: Dependencies) {
|
||||
checks: snapshot.checks,
|
||||
reviewDecision: snapshot.reviewDecision,
|
||||
subscribed,
|
||||
stale: observations.get(url)?.stale ?? Boolean(existing),
|
||||
stale: observations.get(url)?.stale ?? false,
|
||||
};
|
||||
});
|
||||
const pending = existing
|
||||
? commitSubscription({ ...existing.snapshot, activity: [] })
|
||||
: observe(forge, url).ready.then(commitSubscription);
|
||||
return pending.finally(finish);
|
||||
} finally {
|
||||
const remaining = registrations.get(url)! - 1;
|
||||
if (remaining) {
|
||||
registrations.set(url, remaining);
|
||||
} else {
|
||||
registrations.delete(url);
|
||||
if (!groups.get(url)?.watchers.length) {
|
||||
groups.delete(url);
|
||||
stopObserving(url);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function removeWatcher(group: WatchGroup, agentId: string): Promise<void> {
|
||||
@@ -432,15 +355,15 @@ export function createChangeRequestWatches(deps: Dependencies) {
|
||||
throw new Error("Background work is no longer available to stop");
|
||||
}
|
||||
if (group && watcher) await removeWatcher(group, agentId);
|
||||
const withdrawn = withdraw(agentId, (address) => address === url);
|
||||
return { url, removed: Boolean(watcher || withdrawn) };
|
||||
const withdrawn = withdraw(agentId, url);
|
||||
return { url, removed: Boolean(watcher) || withdrawn };
|
||||
});
|
||||
}
|
||||
|
||||
function archive(agentId: string): Promise<void> {
|
||||
return serialize(async () => {
|
||||
if (closed) return;
|
||||
withdraw(agentId, () => true);
|
||||
withdraw(agentId);
|
||||
const updates: WatchGroup[] = [];
|
||||
for (const group of groups.values()) {
|
||||
const watchers = group.watchers.filter((watcher) => watcher.agentId !== agentId);
|
||||
@@ -450,20 +373,6 @@ export function createChangeRequestWatches(deps: Dependencies) {
|
||||
});
|
||||
}
|
||||
|
||||
function inferLegacyForge(url: string): string {
|
||||
for (const candidate of LEGACY_INFERENCE_FORGES) {
|
||||
const source = deps.router.source(candidate);
|
||||
if (!source) continue;
|
||||
try {
|
||||
source.resolve(url);
|
||||
return candidate;
|
||||
} catch {
|
||||
// URL does not match this forge's canonical path shape.
|
||||
}
|
||||
}
|
||||
return LEGACY_DEFAULT_FORGE;
|
||||
}
|
||||
|
||||
return {
|
||||
async start() {
|
||||
const active: WatchGroup[] = [];
|
||||
@@ -473,12 +382,8 @@ export function createChangeRequestWatches(deps: Dependencies) {
|
||||
if (error.code === "ENOENT") return "[]";
|
||||
throw error;
|
||||
});
|
||||
const restored = z.array(persistedWatchGroupSchema).parse(JSON.parse(stored));
|
||||
for (const record of restored) {
|
||||
const group: WatchGroup = {
|
||||
...record,
|
||||
forge: record.forge ?? inferLegacyForge(record.url),
|
||||
};
|
||||
const restored = z.array(watchGroupSchema).parse(JSON.parse(stored));
|
||||
for (const group of restored) {
|
||||
if (group.snapshot.state !== "open") {
|
||||
pruned = true;
|
||||
continue;
|
||||
@@ -488,17 +393,7 @@ export function createChangeRequestWatches(deps: Dependencies) {
|
||||
if (await deps.isActive(watcher.agentId)) watchers.push(watcher);
|
||||
}
|
||||
pruned ||= watchers.length !== group.watchers.length;
|
||||
if (!watchers.length) continue;
|
||||
const nextGroup = { ...group, watchers };
|
||||
if (!deps.router.source(nextGroup.forge)) {
|
||||
deps.logger.warn(
|
||||
{ forge: nextGroup.forge, url: nextGroup.url },
|
||||
"Skipping persisted change request watch for unsupported forge",
|
||||
);
|
||||
unrestored.push(nextGroup);
|
||||
continue;
|
||||
}
|
||||
active.push(nextGroup);
|
||||
if (watchers.length) active.push({ ...group, watchers });
|
||||
}
|
||||
} catch (error) {
|
||||
recoveryError = error;
|
||||
@@ -507,7 +402,7 @@ export function createChangeRequestWatches(deps: Dependencies) {
|
||||
}
|
||||
if (pruned) {
|
||||
try {
|
||||
await writeJsonFileAtomic(file, [...active, ...unrestored]);
|
||||
await writeJsonFileAtomic(file, active);
|
||||
} catch (error) {
|
||||
deps.logger.warn({ err: error, file }, "Could not prune archived change request watches");
|
||||
}
|
||||
@@ -515,24 +410,12 @@ export function createChangeRequestWatches(deps: Dependencies) {
|
||||
for (const group of active) {
|
||||
groups.set(group.url, group);
|
||||
syncBackgroundWork(group);
|
||||
try {
|
||||
observe(group.forge, group.url);
|
||||
} catch (error) {
|
||||
deps.logger.warn(
|
||||
{ err: error, forge: group.forge, url: group.url },
|
||||
"Could not start observing restored change request watch",
|
||||
);
|
||||
}
|
||||
observe(group.url);
|
||||
}
|
||||
},
|
||||
subscribe,
|
||||
async unsubscribe(agentId: string, input: string) {
|
||||
const active = matchActiveGroup(input);
|
||||
if (active) return unsubscribe(agentId, active.url);
|
||||
const withdrawn = await serialize(async () => withdrawByInput(agentId, input));
|
||||
if (withdrawn) return { url: withdrawn, removed: true };
|
||||
const { url } = await deps.router.resolve(input);
|
||||
return unsubscribe(agentId, url);
|
||||
unsubscribe(agentId: string, input: string) {
|
||||
return unsubscribe(agentId, deps.source.resolve(input));
|
||||
},
|
||||
archive,
|
||||
async close() {
|
||||
|
||||
@@ -1,18 +1,16 @@
|
||||
import { mkdir, mkdtemp, readFile, rename, rm, writeFile } from "node:fs/promises";
|
||||
import { mkdir, mkdtemp, readFile, rename, rm } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import pino from "pino";
|
||||
import { afterEach, expect, test, vi } from "vitest";
|
||||
import { createChangeRequestWatches } from "./index.js";
|
||||
import { AgentBackgroundWorkStore } from "../background-work/index.js";
|
||||
import { createAgentMessageDelivery, parseAgentMessages } from "../agent-messages/index.js";
|
||||
import type { ChangeRequestRouter } from "../../../services/change-request-router.js";
|
||||
import type {
|
||||
ChangeRequestSnapshot,
|
||||
ChangeRequestSource,
|
||||
} from "../../../services/change-request-source.js";
|
||||
|
||||
const url = "https://github.com/owner/repo/pull/42";
|
||||
const gitlabUrl = "https://gitlab.com/org/sub/app/-/merge_requests/9";
|
||||
const reviewUrl = url + "#pullrequestreview-1";
|
||||
const initial: ChangeRequestSnapshot = {
|
||||
state: "open",
|
||||
@@ -33,19 +31,13 @@ async function createTestHome() {
|
||||
|
||||
function createHarness(
|
||||
home: string,
|
||||
{
|
||||
isActive = async (_id: string) => true,
|
||||
observationFails = false,
|
||||
resolveFails = false,
|
||||
extraSources = {} as Record<string, ChangeRequestSource>,
|
||||
} = {},
|
||||
{ isActive = async (_id: string) => true, observationFails = false } = {},
|
||||
) {
|
||||
const observations = new Map<string, Parameters<ChangeRequestSource["observe"]>[1]>();
|
||||
const backgroundWork = new AgentBackgroundWorkStore();
|
||||
const busy = new Set<string>();
|
||||
const turns: { recipientId: string; prompt: string }[] = [];
|
||||
const listeners = new Set<(id: string) => void>();
|
||||
const resolveCalls: string[] = [];
|
||||
const messages = createAgentMessageDelivery({
|
||||
isRunning: (id) => busy.has(id),
|
||||
subscribe(listener) {
|
||||
@@ -60,16 +52,10 @@ function createHarness(
|
||||
throw error;
|
||||
},
|
||||
});
|
||||
function createFakeSource(
|
||||
describe: (address: string) => string,
|
||||
accepts: (input: string) => boolean,
|
||||
): ChangeRequestSource {
|
||||
return {
|
||||
resolve: (input) => {
|
||||
if (!accepts(input)) throw new Error("Unsupported URL for fake forge");
|
||||
return input.replace(/\/+$/, "");
|
||||
},
|
||||
describe,
|
||||
const watches = createChangeRequestWatches({
|
||||
source: {
|
||||
resolve: (input) => input,
|
||||
describe: () => "owner/repo #42",
|
||||
observe(address, callbacks) {
|
||||
observations.set(address, callbacks);
|
||||
queueMicrotask(() => {
|
||||
@@ -78,34 +64,7 @@ function createHarness(
|
||||
});
|
||||
return () => observations.delete(address);
|
||||
},
|
||||
};
|
||||
}
|
||||
const sources: Record<string, ChangeRequestSource> = {
|
||||
github: createFakeSource(
|
||||
() => "owner/repo #42",
|
||||
(input) => input.includes("/pull/"),
|
||||
),
|
||||
gitlab: createFakeSource(
|
||||
() => "org/sub/app !9",
|
||||
(input) => input.includes("/merge_requests/"),
|
||||
),
|
||||
...extraSources,
|
||||
};
|
||||
const router: ChangeRequestRouter = {
|
||||
async resolve(input) {
|
||||
resolveCalls.push(input);
|
||||
if (resolveFails) throw new Error("Host probe failed");
|
||||
const forge = input.includes("gitlab") ? "gitlab" : "github";
|
||||
const source = sources[forge];
|
||||
if (!source) throw new Error(`Unsupported forge: ${forge}`);
|
||||
return { forge, url: source.resolve(input) };
|
||||
},
|
||||
source(forge) {
|
||||
return sources[forge] ?? null;
|
||||
},
|
||||
};
|
||||
const watches = createChangeRequestWatches({
|
||||
router,
|
||||
paseoHome: home,
|
||||
logger: pino({ enabled: false }),
|
||||
isActive,
|
||||
@@ -119,7 +78,6 @@ function createHarness(
|
||||
messages,
|
||||
watches,
|
||||
backgroundWork,
|
||||
resolveCalls,
|
||||
idle(id: string) {
|
||||
busy.delete(id);
|
||||
for (const listener of listeners) listener(id);
|
||||
@@ -297,47 +255,6 @@ test("can withdraw a terminal digest after its observation has stopped", async (
|
||||
}
|
||||
});
|
||||
|
||||
test.each([0, 32_000])(
|
||||
"withdraws a terminal update without a host probe after %i ms",
|
||||
async (elapsed) => {
|
||||
vi.useFakeTimers();
|
||||
const home = await createTestHome();
|
||||
const enterpriseUrl = "https://github.example.com/owner/repo/pull/42";
|
||||
const { activity: _activity, ...snapshot } = initial;
|
||||
await writeFile(
|
||||
join(home, "change-request-watches.json"),
|
||||
JSON.stringify([
|
||||
{
|
||||
forge: "github",
|
||||
url: enterpriseUrl,
|
||||
snapshot,
|
||||
seenActivity: [],
|
||||
watchers: [{ agentId: "first" }],
|
||||
},
|
||||
]),
|
||||
);
|
||||
const h = createHarness(home, { resolveFails: true });
|
||||
try {
|
||||
h.busy.add("first");
|
||||
await h.watches.start();
|
||||
await h.observations.get(enterpriseUrl)!.snapshot({ ...initial, state: "merged" });
|
||||
expect(h.observations.has(enterpriseUrl)).toBe(false);
|
||||
await vi.advanceTimersByTimeAsync(elapsed);
|
||||
await expect(h.watches.unsubscribe("first", `${enterpriseUrl}/`)).resolves.toEqual({
|
||||
url: enterpriseUrl,
|
||||
removed: true,
|
||||
});
|
||||
expect(h.resolveCalls).toEqual([]);
|
||||
h.idle("first");
|
||||
await vi.advanceTimersByTimeAsync(32_000);
|
||||
expect(h.turns).toEqual([]);
|
||||
} finally {
|
||||
await h.close();
|
||||
await rm(home, { recursive: true, force: true });
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
test("retains the current observation as the last subscriber leaves and a new one joins", async () => {
|
||||
const home = await createTestHome();
|
||||
const h = createHarness(home);
|
||||
@@ -426,119 +343,3 @@ test("recovers active watches even when pruning archived watchers cannot be writ
|
||||
await rm(home, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("persists forge ids, restores legacy GitHub watches without probing, and preserves unknown forges", async () => {
|
||||
const home = await createTestHome();
|
||||
const file = join(home, "change-request-watches.json");
|
||||
const legacyRecord = {
|
||||
url,
|
||||
snapshot: {
|
||||
state: "open",
|
||||
headSha: "aaa",
|
||||
checksState: "pending",
|
||||
checks: [],
|
||||
reviewDecision: null,
|
||||
},
|
||||
seenActivity: [],
|
||||
watchers: [{ agentId: "legacy-agent", startedAt: "2026-01-01T00:00:00.000Z" }],
|
||||
};
|
||||
const unknownForgeRecord = {
|
||||
forge: "futureforge",
|
||||
url: "https://future.example.com/team/repo/cr/5",
|
||||
snapshot: legacyRecord.snapshot,
|
||||
seenActivity: [],
|
||||
watchers: [{ agentId: "future-agent", startedAt: "2026-01-01T00:00:00.000Z" }],
|
||||
};
|
||||
const strippedGitLabRecord = {
|
||||
url: gitlabUrl,
|
||||
snapshot: legacyRecord.snapshot,
|
||||
seenActivity: [],
|
||||
watchers: [{ agentId: "gitlab-agent", startedAt: "2026-01-01T00:00:00.000Z" }],
|
||||
};
|
||||
await writeFile(
|
||||
file,
|
||||
JSON.stringify([legacyRecord, strippedGitLabRecord, unknownForgeRecord]),
|
||||
"utf8",
|
||||
);
|
||||
|
||||
const h = createHarness(home, { resolveFails: true });
|
||||
try {
|
||||
await h.watches.start();
|
||||
expect(h.resolveCalls).toEqual([]);
|
||||
expect(h.backgroundWork.list("legacy-agent")).toEqual([
|
||||
expect.objectContaining({ description: "owner/repo #42", kind: "monitor" }),
|
||||
]);
|
||||
expect(h.backgroundWork.list("gitlab-agent")).toEqual([
|
||||
expect.objectContaining({ description: "org/sub/app !9", kind: "monitor" }),
|
||||
]);
|
||||
expect(h.observations.has(url)).toBe(true);
|
||||
expect(h.observations.has(gitlabUrl)).toBe(true);
|
||||
|
||||
// Unsubscribing an active watch succeeds even when host resolution is temporarily down.
|
||||
await expect(h.watches.unsubscribe("legacy-agent", `${url}/`)).resolves.toEqual({
|
||||
url,
|
||||
removed: true,
|
||||
});
|
||||
expect(h.backgroundWork.list("legacy-agent")).toEqual([]);
|
||||
const persisted = JSON.parse(await readFile(file, "utf8")) as Array<{
|
||||
forge?: string;
|
||||
url: string;
|
||||
}>;
|
||||
expect(persisted).toEqual([
|
||||
expect.objectContaining({ forge: "gitlab", url: gitlabUrl }),
|
||||
unknownForgeRecord,
|
||||
]);
|
||||
} finally {
|
||||
await h.close();
|
||||
await rm(home, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("watches multiple forges concurrently with forge-native descriptions and custom approval messages", async () => {
|
||||
vi.useFakeTimers();
|
||||
const home = await createTestHome();
|
||||
const file = join(home, "change-request-watches.json");
|
||||
const h = createHarness(home);
|
||||
try {
|
||||
await h.watches.start();
|
||||
await h.watches.subscribe("agent-1", url);
|
||||
await h.watches.subscribe("agent-1", gitlabUrl);
|
||||
expect(h.backgroundWork.list("agent-1").map((item) => item.description)).toEqual([
|
||||
"owner/repo #42",
|
||||
"org/sub/app !9",
|
||||
]);
|
||||
|
||||
const persisted = JSON.parse(await readFile(file, "utf8")) as Array<{
|
||||
forge?: string;
|
||||
url: string;
|
||||
}>;
|
||||
expect(persisted.map(({ forge, url: entryUrl }) => ({ forge, url: entryUrl }))).toEqual([
|
||||
{ forge: "github", url },
|
||||
{ forge: "gitlab", url: gitlabUrl },
|
||||
]);
|
||||
|
||||
await h.observations.get(gitlabUrl)!.snapshot({
|
||||
...initial,
|
||||
activity: [
|
||||
{
|
||||
id: "approval-note:77",
|
||||
kind: "approval",
|
||||
url: `${gitlabUrl}#note_77`,
|
||||
message: `Merge request approved by @alice (1/1 approvals): ${gitlabUrl}#note_77`,
|
||||
},
|
||||
],
|
||||
});
|
||||
await vi.advanceTimersByTimeAsync(32_000);
|
||||
expect(h.turns).toEqual([
|
||||
{
|
||||
recipientId: "agent-1",
|
||||
prompt: expect.stringContaining(
|
||||
`Merge request approved by @alice (1/1 approvals): ${gitlabUrl}#note_77`,
|
||||
),
|
||||
},
|
||||
]);
|
||||
} finally {
|
||||
await h.close();
|
||||
await rm(home, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -2728,19 +2728,13 @@ function createToolCatalog(
|
||||
|
||||
if (options.changeRequestWatches) {
|
||||
const watches = options.changeRequestWatches;
|
||||
const inputSchema = {
|
||||
url: z
|
||||
.string()
|
||||
.trim()
|
||||
.min(1)
|
||||
.describe("URL of a pull request or merge request on a supported forge."),
|
||||
};
|
||||
const inputSchema = { url: z.string().trim().min(1).describe("URL of a GitHub pull request.") };
|
||||
registerTool(
|
||||
"subscribe_change_request",
|
||||
{
|
||||
title: "Watch change request",
|
||||
description:
|
||||
"Watch a pull request or merge request for check failures, passing checks, new comments, reviews, approvals, and closure. Returns the current state and sends future updates after your current turn.",
|
||||
"Watch a pull request for check failures, passing checks, new comments, reviews, and closure. Returns the current state and sends future updates after your current turn.",
|
||||
inputSchema,
|
||||
outputSchema: {
|
||||
url: z.string(),
|
||||
|
||||
@@ -132,9 +132,6 @@ export async function fanOutReconciledWorkspaceUpdates(input: {
|
||||
import { VoiceAssistantWebSocketServer, isDaemonOriginAllowed } from "./websocket-server.js";
|
||||
import { WorkspaceSetupRuntime } from "./workspace-setup-runtime.js";
|
||||
import { createWorkspaceLabelService } from "./workspace-labels/index.js";
|
||||
import { createChangeRequestRouter } from "../services/change-request-router.js";
|
||||
import { createForgeService } from "../services/forge-registry.js";
|
||||
import { createForgeResolver } from "../services/forge-resolver.js";
|
||||
import { createGitHubService } from "../services/github-service.js";
|
||||
import { createPaseoWorktree as createRegisteredPaseoWorktree } from "./paseo-worktree-service.js";
|
||||
import { createWorkspaceProvisioningService } from "./session/workspace-provisioning/workspace-provisioning-service.js";
|
||||
@@ -957,15 +954,12 @@ export async function createPaseoDaemon(
|
||||
workspaceRegistry,
|
||||
});
|
||||
const github = createGitHubService();
|
||||
const forgeResolver = createForgeResolver({
|
||||
createService: (forge) => (forge === "github" ? github : createForgeService(forge)),
|
||||
});
|
||||
const workspaceGitService = new WorkspaceGitServiceImpl({
|
||||
logger,
|
||||
paseoHome: config.paseoHome,
|
||||
worktreesRoot: config.worktreesRoot,
|
||||
deps: {
|
||||
forgeResolver,
|
||||
forgeOverrides: { github },
|
||||
},
|
||||
});
|
||||
const workspaceRuntimeStore = createWorkspaceRuntimeStore();
|
||||
@@ -1478,7 +1472,7 @@ export async function createPaseoDaemon(
|
||||
await scheduleService.start();
|
||||
|
||||
const changeRequestWatches = createChangeRequestWatches({
|
||||
router: createChangeRequestRouter({ forgeResolver }),
|
||||
source: github.changeRequests,
|
||||
backgroundWork: agentManager,
|
||||
paseoHome: config.paseoHome,
|
||||
logger,
|
||||
@@ -2062,7 +2056,6 @@ export async function createPaseoDaemon(
|
||||
if (wsServer) {
|
||||
await wsServer.close();
|
||||
}
|
||||
forgeResolver.dispose();
|
||||
await serviceProxy.stopStandalone();
|
||||
// Force-drop remaining sockets so httpServer.close() resolves promptly.
|
||||
// We've already closed wsServer (which sent ws-layer close frames) and
|
||||
|
||||
@@ -6,7 +6,12 @@ import { PassThrough } from "node:stream";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import pino from "pino";
|
||||
import type { ProviderEvent, ProviderRegistration } from "@getpaseo/plugin/server/provider";
|
||||
import {
|
||||
PROVIDER_CAPABILITIES,
|
||||
type ProviderEvent,
|
||||
type ProviderPrompt,
|
||||
type ProviderRegistration,
|
||||
} from "@getpaseo/plugin/server/provider";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import type { AgentStreamEvent } from "../agent/agent-sdk-types.js";
|
||||
import { PluginAgentClientRegistry } from "../agent/plugin-provider.js";
|
||||
@@ -358,6 +363,232 @@ register(${JSON.stringify(guardUrl)});`;
|
||||
await adapters.shutdown();
|
||||
await runtime.stopAll();
|
||||
});
|
||||
// The muse provider runs against a fake MSP host (injected through the
|
||||
// provider's command override), but everything above it is real: the plugin
|
||||
// subprocess, PluginRuntime's capability enforcement, and the
|
||||
// PluginAgentClientRegistry path an agent actually uses. On a muse build
|
||||
// that does not negotiate `session.subsession`, the daemon fails the whole
|
||||
// provider connection when the child is projected, so both tests fail
|
||||
// before the fix.
|
||||
async function startMuseRuntime() {
|
||||
const fakeMuse = fileURLToPath(
|
||||
new URL("../../../../../plugins/muse-provider/test/fake-muse.mjs", import.meta.url),
|
||||
);
|
||||
const directory = fileURLToPath(
|
||||
new URL("../../../../../plugins/muse-provider/", import.meta.url),
|
||||
);
|
||||
const runtime = createTestRuntime({}, undefined, "0.11.0");
|
||||
await runtime.startPlugin("muse-provider", directory);
|
||||
const [metadata] = runtime.getProviderRegistrations("muse-provider");
|
||||
expect(metadata).toBeDefined();
|
||||
return { runtime, metadata: metadata!, fakeMuse };
|
||||
}
|
||||
|
||||
async function startMuseClient(extraEnv: Record<string, string>) {
|
||||
const { runtime, metadata, fakeMuse } = await startMuseRuntime();
|
||||
const adapters = new PluginAgentClientRegistry(pino({ level: "silent" }));
|
||||
adapters.replace([
|
||||
{
|
||||
...adaptRuntimeProvider(runtime, "muse-provider", metadata),
|
||||
command: metadata.command,
|
||||
},
|
||||
]);
|
||||
const client = adapters.definitions()[metadata.id]!.createClient(pino({ level: "silent" }), {
|
||||
command: { mode: "replace", argv: [process.execPath, fakeMuse] },
|
||||
env: { MUSE_TEST_SCENARIO: "subagent", MUSE_TEST_CHILD: "tool", ...extraEnv },
|
||||
});
|
||||
return { runtime, adapters, client };
|
||||
}
|
||||
|
||||
function hasSettledTurn(events: readonly AgentStreamEvent[]): boolean {
|
||||
return events.some((event) => event.type === "turn_completed" || event.type === "turn_failed");
|
||||
}
|
||||
|
||||
// Asserting on the settled turn (rather than polling only for completion)
|
||||
// puts the provider's failure — e.g. "Provider parent session did not
|
||||
// negotiate session.subsession" — in the test output.
|
||||
async function expectTurnCompleted(events: readonly AgentStreamEvent[]): Promise<void> {
|
||||
await expect.poll(() => hasSettledTurn(events)).toBe(true);
|
||||
expect(events.filter((event) => event.type === "turn_failed")).toEqual([]);
|
||||
expect(hasCompletedAgentTurn(events)).toBe(true);
|
||||
}
|
||||
|
||||
function hasSubagentTimeline(events: readonly AgentStreamEvent[]): boolean {
|
||||
return events.some(
|
||||
(event) =>
|
||||
event.type === "provider_subagent" &&
|
||||
event.event.type === "timeline" &&
|
||||
event.event.item.type === "assistant_message" &&
|
||||
event.event.item.text.includes("SUBAGENT_PHASE0_OK"),
|
||||
);
|
||||
}
|
||||
|
||||
it("projects a muse subagent through PluginRuntime without failing the connection", async () => {
|
||||
const { runtime, adapters, client } = await startMuseClient({});
|
||||
try {
|
||||
const events: AgentStreamEvent[] = [];
|
||||
const session = await client.createSession({ provider: "muse", cwd: process.cwd() });
|
||||
session.subscribe((event) => events.push(event));
|
||||
await session.startTurn("dispatch a subagent", { clientMessageId: "muse-live" });
|
||||
await expectTurnCompleted(events);
|
||||
expect(hasSubagentTimeline(events)).toBe(true);
|
||||
// The connection survives: a fresh session on the same provider opens
|
||||
// and completes a turn instead of hitting a dead cached connection.
|
||||
const second = await client.createSession({ provider: "muse", cwd: process.cwd() });
|
||||
const secondEvents: AgentStreamEvent[] = [];
|
||||
second.subscribe((event) => secondEvents.push(event));
|
||||
await second.startTurn("again", { clientMessageId: "muse-live-2" });
|
||||
await expectTurnCompleted(secondEvents);
|
||||
await second.close();
|
||||
await session.close();
|
||||
} finally {
|
||||
await adapters.shutdown();
|
||||
await runtime.stopAll();
|
||||
}
|
||||
});
|
||||
|
||||
it("replays a muse subagent from history on resume without failing the connection", async () => {
|
||||
const historyDirectory = await mkdtemp(path.join(tmpdir(), "paseo-muse-history-"));
|
||||
temporaryDirectories.push(historyDirectory);
|
||||
const { runtime, adapters, client } = await startMuseClient({
|
||||
MUSE_TEST_HISTORY: path.join(historyDirectory, "native-history.ndjson"),
|
||||
});
|
||||
try {
|
||||
const first = await client.createSession({ provider: "muse", cwd: process.cwd() });
|
||||
const persistence = first.describePersistence();
|
||||
expect(persistence).not.toBeNull();
|
||||
await first.close();
|
||||
|
||||
// Seed old history without running a live subagent first, so this test
|
||||
// reaches resume even when live child projection is broken.
|
||||
await writeFile(
|
||||
path.join(historyDirectory, "native-history.ndjson"),
|
||||
JSON.stringify({
|
||||
itemId: "historical-subagent",
|
||||
revision: 1,
|
||||
kind: "toolCall",
|
||||
status: "completed",
|
||||
tool: "subagent_spawn",
|
||||
childSessionId: "fixture-child",
|
||||
}) + "\n",
|
||||
);
|
||||
const resumed = await client.resumeSession(persistence!, { cwd: process.cwd() });
|
||||
const resumedEvents: AgentStreamEvent[] = [];
|
||||
resumed.subscribe((event) => resumedEvents.push(event));
|
||||
// History replayed during resume is exposed through streamHistory.
|
||||
const replayed: AgentStreamEvent[] = [];
|
||||
for await (const event of resumed.streamHistory()) replayed.push(event);
|
||||
expect(hasSubagentTimeline(replayed)).toBe(true);
|
||||
await resumed.startTurn("continue", { clientMessageId: "muse-resumed" });
|
||||
await expectTurnCompleted(resumedEvents);
|
||||
await resumed.close();
|
||||
} finally {
|
||||
await adapters.shutdown();
|
||||
await runtime.stopAll();
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps other Muse sessions live when a parent closes during a child read", async () => {
|
||||
const directory = await mkdtemp(path.join(tmpdir(), "paseo-muse-child-read-"));
|
||||
temporaryDirectories.push(directory);
|
||||
const requests = path.join(directory, "requests.ndjson");
|
||||
const release = path.join(directory, "release");
|
||||
const { runtime, metadata, fakeMuse } = await startMuseRuntime();
|
||||
try {
|
||||
const connection = await runtime.connectProvider("muse-provider", metadata.id, {
|
||||
versions: [1],
|
||||
capabilities: PROVIDER_CAPABILITIES,
|
||||
launch: {
|
||||
command: process.execPath,
|
||||
args: [fakeMuse],
|
||||
env: {
|
||||
MUSE_TEST_SCENARIO: "subagent",
|
||||
MUSE_TEST_CHILD: "tool",
|
||||
MUSE_TEST_REQUESTS: requests,
|
||||
MUSE_TEST_CHILD_READ_RELEASE: release,
|
||||
},
|
||||
},
|
||||
});
|
||||
const events: ProviderEvent[] = [];
|
||||
connection.onEvent((event) => events.push(event));
|
||||
for (const sessionId of ["closing", "sibling"]) {
|
||||
await connection.send({
|
||||
type: "session.open",
|
||||
requestId: `open-${sessionId}`,
|
||||
sessionId,
|
||||
history: "skip",
|
||||
config: { cwd: process.cwd(), env: {}, mcpServers: {}, settings: {}, persist: true },
|
||||
});
|
||||
await expect
|
||||
.poll(() => events, { timeout: 5000 })
|
||||
.toContainEqual(expect.objectContaining({ type: "session.ready", sessionId }));
|
||||
}
|
||||
const prompt: ProviderPrompt = {
|
||||
clientMessageId: "spawn-child",
|
||||
delivery: "auto",
|
||||
input: { type: "message", content: [{ type: "text", text: "spawn a child" }] },
|
||||
};
|
||||
await connection.send({ type: "session.prompt", sessionId: "closing", prompt });
|
||||
await expect
|
||||
.poll(() => readFile(requests, "utf8"), { timeout: 5000 })
|
||||
.toContain('"method":"session/read"');
|
||||
|
||||
// send() resolves after the runtime has accepted the close and removed
|
||||
// the parent from its session table, while the child read is still pending.
|
||||
await connection.send({
|
||||
type: "session.close",
|
||||
requestId: "close-parent",
|
||||
sessionId: "closing",
|
||||
});
|
||||
await writeFile(release, "");
|
||||
|
||||
const closeSettled = (event: ProviderEvent) =>
|
||||
(event.type === "request.completed" && event.requestId === "close-parent") ||
|
||||
(event.type === "session.runtime_failed" && event.sessionId === "sibling");
|
||||
await expect.poll(() => events.some(closeSettled), { timeout: 5000 }).toBe(true);
|
||||
expect(
|
||||
events.filter(
|
||||
(event) => event.type === "session.runtime_failed" && event.sessionId === "sibling",
|
||||
),
|
||||
).toEqual([]);
|
||||
expect(events).toContainEqual({ type: "request.completed", requestId: "close-parent" });
|
||||
await connection.send({ type: "session.prompt", sessionId: "sibling", prompt });
|
||||
await expect
|
||||
.poll(() => events, { timeout: 5000 })
|
||||
.toContainEqual(
|
||||
expect.objectContaining({
|
||||
type: "session.turn",
|
||||
sessionId: "sibling",
|
||||
state: "completed",
|
||||
}),
|
||||
);
|
||||
} finally {
|
||||
await writeFile(release, "");
|
||||
await runtime.stopAll();
|
||||
}
|
||||
});
|
||||
|
||||
it("closes a Muse agent when the host exits without answering a child read", async () => {
|
||||
const directory = await mkdtemp(path.join(tmpdir(), "paseo-muse-close-"));
|
||||
temporaryDirectories.push(directory);
|
||||
const requests = path.join(directory, "requests.ndjson");
|
||||
const { runtime, adapters, client } = await startMuseClient({
|
||||
MUSE_TEST_HANG: "session/read",
|
||||
MUSE_TEST_REQUESTS: requests,
|
||||
});
|
||||
try {
|
||||
const session = await client.createSession({ provider: "muse", cwd: process.cwd() });
|
||||
await session.startTurn("spawn a child", { clientMessageId: "close-with-pending-read" });
|
||||
await expect
|
||||
.poll(() => readFile(requests, "utf8"), { timeout: 5000 })
|
||||
.toContain('"method":"session/read"');
|
||||
|
||||
await expect(session.close()).resolves.toBeUndefined();
|
||||
} finally {
|
||||
await adapters.shutdown();
|
||||
await runtime.stopAll();
|
||||
}
|
||||
});
|
||||
|
||||
it("runs a provider connection through the real plugin subprocess boundary", async () => {
|
||||
const directory = await createPlugin(
|
||||
|
||||
@@ -2404,46 +2404,6 @@ describe("WorkspaceGitServiceImpl with workspace folders that no longer exist",
|
||||
await service.dispose();
|
||||
});
|
||||
|
||||
test("a snapshot read during restoration waits for fresh checkout facts", async () => {
|
||||
const workspace = await createTemporaryFolder();
|
||||
const git = createFolderBackedGit();
|
||||
const started = createDeferred<void>();
|
||||
const release = createDeferred<void>();
|
||||
let holdRestoredRead = false;
|
||||
const service = createService({
|
||||
...git.deps,
|
||||
getCheckoutSnapshotFacts: async (cwd: string) => {
|
||||
if (holdRestoredRead) {
|
||||
started.resolve();
|
||||
await release.promise;
|
||||
}
|
||||
return git.deps.getCheckoutSnapshotFacts(cwd);
|
||||
},
|
||||
});
|
||||
const subscription = service.registerWorkspace({ cwd: workspace }, vi.fn());
|
||||
await waitForObservationToSettle(service, 1);
|
||||
await rm(workspace, { recursive: true, force: true });
|
||||
service.onWorkspaceStateMayHaveChanged(workspace);
|
||||
await vi.advanceTimersByTimeAsync(1_000);
|
||||
await waitForRefreshesToSettle(service);
|
||||
expect((await service.getSnapshot(workspace)).git.isGit).toBe(false);
|
||||
await advanceThroughDegradedPolls(service);
|
||||
await waitForObservationToSettle(service, 0);
|
||||
|
||||
await mkdir(workspace);
|
||||
holdRestoredRead = true;
|
||||
const restoringRead = service.getSnapshot(workspace);
|
||||
await started.promise;
|
||||
const concurrentRead = service.getSnapshot(workspace);
|
||||
release.resolve();
|
||||
|
||||
expect((await restoringRead).git.isGit).toBe(true);
|
||||
expect((await concurrentRead).git.isGit).toBe(true);
|
||||
|
||||
subscription.unsubscribe();
|
||||
await service.dispose();
|
||||
});
|
||||
|
||||
test("a resumed workspace rebuilds observation from fresh facts, not the non-git facts cached while its folder was gone", async () => {
|
||||
const workspace = await createTemporaryFolder();
|
||||
const git = createFolderBackedGit();
|
||||
|
||||
@@ -422,8 +422,6 @@ interface WorkspaceGitServiceDependencies {
|
||||
* fakes. Any forge not listed here is built (and cached once) by the registry.
|
||||
*/
|
||||
forgeOverrides?: Record<string, ForgeService>;
|
||||
/** Shared forge resolver when callers share adapter instances with other services. */
|
||||
forgeResolver?: ForgeResolver;
|
||||
/** Resolves an SSH config alias to its HostName; defaults to `ssh -G`. */
|
||||
resolveSshHostname?: SshHostnameResolver;
|
||||
resolveAbsoluteGitDir: (cwd: string) => Promise<string | null>;
|
||||
@@ -725,12 +723,10 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
|
||||
this.fileObserver.subscribe.bind(this.fileObserver),
|
||||
options.deps,
|
||||
);
|
||||
this.forgeResolver =
|
||||
this.deps.forgeResolver ??
|
||||
createForgeResolver({
|
||||
createService: (forge) => this.deps.forgeOverrides?.[forge] ?? createForgeService(forge),
|
||||
resolveSshHostname: this.deps.resolveSshHostname,
|
||||
});
|
||||
this.forgeResolver = createForgeResolver({
|
||||
createService: (forge) => this.deps.forgeOverrides?.[forge] ?? createForgeService(forge),
|
||||
resolveSshHostname: this.deps.resolveSshHostname,
|
||||
});
|
||||
}
|
||||
|
||||
resolveForge(cwd: string): Promise<ForgeResolution | null> {
|
||||
@@ -838,10 +834,9 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
|
||||
cwd = resolve(cwd);
|
||||
const request = this.normalizeRefreshRequest(options, "getSnapshot");
|
||||
const target = this.ensureWorkspaceTarget(cwd);
|
||||
// Restoration clears folderMissing before the fresh snapshot is ready.
|
||||
if (target.folderRestorePromise) {
|
||||
await target.folderRestorePromise;
|
||||
} else if (target.folderMissing) {
|
||||
// The snapshot cached while the folder was gone can say "not git". Resume
|
||||
// first, so a restored folder is read again instead of served from it.
|
||||
if (target.folderMissing) {
|
||||
await this.resumeWorkspaceIfFolderRestored(target);
|
||||
}
|
||||
if (!request.force && target.latestSnapshot) {
|
||||
|
||||
@@ -1,230 +0,0 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import type { ChangeRequestSnapshot } from "./change-request-source.js";
|
||||
import {
|
||||
ChangeRequestRateLimitError,
|
||||
createPerHostChangeRequestPoller,
|
||||
parseCliHttpResponse,
|
||||
parseRetryAfterMs,
|
||||
} from "./change-request-poller.js";
|
||||
|
||||
const sampleSnapshot: ChangeRequestSnapshot = {
|
||||
state: "open",
|
||||
headSha: "abc123",
|
||||
checksState: "passed",
|
||||
checks: [],
|
||||
reviewDecision: null,
|
||||
activity: [],
|
||||
};
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
describe("parseCliHttpResponse", () => {
|
||||
it("parses status line, mixed line endings, redirect blocks, and JSON body", () => {
|
||||
const raw = [
|
||||
"HTTP/1.1 100 Continue\r\n\r\n",
|
||||
"HTTP/2.0 200 OK\n",
|
||||
"Content-Type: application/json\r\n",
|
||||
"X-Next-Page: 2\r\n",
|
||||
"Ratelimit-Remaining: 95\r\n",
|
||||
"Ratelimit-Reset: 1700000120\r\n",
|
||||
"\r\n",
|
||||
'{"ok":true}',
|
||||
].join("");
|
||||
const parsed = parseCliHttpResponse(raw);
|
||||
expect(parsed.status).toBe(200);
|
||||
expect(parsed.headers.get("x-next-page")).toBe("2");
|
||||
expect(parsed.headers.get("ratelimit-remaining")).toBe("95");
|
||||
expect(parsed.body).toBe('{"ok":true}');
|
||||
});
|
||||
|
||||
it("returns null status and raw body when headers are absent", () => {
|
||||
const parsed = parseCliHttpResponse('{"ok":true}');
|
||||
expect(parsed.status).toBeNull();
|
||||
expect(parsed.headers.size).toBe(0);
|
||||
expect(parsed.body).toBe('{"ok":true}');
|
||||
});
|
||||
});
|
||||
|
||||
describe("parseRetryAfterMs", () => {
|
||||
it("parses Retry-After seconds and exhausted Ratelimit-Reset headers", () => {
|
||||
const now = 1_700_000_000_000;
|
||||
expect(parseRetryAfterMs(new Map([["retry-after", "45"]]), now)).toBe(now + 45_000);
|
||||
expect(
|
||||
parseRetryAfterMs(
|
||||
new Map([
|
||||
["ratelimit-remaining", "0"],
|
||||
["ratelimit-reset", "1700000060"],
|
||||
]),
|
||||
now,
|
||||
),
|
||||
).toBe(1_700_000_060_000);
|
||||
expect(
|
||||
parseRetryAfterMs(
|
||||
new Map([
|
||||
["ratelimit-remaining", "50"],
|
||||
["ratelimit-reset", "1700000060"],
|
||||
]),
|
||||
now,
|
||||
),
|
||||
).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("createPerHostChangeRequestPoller", () => {
|
||||
it("bounds concurrent reads per host and drains waiting watches as slots free", async () => {
|
||||
vi.useFakeTimers();
|
||||
let active = 0;
|
||||
let maxActive = 0;
|
||||
const resolvers = new Map<string, () => void>();
|
||||
const poller = createPerHostChangeRequestPoller({
|
||||
hostOf: (url) => new URL(url).hostname,
|
||||
maxConcurrencyPerHost: 2,
|
||||
pollIntervalMs: 20_000,
|
||||
async read({ url }) {
|
||||
active += 1;
|
||||
maxActive = Math.max(maxActive, active);
|
||||
await new Promise<void>((resolve) => {
|
||||
resolvers.set(url, resolve);
|
||||
});
|
||||
active -= 1;
|
||||
return sampleSnapshot;
|
||||
},
|
||||
});
|
||||
const received: string[] = [];
|
||||
try {
|
||||
for (const n of [1, 2, 3]) {
|
||||
const url = `https://gitlab.com/org/repo/-/merge_requests/${n}`;
|
||||
poller.observe(url, {
|
||||
async snapshot() {
|
||||
received.push(url);
|
||||
},
|
||||
error(error) {
|
||||
throw error;
|
||||
},
|
||||
});
|
||||
}
|
||||
await vi.advanceTimersByTimeAsync(25);
|
||||
expect(maxActive).toBe(2);
|
||||
expect(resolvers.size).toBe(2);
|
||||
|
||||
resolvers.get("https://gitlab.com/org/repo/-/merge_requests/1")?.();
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
expect(maxActive).toBe(2);
|
||||
expect(resolvers.has("https://gitlab.com/org/repo/-/merge_requests/3")).toBe(true);
|
||||
|
||||
resolvers.get("https://gitlab.com/org/repo/-/merge_requests/2")?.();
|
||||
resolvers.get("https://gitlab.com/org/repo/-/merge_requests/3")?.();
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
expect(received).toHaveLength(3);
|
||||
} finally {
|
||||
poller.dispose();
|
||||
}
|
||||
});
|
||||
|
||||
it("backs off exponentially on transient errors and resets after a successful poll", async () => {
|
||||
vi.useFakeTimers();
|
||||
let calls = 0;
|
||||
let shouldFail = true;
|
||||
const poller = createPerHostChangeRequestPoller({
|
||||
hostOf: (url) => new URL(url).hostname,
|
||||
pollIntervalMs: 10_000,
|
||||
maxErrorBackoffMs: 40_000,
|
||||
async read() {
|
||||
calls += 1;
|
||||
if (shouldFail) throw new Error(`fail ${calls}`);
|
||||
return sampleSnapshot;
|
||||
},
|
||||
});
|
||||
const errors: unknown[] = [];
|
||||
const snapshots: ChangeRequestSnapshot[] = [];
|
||||
try {
|
||||
poller.observe("https://gitlab.com/org/repo/-/merge_requests/1", {
|
||||
async snapshot(s) {
|
||||
snapshots.push(s);
|
||||
},
|
||||
error(err) {
|
||||
errors.push(err);
|
||||
},
|
||||
});
|
||||
await vi.advanceTimersByTimeAsync(25);
|
||||
expect(calls).toBe(1);
|
||||
expect(errors).toHaveLength(1);
|
||||
|
||||
// 1st failure -> 10s backoff
|
||||
await vi.advanceTimersByTimeAsync(9_999);
|
||||
expect(calls).toBe(1);
|
||||
await vi.advanceTimersByTimeAsync(1);
|
||||
expect(calls).toBe(2);
|
||||
|
||||
// 2nd failure -> 20s backoff
|
||||
await vi.advanceTimersByTimeAsync(19_999);
|
||||
expect(calls).toBe(2);
|
||||
shouldFail = false;
|
||||
await vi.advanceTimersByTimeAsync(1);
|
||||
expect(calls).toBe(3);
|
||||
expect(snapshots).toHaveLength(1);
|
||||
|
||||
// Reset to 10s base interval after success
|
||||
await vi.advanceTimersByTimeAsync(10_000);
|
||||
expect(calls).toBe(4);
|
||||
} finally {
|
||||
poller.dispose();
|
||||
}
|
||||
});
|
||||
|
||||
it("pauses all watches on a rate-limited host until resetAt and fast-fails new observers", async () => {
|
||||
vi.useFakeTimers();
|
||||
vi.setSystemTime(1_700_000_000_000);
|
||||
let calls = 0;
|
||||
const poller = createPerHostChangeRequestPoller({
|
||||
hostOf: (url) => new URL(url).hostname,
|
||||
pollIntervalMs: 10_000,
|
||||
async read() {
|
||||
calls += 1;
|
||||
if (calls === 1) {
|
||||
throw new ChangeRequestRateLimitError({
|
||||
host: "gitlab.com",
|
||||
resetAtMs: Date.now() + 60_000,
|
||||
});
|
||||
}
|
||||
return sampleSnapshot;
|
||||
},
|
||||
});
|
||||
const errors1: unknown[] = [];
|
||||
const errors2: unknown[] = [];
|
||||
const snapshots2: ChangeRequestSnapshot[] = [];
|
||||
try {
|
||||
poller.observe("https://gitlab.com/org/repo/-/merge_requests/1", {
|
||||
async snapshot() {},
|
||||
error(err) {
|
||||
errors1.push(err);
|
||||
},
|
||||
});
|
||||
await vi.advanceTimersByTimeAsync(25);
|
||||
expect(calls).toBe(1);
|
||||
expect(errors1[0]).toBeInstanceOf(ChangeRequestRateLimitError);
|
||||
|
||||
poller.observe("https://gitlab.com/org/repo/-/merge_requests/2", {
|
||||
async snapshot(s) {
|
||||
snapshots2.push(s);
|
||||
},
|
||||
error(err) {
|
||||
errors2.push(err);
|
||||
},
|
||||
});
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
expect(errors2[0]).toBeInstanceOf(ChangeRequestRateLimitError);
|
||||
|
||||
await vi.advanceTimersByTimeAsync(59_999);
|
||||
expect(calls).toBe(1);
|
||||
|
||||
await vi.advanceTimersByTimeAsync(1);
|
||||
expect(calls).toBe(3);
|
||||
expect(snapshots2).toHaveLength(1);
|
||||
} finally {
|
||||
poller.dispose();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,362 +0,0 @@
|
||||
import type { ChangeRequestSnapshot, ChangeRequestSource } from "./change-request-source.js";
|
||||
|
||||
const DEFAULT_INITIAL_DELAY_MS = 25;
|
||||
const DEFAULT_POLL_INTERVAL_MS = 20_000;
|
||||
const DEFAULT_MAX_ERROR_BACKOFF_MS = 300_000;
|
||||
const DEFAULT_MAX_CONCURRENCY_PER_HOST = 2;
|
||||
const MIN_RATE_LIMIT_PAUSE_MS = 1_000;
|
||||
const MAX_RATE_LIMIT_PAUSE_MS = 15 * 60_000;
|
||||
|
||||
export interface ParsedCliHttpResponse {
|
||||
status: number | null;
|
||||
headers: Map<string, string>;
|
||||
body: string;
|
||||
}
|
||||
|
||||
const HTTP_STATUS_PREFIX = /^HTTP\/\d(?:\.\d)?\s+(\d{3})[^\r\n]*\r?\n/;
|
||||
const HEADER_BODY_SEPARATOR = /\r?\n\r?\n/;
|
||||
|
||||
/**
|
||||
* Parse output from CLI API commands invoked with `-i` / `--include`.
|
||||
* Consumes multiple leading HTTP response blocks (e.g. `100 Continue` or
|
||||
* redirect headers) and returns the final status code, lowercased headers,
|
||||
* and response body. Returns `status: null` when no HTTP header block is
|
||||
* present.
|
||||
*/
|
||||
export function parseCliHttpResponse(raw: string): ParsedCliHttpResponse {
|
||||
let remaining = raw.trimStart();
|
||||
let status: number | null = null;
|
||||
let headers = new Map<string, string>();
|
||||
|
||||
while (true) {
|
||||
const statusMatch = HTTP_STATUS_PREFIX.exec(remaining);
|
||||
if (!statusMatch) {
|
||||
break;
|
||||
}
|
||||
const separatorMatch = HEADER_BODY_SEPARATOR.exec(remaining);
|
||||
if (!separatorMatch) {
|
||||
status = Number(statusMatch[1]);
|
||||
headers = parseHeaderLines(remaining.slice(statusMatch[0].length));
|
||||
remaining = "";
|
||||
break;
|
||||
}
|
||||
status = Number(statusMatch[1]);
|
||||
const headerBlock = remaining.slice(statusMatch[0].length, separatorMatch.index);
|
||||
headers = parseHeaderLines(headerBlock);
|
||||
remaining = remaining.slice(separatorMatch.index + separatorMatch[0].length);
|
||||
}
|
||||
|
||||
return { status, headers, body: remaining.trim() };
|
||||
}
|
||||
|
||||
function parseHeaderLines(block: string): Map<string, string> {
|
||||
const headers = new Map<string, string>();
|
||||
for (const line of block.split(/\r?\n/)) {
|
||||
const colon = line.indexOf(":");
|
||||
if (colon <= 0) continue;
|
||||
const name = line.slice(0, colon).trim().toLowerCase();
|
||||
const value = line.slice(colon + 1).trim();
|
||||
if (!name) continue;
|
||||
const existing = headers.get(name);
|
||||
headers.set(name, existing ? `${existing}, ${value}` : value);
|
||||
}
|
||||
return headers;
|
||||
}
|
||||
|
||||
function clampPauseUntil(targetMs: number, nowMs: number): number {
|
||||
return Math.min(
|
||||
Math.max(targetMs, nowMs + MIN_RATE_LIMIT_PAUSE_MS),
|
||||
nowMs + MAX_RATE_LIMIT_PAUSE_MS,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract the timestamp (epoch ms) until which a host should pause polling
|
||||
* based on `Retry-After` or exhausted `Ratelimit-Remaining` / `Ratelimit-Reset`
|
||||
* headers. Returns null when no pause is signaled.
|
||||
*/
|
||||
export function parseRetryAfterMs(
|
||||
headers: ReadonlyMap<string, string>,
|
||||
nowMs: number,
|
||||
options: { forceOnMissing?: boolean; defaultPauseMs?: number } = {},
|
||||
): number | null {
|
||||
const retryAfter = headers.get("retry-after");
|
||||
if (retryAfter) {
|
||||
const seconds = Number(retryAfter);
|
||||
if (Number.isFinite(seconds) && seconds >= 0) {
|
||||
return clampPauseUntil(nowMs + Math.ceil(seconds * 1_000), nowMs);
|
||||
}
|
||||
const parsedDate = Date.parse(retryAfter);
|
||||
if (Number.isFinite(parsedDate)) {
|
||||
return clampPauseUntil(parsedDate, nowMs);
|
||||
}
|
||||
}
|
||||
|
||||
const remainingRaw = headers.get("ratelimit-remaining") ?? headers.get("x-ratelimit-remaining");
|
||||
const resetRaw = headers.get("ratelimit-reset") ?? headers.get("x-ratelimit-reset");
|
||||
const remaining = remainingRaw !== undefined ? Number(remainingRaw) : Number.NaN;
|
||||
const resetSec = resetRaw !== undefined ? Number(resetRaw) : Number.NaN;
|
||||
if (
|
||||
(options.forceOnMissing || (Number.isFinite(remaining) && remaining <= 1)) &&
|
||||
Number.isFinite(resetSec) &&
|
||||
resetSec > 0
|
||||
) {
|
||||
return clampPauseUntil(resetSec * 1_000, nowMs);
|
||||
}
|
||||
|
||||
if (options.forceOnMissing) {
|
||||
return clampPauseUntil(nowMs + (options.defaultPauseMs ?? 60_000), nowMs);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export class ChangeRequestRateLimitError extends Error {
|
||||
readonly host: string;
|
||||
readonly resetAtMs: number;
|
||||
|
||||
constructor(params: { host: string; resetAtMs: number; message?: string }) {
|
||||
super(
|
||||
params.message ??
|
||||
`Change request polling for ${params.host} is rate-limited until ${new Date(params.resetAtMs).toISOString()}`,
|
||||
);
|
||||
this.name = "ChangeRequestRateLimitError";
|
||||
this.host = params.host;
|
||||
this.resetAtMs = params.resetAtMs;
|
||||
}
|
||||
}
|
||||
|
||||
export interface PerHostReadContext {
|
||||
url: string;
|
||||
host: string;
|
||||
knownActivity(): ReadonlySet<string> | undefined;
|
||||
isObserved(): boolean;
|
||||
assertHostAvailable(): void;
|
||||
deferPollsUntil(untilMs: number): void;
|
||||
pauseHost(untilMs: number): void;
|
||||
}
|
||||
|
||||
export interface PerHostChangeRequestPollerOptions {
|
||||
hostOf(url: string): string;
|
||||
read(context: PerHostReadContext): Promise<ChangeRequestSnapshot>;
|
||||
now?: () => number;
|
||||
initialDelayMs?: number;
|
||||
pollIntervalMs?: number;
|
||||
maxErrorBackoffMs?: number;
|
||||
maxConcurrencyPerHost?: number;
|
||||
onError?(error: unknown, host: string): void;
|
||||
}
|
||||
|
||||
interface WatchedEntry {
|
||||
url: string;
|
||||
host: string;
|
||||
callbacks: Parameters<ChangeRequestSource["observe"]>[1];
|
||||
nextDueAt: number;
|
||||
consecutiveErrors: number;
|
||||
inFlight: boolean;
|
||||
}
|
||||
|
||||
export interface PerHostChangeRequestPoller {
|
||||
observe: ChangeRequestSource["observe"];
|
||||
dispose(): void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Bounded per-host polling loop shared by REST-backed forge watch adapters.
|
||||
* Limits concurrent reads per host, applies exponential backoff on transient
|
||||
* failures, and pauses all watches for a host when rate-limited.
|
||||
*/
|
||||
export function createPerHostChangeRequestPoller(
|
||||
options: PerHostChangeRequestPollerOptions,
|
||||
): PerHostChangeRequestPoller {
|
||||
const now = options.now ?? Date.now;
|
||||
const initialDelayMs = options.initialDelayMs ?? DEFAULT_INITIAL_DELAY_MS;
|
||||
const pollIntervalMs = options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
|
||||
const maxErrorBackoffMs = options.maxErrorBackoffMs ?? DEFAULT_MAX_ERROR_BACKOFF_MS;
|
||||
const maxConcurrencyPerHost = options.maxConcurrencyPerHost ?? DEFAULT_MAX_CONCURRENCY_PER_HOST;
|
||||
|
||||
const watches = new Map<string, WatchedEntry>();
|
||||
const inFlightByHost = new Map<string, number>();
|
||||
const pausesByHost = new Map<string, { pollsUntil: number; requestsUntil: number }>();
|
||||
let timer: NodeJS.Timeout | null = null;
|
||||
let disposed = false;
|
||||
|
||||
function clearTimer(): void {
|
||||
if (timer) {
|
||||
clearTimeout(timer);
|
||||
timer = null;
|
||||
}
|
||||
}
|
||||
|
||||
function deferHost(host: string, untilMs: number, blockRequests: boolean): void {
|
||||
const current = pausesByHost.get(host) ?? { pollsUntil: 0, requestsUntil: 0 };
|
||||
pausesByHost.set(host, {
|
||||
pollsUntil: Math.max(current.pollsUntil, untilMs),
|
||||
requestsUntil: blockRequests
|
||||
? Math.max(current.requestsUntil, untilMs)
|
||||
: current.requestsUntil,
|
||||
});
|
||||
}
|
||||
|
||||
function hostPauseUntil(host: string, nowMs: number): number {
|
||||
const pause = pausesByHost.get(host);
|
||||
if (!pause) return 0;
|
||||
if (pause.pollsUntil > nowMs) return pause.pollsUntil;
|
||||
if (!pause.requestsUntil) pausesByHost.delete(host);
|
||||
return 0;
|
||||
}
|
||||
|
||||
function pollLimit(host: string): number {
|
||||
// After a 429, admit one poll until it has delivered a full snapshot.
|
||||
// This lets it use the reset quota without competing with another poll.
|
||||
return pausesByHost.get(host)?.requestsUntil ? 1 : maxConcurrencyPerHost;
|
||||
}
|
||||
|
||||
function armTimer(): void {
|
||||
clearTimer();
|
||||
if (disposed || watches.size === 0) return;
|
||||
|
||||
const nowMs = now();
|
||||
let earliestDue = Number.POSITIVE_INFINITY;
|
||||
for (const watch of watches.values()) {
|
||||
if (watch.inFlight) continue;
|
||||
if ((inFlightByHost.get(watch.host) ?? 0) >= pollLimit(watch.host)) continue;
|
||||
const dueAt = Math.max(watch.nextDueAt, hostPauseUntil(watch.host, nowMs));
|
||||
if (dueAt < earliestDue) {
|
||||
earliestDue = dueAt;
|
||||
}
|
||||
}
|
||||
if (!Number.isFinite(earliestDue)) return;
|
||||
|
||||
const delay = Math.max(0, earliestDue - nowMs);
|
||||
timer = setTimeout(() => {
|
||||
timer = null;
|
||||
drainDueWatches();
|
||||
}, delay);
|
||||
timer.unref();
|
||||
}
|
||||
|
||||
function drainDueWatches(): void {
|
||||
if (disposed) return;
|
||||
const nowMs = now();
|
||||
for (const watch of watches.values()) {
|
||||
if (watch.inFlight) continue;
|
||||
const inFlightCount = inFlightByHost.get(watch.host) ?? 0;
|
||||
if (inFlightCount >= pollLimit(watch.host)) continue;
|
||||
const dueAt = Math.max(watch.nextDueAt, hostPauseUntil(watch.host, nowMs));
|
||||
if (dueAt > nowMs) continue;
|
||||
startPoll(watch);
|
||||
}
|
||||
armTimer();
|
||||
}
|
||||
|
||||
function startPoll(watch: WatchedEntry): void {
|
||||
watch.inFlight = true;
|
||||
inFlightByHost.set(watch.host, (inFlightByHost.get(watch.host) ?? 0) + 1);
|
||||
const isObserved = () => !disposed && watches.get(watch.url) === watch;
|
||||
const recovering = Boolean(pausesByHost.get(watch.host)?.requestsUntil);
|
||||
let completed = false;
|
||||
|
||||
void (async () => {
|
||||
try {
|
||||
const snapshot = await options.read({
|
||||
url: watch.url,
|
||||
host: watch.host,
|
||||
knownActivity: () => watch.callbacks.knownActivity?.(),
|
||||
isObserved,
|
||||
assertHostAvailable() {
|
||||
const nowMs = now();
|
||||
const resetAtMs = pausesByHost.get(watch.host)?.requestsUntil ?? 0;
|
||||
if (resetAtMs > nowMs) {
|
||||
throw new ChangeRequestRateLimitError({ host: watch.host, resetAtMs });
|
||||
}
|
||||
},
|
||||
deferPollsUntil: (untilMs) => deferHost(watch.host, untilMs, false),
|
||||
pauseHost: (untilMs) => deferHost(watch.host, untilMs, true),
|
||||
});
|
||||
if (!isObserved()) return;
|
||||
watch.consecutiveErrors = 0;
|
||||
await watch.callbacks.snapshot(snapshot);
|
||||
if (!isObserved()) return;
|
||||
const nowMs = now();
|
||||
const pause = pausesByHost.get(watch.host);
|
||||
if (pause && pause.requestsUntil <= nowMs) pause.requestsUntil = 0;
|
||||
watch.nextDueAt = Math.max(nowMs + pollIntervalMs, hostPauseUntil(watch.host, nowMs));
|
||||
completed = true;
|
||||
} catch (error) {
|
||||
if (!isObserved()) return;
|
||||
options.onError?.(error, watch.host);
|
||||
const nowMs = now();
|
||||
if (error instanceof ChangeRequestRateLimitError) {
|
||||
deferHost(watch.host, error.resetAtMs, true);
|
||||
watch.nextDueAt = Math.max(nowMs + pollIntervalMs, error.resetAtMs);
|
||||
} else {
|
||||
watch.consecutiveErrors += 1;
|
||||
const backoff = Math.min(
|
||||
pollIntervalMs * 2 ** (watch.consecutiveErrors - 1),
|
||||
maxErrorBackoffMs,
|
||||
);
|
||||
watch.nextDueAt = nowMs + backoff;
|
||||
}
|
||||
watch.callbacks.error(error);
|
||||
} finally {
|
||||
// Rotate after a snapshot or a recovery attempt so a watch that
|
||||
// keeps failing cannot take every turn after a quota reset.
|
||||
if ((completed || recovering) && isObserved()) {
|
||||
watches.delete(watch.url);
|
||||
watches.set(watch.url, watch);
|
||||
}
|
||||
watch.inFlight = false;
|
||||
const remaining = (inFlightByHost.get(watch.host) ?? 1) - 1;
|
||||
if (remaining > 0) inFlightByHost.set(watch.host, remaining);
|
||||
else inFlightByHost.delete(watch.host);
|
||||
if (!disposed) {
|
||||
// Immediately admit any queued due watch on this host, then re-arm timer.
|
||||
drainDueWatches();
|
||||
}
|
||||
}
|
||||
})();
|
||||
}
|
||||
|
||||
return {
|
||||
observe(url, callbacks) {
|
||||
if (disposed) {
|
||||
queueMicrotask(() => callbacks.error(new Error("Change request poller is disposed")));
|
||||
return () => {};
|
||||
}
|
||||
const host = options.hostOf(url);
|
||||
const nowMs = now();
|
||||
const watch: WatchedEntry = {
|
||||
url,
|
||||
host,
|
||||
callbacks,
|
||||
nextDueAt: nowMs + initialDelayMs,
|
||||
consecutiveErrors: 0,
|
||||
inFlight: false,
|
||||
};
|
||||
watches.set(url, watch);
|
||||
const pauseUntil = hostPauseUntil(host, nowMs);
|
||||
if (pauseUntil > nowMs) {
|
||||
queueMicrotask(() => {
|
||||
if (!disposed && watches.get(url) === watch) {
|
||||
callbacks.error(new ChangeRequestRateLimitError({ host, resetAtMs: pauseUntil }));
|
||||
}
|
||||
});
|
||||
}
|
||||
armTimer();
|
||||
return () => {
|
||||
if (watches.get(url) === watch) {
|
||||
watches.delete(url);
|
||||
armTimer();
|
||||
}
|
||||
};
|
||||
},
|
||||
|
||||
dispose() {
|
||||
disposed = true;
|
||||
clearTimer();
|
||||
watches.clear();
|
||||
inFlightByHost.clear();
|
||||
pausesByHost.clear();
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -1,120 +0,0 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { createChangeRequestRouter } from "./change-request-router.js";
|
||||
import type { ChangeRequestSource } from "./change-request-source.js";
|
||||
import { createForgeResolver } from "./forge-resolver.js";
|
||||
import type { ForgeService } from "./forge-service.js";
|
||||
|
||||
function createFakeSource(
|
||||
forge: string,
|
||||
canonicalize: (url: string) => string,
|
||||
): ChangeRequestSource {
|
||||
return {
|
||||
resolve: canonicalize,
|
||||
describe: (url) => `${forge}:${url}`,
|
||||
observe: () => () => {},
|
||||
};
|
||||
}
|
||||
|
||||
function createFakeForgeService(changeRequests?: ChangeRequestSource): ForgeService {
|
||||
return {
|
||||
...(changeRequests ? { changeRequests } : {}),
|
||||
invalidate() {},
|
||||
} as unknown as ForgeService;
|
||||
}
|
||||
|
||||
describe("createChangeRequestRouter", () => {
|
||||
it("routes cloud hosts without probing and delegates canonicalization to the matched forge", async () => {
|
||||
const probeForge = vi.fn(async () => {
|
||||
throw new Error("cloud host must not trigger a probe");
|
||||
});
|
||||
const githubSource = createFakeSource(
|
||||
"github",
|
||||
(url) => `https://github.com/canonical/${new URL(url).pathname.split("/").at(-1)}`,
|
||||
);
|
||||
const gitlabSource = createFakeSource(
|
||||
"gitlab",
|
||||
(url) => `https://gitlab.com/canonical/${new URL(url).pathname.split("/").at(-1)}`,
|
||||
);
|
||||
const resolver = createForgeResolver({
|
||||
probeForge,
|
||||
createService: (forge) => {
|
||||
if (forge === "github") return createFakeForgeService(githubSource);
|
||||
if (forge === "gitlab") return createFakeForgeService(gitlabSource);
|
||||
return null;
|
||||
},
|
||||
});
|
||||
const router = createChangeRequestRouter({ forgeResolver: resolver });
|
||||
|
||||
await expect(router.resolve("https://GitHub.com/Org/Repo/pull/7")).resolves.toEqual({
|
||||
forge: "github",
|
||||
url: "https://github.com/canonical/7",
|
||||
});
|
||||
await expect(
|
||||
router.resolve("https://gitlab.com/org/sub/repo/-/merge_requests/12"),
|
||||
).resolves.toEqual({
|
||||
forge: "gitlab",
|
||||
url: "https://gitlab.com/canonical/12",
|
||||
});
|
||||
expect(probeForge).not.toHaveBeenCalled();
|
||||
expect(router.source("github")).toBe(githubSource);
|
||||
expect(router.source("gitlab")).toBe(gitlabSource);
|
||||
});
|
||||
|
||||
it("probes self-hosted hosts before parsing the URL path", async () => {
|
||||
const probeForge = vi.fn(async (host: string) =>
|
||||
host === "git.corp.internal" ? "gitlab" : null,
|
||||
);
|
||||
const gitlabResolve = vi.fn(() => "https://git.corp.internal/team/app/-/merge_requests/9");
|
||||
const githubResolve = vi.fn(() => {
|
||||
throw new Error("github must not parse a gitlab host");
|
||||
});
|
||||
const resolver = createForgeResolver({
|
||||
probeForge,
|
||||
createService: (forge) => {
|
||||
if (forge === "github")
|
||||
return createFakeForgeService(createFakeSource("github", githubResolve));
|
||||
if (forge === "gitlab")
|
||||
return createFakeForgeService(createFakeSource("gitlab", gitlabResolve));
|
||||
return null;
|
||||
},
|
||||
});
|
||||
const router = createChangeRequestRouter({ forgeResolver: resolver });
|
||||
|
||||
await expect(
|
||||
router.resolve("https://git.corp.internal/team/app/-/merge_requests/9"),
|
||||
).resolves.toEqual({
|
||||
forge: "gitlab",
|
||||
url: "https://git.corp.internal/team/app/-/merge_requests/9",
|
||||
});
|
||||
expect(probeForge).toHaveBeenCalledWith("git.corp.internal");
|
||||
expect(gitlabResolve).toHaveBeenCalledTimes(1);
|
||||
expect(githubResolve).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects unrecognized hosts, credentials, non-http schemes, and forges without watch support", async () => {
|
||||
const resolver = createForgeResolver({
|
||||
probeForge: async () => null,
|
||||
createService: (forge) => {
|
||||
if (forge === "gitea") return createFakeForgeService();
|
||||
return null;
|
||||
},
|
||||
});
|
||||
const router = createChangeRequestRouter({ forgeResolver: resolver });
|
||||
|
||||
await expect(router.resolve("not a url")).rejects.toThrow(/change request URL/i);
|
||||
await expect(router.resolve("ftp://github.com/org/repo/pull/1")).rejects.toThrow(
|
||||
/change request URL/i,
|
||||
);
|
||||
await expect(router.resolve("https://user:pass@github.com/org/repo/pull/1")).rejects.toThrow(
|
||||
/change request URL/i,
|
||||
);
|
||||
await expect(router.resolve("https://unknown.example.com/org/repo/pull/1")).rejects.toThrow(
|
||||
/unknown\.example\.com/,
|
||||
);
|
||||
await expect(router.resolve("https://gitea.com/org/repo/pulls/1")).rejects.toThrow(
|
||||
/not supported.*gitea/i,
|
||||
);
|
||||
expect(router.source("gitea")).toBeNull();
|
||||
expect(router.source("unknown")).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -1,80 +0,0 @@
|
||||
import { normalizeHost } from "@getpaseo/protocol/git-remote";
|
||||
import type { ChangeRequestSource } from "./change-request-source.js";
|
||||
import type { ForgeResolver } from "./forge-resolver.js";
|
||||
|
||||
export interface ResolvedChangeRequest {
|
||||
forge: string;
|
||||
url: string;
|
||||
}
|
||||
|
||||
export interface ChangeRequestRouter {
|
||||
/** Route a user-supplied URL host-first through registered forges and canonicalize it. */
|
||||
resolve(url: string): Promise<ResolvedChangeRequest>;
|
||||
/** Return the watch source for a known forge id without probing the network. */
|
||||
source(forge: string): ChangeRequestSource | null;
|
||||
}
|
||||
|
||||
export interface CreateChangeRequestRouterOptions {
|
||||
forgeResolver: Pick<ForgeResolver, "resolveHost" | "getService">;
|
||||
}
|
||||
|
||||
function extractUrlHost(input: string): { trimmed: string; host: string; authority: string } {
|
||||
const trimmed = input.trim();
|
||||
if (!trimmed || /\s/.test(trimmed)) {
|
||||
throw new Error("Enter a supported change request URL.");
|
||||
}
|
||||
let parsed: URL;
|
||||
try {
|
||||
parsed = new URL(trimmed);
|
||||
} catch {
|
||||
throw new Error("Enter a supported change request URL.");
|
||||
}
|
||||
if (
|
||||
(parsed.protocol !== "https:" && parsed.protocol !== "http:") ||
|
||||
parsed.username ||
|
||||
parsed.password
|
||||
) {
|
||||
throw new Error("Enter a supported change request URL.");
|
||||
}
|
||||
const host = normalizeHost(parsed.hostname);
|
||||
if (!host) {
|
||||
throw new Error("Enter a supported change request URL.");
|
||||
}
|
||||
return { trimmed, host, authority: parsed.port ? `${host}:${parsed.port}` : host };
|
||||
}
|
||||
|
||||
/**
|
||||
* Host-first router for change request watches. Resolves the target forge from
|
||||
* the URL host via ForgeResolver (cloud match first, then cached CLI auth
|
||||
* probe) before delegating path parsing and canonicalization to that forge's
|
||||
* ChangeRequestSource.
|
||||
*/
|
||||
export function createChangeRequestRouter({
|
||||
forgeResolver,
|
||||
}: CreateChangeRequestRouterOptions): ChangeRequestRouter {
|
||||
return {
|
||||
async resolve(input: string): Promise<ResolvedChangeRequest> {
|
||||
const { trimmed, host, authority } = extractUrlHost(input);
|
||||
const resolution =
|
||||
(await forgeResolver.resolveHost(authority)) ??
|
||||
(authority === host ? null : await forgeResolver.resolveHost(host));
|
||||
if (!resolution) {
|
||||
throw new Error(
|
||||
`Could not recognize a supported forge for host ${host}. Authenticate the forge CLI for this host first.`,
|
||||
);
|
||||
}
|
||||
const source = resolution.service.changeRequests;
|
||||
if (!source) {
|
||||
throw new Error(`Change request watches are not supported for ${resolution.forge} yet.`);
|
||||
}
|
||||
return {
|
||||
forge: resolution.forge,
|
||||
url: source.resolve(trimmed),
|
||||
};
|
||||
},
|
||||
|
||||
source(forge: string): ChangeRequestSource | null {
|
||||
return forgeResolver.getService(forge)?.changeRequests ?? null;
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -17,9 +17,8 @@ const changeRequestSnapshotSchema = changeRequestStatusSchema.extend({
|
||||
activity: z.array(
|
||||
z.object({
|
||||
id: z.string(),
|
||||
kind: z.enum(["comment", "inline comment", "review", "approval"]),
|
||||
kind: z.enum(["comment", "inline comment", "review"]),
|
||||
url: z.string(),
|
||||
message: z.string().optional(),
|
||||
}),
|
||||
),
|
||||
});
|
||||
|
||||
@@ -373,40 +373,4 @@ describe("createForgeResolver", () => {
|
||||
expect(b).toMatchObject({ forge: "gitlab", host: "git.acme.internal" });
|
||||
expect(probeForge).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("resolves cloud and probed hosts directly via resolveHost and shares service instances", async () => {
|
||||
const probeForge = vi.fn(async (host: string) =>
|
||||
host === "git.acme.internal" ? "gitlab" : null,
|
||||
);
|
||||
const created: string[] = [];
|
||||
const disposed: string[] = [];
|
||||
const resolver = createForgeResolver({
|
||||
probeForge,
|
||||
createService: (forge) => {
|
||||
created.push(forge);
|
||||
const base = createForgeService(forge);
|
||||
if (!base) return null;
|
||||
return {
|
||||
...base,
|
||||
dispose: () => {
|
||||
disposed.push(forge);
|
||||
},
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
const cloud = await resolver.resolveHost("GitLab.com.");
|
||||
expect(cloud).toMatchObject({ forge: "gitlab", host: "gitlab.com" });
|
||||
expect(probeForge).not.toHaveBeenCalled();
|
||||
|
||||
const selfHosted = await resolver.resolveHost("GIT.ACME.INTERNAL");
|
||||
expect(selfHosted).toMatchObject({ forge: "gitlab", host: "git.acme.internal" });
|
||||
expect(selfHosted?.service).toBe(cloud?.service);
|
||||
expect(probeForge).toHaveBeenCalledTimes(1);
|
||||
expect(resolver.getService("gitlab")).toBe(cloud?.service);
|
||||
expect(created).toEqual(["gitlab"]);
|
||||
|
||||
resolver.dispose();
|
||||
expect(disposed).toEqual(["gitlab"]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,9 +1,5 @@
|
||||
import { LRUCache } from "lru-cache";
|
||||
import {
|
||||
normalizeHost,
|
||||
parseGitRemoteLocation,
|
||||
type GitRemoteLocation,
|
||||
} from "@getpaseo/protocol/git-remote";
|
||||
import { parseGitRemoteLocation, type GitRemoteLocation } from "@getpaseo/protocol/git-remote";
|
||||
import { resolveSshHostname, type SshHostnameResolver } from "../utils/ssh-hostname.js";
|
||||
import { defaultResolveRemoteUrl } from "./forge-cli-command.js";
|
||||
import type { ForgeService } from "./forge-service.js";
|
||||
@@ -28,7 +24,6 @@ export type ForgeHostProbe = (host: string) => Promise<string | null>;
|
||||
export interface CreateForgeResolverOptions {
|
||||
resolveRemoteUrl?: (cwd: string) => Promise<string | null>;
|
||||
createService?: (forge: string) => ForgeService | null;
|
||||
matchHost?: (host: string) => string | null;
|
||||
probeForge?: ForgeHostProbe;
|
||||
resolveSshHostname?: SshHostnameResolver;
|
||||
now?: () => number;
|
||||
@@ -41,18 +36,12 @@ export interface ForgeResolver {
|
||||
resolveFromRemoteUrl(remoteUrl: string | null): ForgeResolution | null;
|
||||
/** Resolve from a known origin remote URL, running the per-host probe when needed. */
|
||||
resolveFromRemoteUrlAsync(remoteUrl: string | null): Promise<ForgeResolution | null>;
|
||||
/** Resolve a forge directly by hostname (cloud match first, then cached async probe). */
|
||||
resolveHost(host: string): Promise<ForgeResolution | null>;
|
||||
/** Return the shared adapter instance for a known forge id without probing the network. */
|
||||
getService(forge: string): ForgeService | null;
|
||||
/**
|
||||
* Invalidate every cached adapter's state for a cwd. Routed through the
|
||||
* resolver so invalidation hits the same adapter instance the poller reads,
|
||||
* regardless of which forge backs the workspace.
|
||||
*/
|
||||
invalidate(cwd: string): void;
|
||||
/** Dispose all instantiated forge adapters owned by this resolver. */
|
||||
dispose(): void;
|
||||
}
|
||||
|
||||
// A positive probe (host IS a known forge) is cached permanently; a negative one
|
||||
@@ -75,7 +64,6 @@ export function forgeForHost(host: string): string | null {
|
||||
export function createForgeResolver(options: CreateForgeResolverOptions = {}): ForgeResolver {
|
||||
const resolveRemoteUrl = options.resolveRemoteUrl ?? defaultResolveRemoteUrl;
|
||||
const create = options.createService ?? createForgeService;
|
||||
const matchHost = options.matchHost ?? forgeForHost;
|
||||
const probeForge = options.probeForge ?? probeRegisteredForgeHost;
|
||||
const resolveSsh = options.resolveSshHostname ?? resolveSshHostname;
|
||||
const now = options.now ?? Date.now;
|
||||
@@ -122,34 +110,22 @@ export function createForgeResolver(options: CreateForgeResolverOptions = {}): F
|
||||
if (!entry) {
|
||||
return undefined;
|
||||
}
|
||||
if (entry.expiresAt !== null && now() >= entry.expiresAt) {
|
||||
if (entry.expiresAt !== null && Date.now() >= entry.expiresAt) {
|
||||
probedForgeByHost.delete(host);
|
||||
return undefined;
|
||||
}
|
||||
return entry.forge;
|
||||
}
|
||||
|
||||
function getService(forge: string): ForgeService | null {
|
||||
const normalized = forge.trim().toLowerCase();
|
||||
if (!normalized) {
|
||||
return null;
|
||||
}
|
||||
let service = services.get(normalized);
|
||||
function buildResolution(forge: string, host: string): ForgeResolution | null {
|
||||
let service = services.get(forge);
|
||||
if (!service) {
|
||||
const created = create(normalized);
|
||||
const created = create(forge);
|
||||
if (!created) {
|
||||
return null;
|
||||
}
|
||||
service = created;
|
||||
services.set(normalized, service);
|
||||
}
|
||||
return service;
|
||||
}
|
||||
|
||||
function buildResolution(forge: string, host: string): ForgeResolution | null {
|
||||
const service = getService(forge);
|
||||
if (!service) {
|
||||
return null;
|
||||
services.set(forge, service);
|
||||
}
|
||||
return { forge, host, service };
|
||||
}
|
||||
@@ -175,7 +151,7 @@ export function createForgeResolver(options: CreateForgeResolverOptions = {}): F
|
||||
}
|
||||
probedForgeByHost.set(host, {
|
||||
forge: probed,
|
||||
expiresAt: probed === null ? now() + NEGATIVE_PROBE_TTL_MS : null,
|
||||
expiresAt: probed === null ? Date.now() + NEGATIVE_PROBE_TTL_MS : null,
|
||||
});
|
||||
return probed;
|
||||
} finally {
|
||||
@@ -194,29 +170,13 @@ export function createForgeResolver(options: CreateForgeResolverOptions = {}): F
|
||||
if (!host) {
|
||||
return null;
|
||||
}
|
||||
const forge = matchHost(host) ?? readFreshProbe(host) ?? null;
|
||||
const forge = forgeForHost(host) ?? readFreshProbe(host) ?? null;
|
||||
if (!forge) {
|
||||
return null;
|
||||
}
|
||||
return buildResolution(forge, host);
|
||||
}
|
||||
|
||||
async function resolveHost(host: string): Promise<ForgeResolution | null> {
|
||||
const normalized = normalizeHost(host);
|
||||
if (!normalized) {
|
||||
return null;
|
||||
}
|
||||
const directForge = matchHost(normalized);
|
||||
if (directForge) {
|
||||
return buildResolution(directForge, normalized);
|
||||
}
|
||||
const probed = await probeHostForge(normalized);
|
||||
if (!probed) {
|
||||
return null;
|
||||
}
|
||||
return buildResolution(probed, normalized);
|
||||
}
|
||||
|
||||
async function resolveFromRemoteUrlAsync(
|
||||
remoteUrl: string | null,
|
||||
): Promise<ForgeResolution | null> {
|
||||
@@ -227,7 +187,7 @@ export function createForgeResolver(options: CreateForgeResolverOptions = {}): F
|
||||
if (!location) {
|
||||
return null;
|
||||
}
|
||||
const directForge = matchHost(location.host);
|
||||
const directForge = forgeForHost(location.host);
|
||||
if (directForge) {
|
||||
return buildResolution(directForge, location.host);
|
||||
}
|
||||
@@ -255,7 +215,7 @@ export function createForgeResolver(options: CreateForgeResolverOptions = {}): F
|
||||
}
|
||||
probedForgeByHost.set(aliasHost, {
|
||||
forge,
|
||||
expiresAt: forge === null ? now() + NEGATIVE_PROBE_TTL_MS : null,
|
||||
expiresAt: forge === null ? Date.now() + NEGATIVE_PROBE_TTL_MS : null,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -271,7 +231,7 @@ export function createForgeResolver(options: CreateForgeResolverOptions = {}): F
|
||||
return { host: location.host };
|
||||
}
|
||||
|
||||
const resolvedForge = matchHost(resolvedHost);
|
||||
const resolvedForge = forgeForHost(resolvedHost);
|
||||
if (resolvedForge) {
|
||||
return { host: resolvedHost, forge: resolvedForge };
|
||||
}
|
||||
@@ -286,19 +246,10 @@ export function createForgeResolver(options: CreateForgeResolverOptions = {}): F
|
||||
}
|
||||
}
|
||||
|
||||
function dispose(): void {
|
||||
for (const service of services.values()) {
|
||||
service.dispose?.();
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
resolveFromRemoteUrl,
|
||||
resolveFromRemoteUrlAsync,
|
||||
resolveHost,
|
||||
getService,
|
||||
invalidate,
|
||||
dispose,
|
||||
async resolve(cwd: string): Promise<ForgeResolution | null> {
|
||||
return resolveFromRemoteUrlAsync(await resolveRemoteUrlCached(cwd));
|
||||
},
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import type { ForgeSearchKind } from "@getpaseo/protocol/messages";
|
||||
import type { ChangeRequestSource } from "./change-request-source.js";
|
||||
|
||||
export type ForgeSearchRequestKind = ForgeSearchKind | "github-issue" | "github-pr" | "pr";
|
||||
|
||||
@@ -534,8 +533,6 @@ export interface ForgeService {
|
||||
onError?: (error: unknown) => void;
|
||||
},
|
||||
): { unsubscribe: () => void };
|
||||
/** Exact-URL change request observation adapter for watches, when supported by the forge. */
|
||||
changeRequests?: ChangeRequestSource;
|
||||
invalidate(options: { cwd: string }): void;
|
||||
dispose?(): void;
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,936 +0,0 @@
|
||||
import pLimit from "p-limit";
|
||||
import { z } from "zod";
|
||||
import { normalizeHost } from "@getpaseo/protocol/git-remote";
|
||||
import {
|
||||
ChangeRequestRateLimitError,
|
||||
createPerHostChangeRequestPoller,
|
||||
type PerHostReadContext,
|
||||
parseCliHttpResponse,
|
||||
parseRetryAfterMs,
|
||||
} from "./change-request-poller.js";
|
||||
import type { ChangeRequestSnapshot, ChangeRequestSource } from "./change-request-source.js";
|
||||
import {
|
||||
findTeaLoginNameForBaseUrl,
|
||||
getGiteaActionTaskName,
|
||||
GITEA_ACTION_MAX_PAGES,
|
||||
GITEA_ACTION_PAGE_LIMIT,
|
||||
GiteaActionsListResponseSchema,
|
||||
GiteaCombinedCommitStatusSchema,
|
||||
latestGiteaActionTasksByWorkflow,
|
||||
parseGiteaActionTasks,
|
||||
type GiteaActionTask,
|
||||
type GiteaCommitStatus,
|
||||
} from "./gitea-checks.js";
|
||||
|
||||
const GITEA_CLOUD_HOSTS = new Set(["gitea.com", "codeberg.org"]);
|
||||
const GITEA_PR_TABS = new Set(["commits", "files", "checks"]);
|
||||
const GITEA_PAGE_SIZE = GITEA_ACTION_PAGE_LIMIT;
|
||||
const GITEA_REVIEW_COMMENT_CONCURRENCY = 3;
|
||||
const GITEA_REVIEW_COMMENTS_TTL_MS = 5 * 60_000;
|
||||
const GITEA_ACTION_RUN_LOOKUP_LIMIT = 5;
|
||||
|
||||
const checkUrlSchema = z.url({ protocol: /^https?$/ });
|
||||
|
||||
const giteaWatchPrSchema = z
|
||||
.object({
|
||||
number: z.number(),
|
||||
state: z.string(),
|
||||
merged: z.boolean().optional(),
|
||||
merged_at: z.string().nullable().optional(),
|
||||
html_url: z.string().optional(),
|
||||
head: z
|
||||
.object({
|
||||
sha: z.string(),
|
||||
})
|
||||
.passthrough(),
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
const giteaIssueCommentSchema = z
|
||||
.object({
|
||||
id: z.number(),
|
||||
html_url: z.string().optional(),
|
||||
type: z.string().optional(),
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
const giteaReviewSchema = z
|
||||
.object({
|
||||
id: z.number(),
|
||||
state: z.string(),
|
||||
comments_count: z.number().optional().default(0),
|
||||
submitted_at: z.string().nullable().optional(),
|
||||
updated_at: z.string().nullable().optional(),
|
||||
html_url: z.string().optional(),
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
const giteaReviewCommentSchema = z
|
||||
.object({
|
||||
id: z.number(),
|
||||
html_url: z.string().optional(),
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
const giteaActionJobSchema = z.object({
|
||||
id: z.number(),
|
||||
name: z.string(),
|
||||
status: z.string(),
|
||||
conclusion: z.string().nullable().optional(),
|
||||
html_url: z.string().nullable().optional(),
|
||||
});
|
||||
|
||||
const giteaActionJobsPageSchema = z.union([
|
||||
z.object({
|
||||
jobs: z
|
||||
.array(giteaActionJobSchema)
|
||||
.nullable()
|
||||
.transform((jobs) => jobs ?? []),
|
||||
total_count: z.number(),
|
||||
}),
|
||||
// Forgejo returns the complete job list as an array.
|
||||
z.array(giteaActionJobSchema),
|
||||
]);
|
||||
|
||||
type GiteaActionJob = z.infer<typeof giteaActionJobSchema>;
|
||||
|
||||
type GiteaWatchPr = z.infer<typeof giteaWatchPrSchema>;
|
||||
type GiteaReview = z.infer<typeof giteaReviewSchema>;
|
||||
|
||||
interface GiteaPullRequestIdentity {
|
||||
baseUrl: string;
|
||||
displayBase: string | null;
|
||||
owner: string;
|
||||
repo: string;
|
||||
number: number;
|
||||
}
|
||||
|
||||
function invalidGiteaUrl(): never {
|
||||
throw new Error("Enter a Gitea, Forgejo, or Codeberg pull request URL.");
|
||||
}
|
||||
|
||||
function parseGiteaUrlOrigin(input: string): {
|
||||
protocol: "http:" | "https:";
|
||||
host: string;
|
||||
port: string;
|
||||
hostWithPort: string;
|
||||
pathname: string;
|
||||
} {
|
||||
const trimmed = input.trim();
|
||||
if (!trimmed || /\s/.test(trimmed)) invalidGiteaUrl();
|
||||
let parsed: URL;
|
||||
try {
|
||||
parsed = new URL(trimmed);
|
||||
} catch {
|
||||
invalidGiteaUrl();
|
||||
}
|
||||
const protocol = parsed.protocol.toLowerCase();
|
||||
if ((protocol !== "https:" && protocol !== "http:") || parsed.username || parsed.password) {
|
||||
invalidGiteaUrl();
|
||||
}
|
||||
const host = normalizeHost(parsed.hostname);
|
||||
if (!host || (GITEA_CLOUD_HOSTS.has(host) && protocol !== "https:")) {
|
||||
invalidGiteaUrl();
|
||||
}
|
||||
return {
|
||||
protocol: protocol as "http:" | "https:",
|
||||
host,
|
||||
port: parsed.port,
|
||||
hostWithPort: parsed.port ? `${host}:${parsed.port}` : host,
|
||||
pathname: parsed.pathname,
|
||||
};
|
||||
}
|
||||
|
||||
function decodeRepoSegment(raw: string): string {
|
||||
let decoded: string;
|
||||
try {
|
||||
decoded = decodeURIComponent(raw);
|
||||
} catch {
|
||||
invalidGiteaUrl();
|
||||
}
|
||||
if (
|
||||
!decoded ||
|
||||
decoded === "." ||
|
||||
decoded === ".." ||
|
||||
decoded.includes("/") ||
|
||||
decoded.includes("\\")
|
||||
) {
|
||||
invalidGiteaUrl();
|
||||
}
|
||||
return decoded;
|
||||
}
|
||||
|
||||
function parseGiteaPullRequestUrl(input: string): GiteaPullRequestIdentity {
|
||||
const origin = parseGiteaUrlOrigin(input);
|
||||
const segments = origin.pathname.split("/").filter(Boolean);
|
||||
|
||||
if (
|
||||
segments.length >= 5 &&
|
||||
GITEA_PR_TABS.has(segments.at(-1)!.toLowerCase()) &&
|
||||
/^\d+$/.test(segments.at(-2)!)
|
||||
) {
|
||||
segments.pop();
|
||||
}
|
||||
|
||||
const rawNumber = segments.pop();
|
||||
const number = Number(rawNumber);
|
||||
const resource = segments.pop();
|
||||
const repo = segments.pop();
|
||||
const owner = segments.pop();
|
||||
if (
|
||||
resource?.toLowerCase() !== "pulls" ||
|
||||
!owner ||
|
||||
!repo ||
|
||||
!rawNumber ||
|
||||
!/^\d+$/.test(rawNumber) ||
|
||||
!Number.isInteger(number) ||
|
||||
number < 1 ||
|
||||
number > 2_147_483_647
|
||||
) {
|
||||
invalidGiteaUrl();
|
||||
}
|
||||
|
||||
const path = segments.length ? `/${segments.join("/")}` : "";
|
||||
const displayBase =
|
||||
!path && !origin.port && GITEA_CLOUD_HOSTS.has(origin.host)
|
||||
? null
|
||||
: `${origin.hostWithPort}${path}`;
|
||||
return {
|
||||
baseUrl: `${origin.protocol}//${origin.hostWithPort}${path}`,
|
||||
displayBase,
|
||||
owner: decodeRepoSegment(owner),
|
||||
repo: decodeRepoSegment(repo),
|
||||
number,
|
||||
};
|
||||
}
|
||||
|
||||
export function resolveGiteaChangeRequest(input: string): string {
|
||||
const { baseUrl, owner, repo, number } = parseGiteaPullRequestUrl(input);
|
||||
return `${baseUrl}/${owner.toLowerCase()}/${repo.toLowerCase()}/pulls/${number}`;
|
||||
}
|
||||
|
||||
export function describeGiteaChangeRequest(url: string): string {
|
||||
const { displayBase, owner, repo, number } = parseGiteaPullRequestUrl(url);
|
||||
const project = displayBase ? `${displayBase}/${owner}/${repo}` : `${owner}/${repo}`;
|
||||
return `${project} #${number}`;
|
||||
}
|
||||
|
||||
function mapGiteaPrState(pr: GiteaWatchPr): ChangeRequestSnapshot["state"] {
|
||||
if (pr.merged === true || pr.merged_at != null) return "merged";
|
||||
const normalized = pr.state.toLowerCase();
|
||||
if (normalized === "open") return "open";
|
||||
if (normalized === "merged") return "merged";
|
||||
return "closed";
|
||||
}
|
||||
|
||||
function mapCommitStatusToWatchState(
|
||||
status: string,
|
||||
): ChangeRequestSnapshot["checks"][number]["state"] {
|
||||
switch (status.toLowerCase()) {
|
||||
case "success":
|
||||
return "passed";
|
||||
case "failure":
|
||||
case "error":
|
||||
case "warning":
|
||||
return "failed";
|
||||
case "pending":
|
||||
case "running":
|
||||
return "pending";
|
||||
default:
|
||||
return "neutral";
|
||||
}
|
||||
}
|
||||
|
||||
function isCanceledActionStatus(status: GiteaCommitStatus): boolean {
|
||||
// Actions writes a generic failure state on cancellation, with a distinct
|
||||
// description in the native job's commit status.
|
||||
const description = status.description ?? "";
|
||||
return description === "Has been cancelled" || description.startsWith("Canceled after ");
|
||||
}
|
||||
|
||||
function mapActionTaskToWatchState(
|
||||
status: string,
|
||||
): ChangeRequestSnapshot["checks"][number]["state"] {
|
||||
switch (status.toLowerCase()) {
|
||||
case "success":
|
||||
return "passed";
|
||||
case "failure":
|
||||
case "failed":
|
||||
case "error":
|
||||
return "failed";
|
||||
case "cancelled":
|
||||
case "canceled":
|
||||
case "skipped":
|
||||
return "neutral";
|
||||
default:
|
||||
return "pending";
|
||||
}
|
||||
}
|
||||
|
||||
function computeAggregateChecksState(
|
||||
checks: ChangeRequestSnapshot["checks"],
|
||||
): ChangeRequestSnapshot["checksState"] {
|
||||
if (checks.length === 0) return "neutral";
|
||||
if (checks.some((check) => check.state === "failed")) return "failed";
|
||||
if (checks.some((check) => check.state === "pending")) return "pending";
|
||||
if (checks.some((check) => check.state === "passed")) return "passed";
|
||||
return "neutral";
|
||||
}
|
||||
|
||||
function nativeActionUrl(value: string | null | undefined, origin: string) {
|
||||
if (!value) return null;
|
||||
try {
|
||||
const url = new URL(value, origin);
|
||||
if (url.origin !== origin) return null;
|
||||
const match = /^(.*\/actions\/runs\/(\d+))(\/jobs\/\d+)?\/?$/.exec(url.pathname);
|
||||
if (!match) return null;
|
||||
const [, run, runId, job] = match;
|
||||
return { run: run!, runId: runId!, jobUrl: job ? `${origin}${run}${job}` : null };
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function combineWatchChecks(
|
||||
commitStatuses: GiteaCommitStatus[],
|
||||
actionTasks: GiteaActionTask[],
|
||||
jobsByRun: ReadonlyMap<string, GiteaActionJob[]>,
|
||||
origin: string,
|
||||
): ChangeRequestSnapshot["checks"] {
|
||||
const checks: ChangeRequestSnapshot["checks"] = [];
|
||||
const actionJobs = [...jobsByRun.values()].flat();
|
||||
const coveredJobUrls = new Set(
|
||||
actionJobs.map((job) => nativeActionUrl(job.html_url, origin)?.jobUrl),
|
||||
);
|
||||
|
||||
for (const status of commitStatuses) {
|
||||
const jobUrl = nativeActionUrl(status.target_url, origin)?.jobUrl;
|
||||
if (jobUrl && coveredJobUrls.has(jobUrl)) continue;
|
||||
const url = checkUrlSchema.safeParse(status.target_url).data;
|
||||
checks.push({
|
||||
id: `status:${status.id}`,
|
||||
name: status.context || `status-${status.id}`,
|
||||
state:
|
||||
jobUrl && isCanceledActionStatus(status)
|
||||
? "neutral"
|
||||
: mapCommitStatusToWatchState(status.status),
|
||||
...(url ? { url } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
for (const job of actionJobs) {
|
||||
const url = checkUrlSchema.safeParse(job.html_url).data;
|
||||
checks.push({
|
||||
id: `action-job:${job.id}`,
|
||||
name: job.name,
|
||||
state: mapActionTaskToWatchState(job.conclusion || job.status),
|
||||
...(url ? { url } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
const seenTaskIds = new Set<number>();
|
||||
for (const task of actionTasks) {
|
||||
if (seenTaskIds.has(task.id)) continue;
|
||||
const address = nativeActionUrl(task.url, origin);
|
||||
if (address && jobsByRun.has(address.run)) continue;
|
||||
seenTaskIds.add(task.id);
|
||||
const url = checkUrlSchema.safeParse(task.url).data;
|
||||
checks.push({
|
||||
id: `action:${task.id}`,
|
||||
name: getGiteaActionTaskName(task),
|
||||
state: mapActionTaskToWatchState(task.status),
|
||||
...(url ? { url } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
return checks;
|
||||
}
|
||||
|
||||
function hasNextLinkHeader(headers: ReadonlyMap<string, string>): boolean {
|
||||
const link = headers.get("link");
|
||||
return link ? /rel=["']?next["']?/i.test(link) : false;
|
||||
}
|
||||
|
||||
function parseTotalCountHeader(headers: ReadonlyMap<string, string>): number | null {
|
||||
const raw = headers.get("x-total-count");
|
||||
if (!raw) return null;
|
||||
const parsed = Number(raw);
|
||||
return Number.isInteger(parsed) && parsed >= 0 ? parsed : null;
|
||||
}
|
||||
|
||||
function isSubmittedGiteaReview(review: GiteaReview): boolean {
|
||||
const state = review.state.trim().toUpperCase();
|
||||
return state !== "PENDING" && state !== "REQUEST_REVIEW";
|
||||
}
|
||||
|
||||
function parseTeaHttpStreams(
|
||||
stdout: string,
|
||||
stderr: string,
|
||||
): {
|
||||
status: number | null;
|
||||
headers: Map<string, string>;
|
||||
body: string;
|
||||
} {
|
||||
const fromStdout = parseCliHttpResponse(stdout);
|
||||
if (fromStdout.status !== null) {
|
||||
return fromStdout;
|
||||
}
|
||||
const fromStderr = parseCliHttpResponse(stderr);
|
||||
if (fromStderr.status !== null) {
|
||||
return { status: fromStderr.status, headers: fromStderr.headers, body: stdout.trim() };
|
||||
}
|
||||
return { status: null, headers: new Map(), body: stdout.trim() };
|
||||
}
|
||||
|
||||
class TeaHttpStatusError extends Error {
|
||||
readonly status: number;
|
||||
|
||||
constructor(status: number, message: string) {
|
||||
super(message);
|
||||
this.name = "TeaHttpStatusError";
|
||||
this.status = status;
|
||||
}
|
||||
}
|
||||
|
||||
function isOptionalEndpointStatus(error: unknown): boolean {
|
||||
return (
|
||||
error instanceof TeaHttpStatusError &&
|
||||
(error.status === 403 || error.status === 404 || error.status === 501)
|
||||
);
|
||||
}
|
||||
|
||||
type TeaApiGet = <T>(
|
||||
endpoint: string,
|
||||
schema: z.ZodType<T>,
|
||||
) => Promise<{ data: T; headers: ReadonlyMap<string, string> }>;
|
||||
|
||||
interface TeaPollApi {
|
||||
get: TeaApiGet;
|
||||
all<T extends readonly unknown[]>(
|
||||
reads: T,
|
||||
): Promise<{ -readonly [Key in keyof T]: Awaited<T[Key]> }>;
|
||||
}
|
||||
|
||||
interface CachedReviewComments {
|
||||
count: number;
|
||||
fetchedAt: number;
|
||||
items: ChangeRequestSnapshot["activity"];
|
||||
}
|
||||
|
||||
export interface CreateGiteaChangeRequestSourceOptions {
|
||||
runCommand(
|
||||
args: string[],
|
||||
options: { cwd: string; envOverlay?: Record<string, string> },
|
||||
): Promise<{ stdout: string; stderr: string }>;
|
||||
createAuthError(stderr: string): Error;
|
||||
createCommandError(params: {
|
||||
args: string[];
|
||||
cwd: string;
|
||||
exitCode: number | null;
|
||||
stderr: string;
|
||||
stdout?: string;
|
||||
}): Error;
|
||||
now?: () => number;
|
||||
pollIntervalMs?: number;
|
||||
initialDelayMs?: number;
|
||||
}
|
||||
|
||||
export function createGiteaChangeRequestSource(
|
||||
options: CreateGiteaChangeRequestSourceOptions,
|
||||
): ChangeRequestSource & { dispose(): void } {
|
||||
const now = options.now ?? Date.now;
|
||||
const cachedReviewCommentsByUrl = new Map<string, Map<number, CachedReviewComments>>();
|
||||
const reviewCommentLimit = pLimit(GITEA_REVIEW_COMMENT_CONCURRENCY);
|
||||
|
||||
async function resolveLogin(baseUrl: string): Promise<string> {
|
||||
const result = await options.runCommand(["login", "list", "-o", "json"], {
|
||||
cwd: process.cwd(),
|
||||
});
|
||||
const loginName = findTeaLoginNameForBaseUrl(result.stdout, baseUrl);
|
||||
if (!loginName) {
|
||||
throw options.createAuthError(`No tea login configured for ${baseUrl}`);
|
||||
}
|
||||
return loginName;
|
||||
}
|
||||
|
||||
function parseJsonBody<T>(params: {
|
||||
args: string[];
|
||||
cwd: string;
|
||||
body: string;
|
||||
schema: z.ZodType<T>;
|
||||
}): T {
|
||||
let data: unknown;
|
||||
try {
|
||||
data = JSON.parse(params.body);
|
||||
} catch {
|
||||
throw options.createCommandError({
|
||||
args: params.args,
|
||||
cwd: params.cwd,
|
||||
exitCode: null,
|
||||
stderr: `tea did not return valid JSON (${params.body.length} bytes)`,
|
||||
});
|
||||
}
|
||||
const parsed = params.schema.safeParse(data);
|
||||
if (!parsed.success) {
|
||||
throw options.createCommandError({
|
||||
args: params.args,
|
||||
cwd: params.cwd,
|
||||
exitCode: null,
|
||||
stderr: `tea JSON did not match the expected schema: ${parsed.error.message}`,
|
||||
});
|
||||
}
|
||||
return parsed.data;
|
||||
}
|
||||
|
||||
function bindTeaApi(context: PerHostReadContext, loginName: string): TeaPollApi {
|
||||
let active = true;
|
||||
|
||||
const get: TeaApiGet = async (endpoint, schema) => {
|
||||
if (!active || !context.isObserved()) throw new Error("Change request observation ended");
|
||||
context.assertHostAvailable();
|
||||
const args = ["api", "--login", loginName, "-i", endpoint];
|
||||
const cwd = process.cwd();
|
||||
const result = await options.runCommand(args, { cwd });
|
||||
const parsed = parseTeaHttpStreams(result.stdout, result.stderr);
|
||||
const nowMs = now();
|
||||
|
||||
// tea api can exit 0 on an HTTP failure, so always check the status line.
|
||||
if (parsed.status === null) {
|
||||
throw options.createCommandError({
|
||||
args,
|
||||
cwd,
|
||||
exitCode: 0,
|
||||
stderr: "tea api -i did not return an HTTP status line",
|
||||
stdout: result.stdout,
|
||||
});
|
||||
}
|
||||
if (parsed.status === 429) {
|
||||
const resetAtMs = parseRetryAfterMs(parsed.headers, nowMs, {
|
||||
forceOnMissing: true,
|
||||
defaultPauseMs: 60_000,
|
||||
})!;
|
||||
context.pauseHost(resetAtMs);
|
||||
throw new ChangeRequestRateLimitError({ host: context.host, resetAtMs });
|
||||
}
|
||||
if (parsed.status === 401) {
|
||||
throw options.createAuthError(parsed.body || "401 Unauthorized");
|
||||
}
|
||||
if (parsed.status < 200 || parsed.status >= 300) {
|
||||
throw new TeaHttpStatusError(
|
||||
parsed.status,
|
||||
`Gitea API returned HTTP ${parsed.status} for ${endpoint}: ${parsed.body}`.trim(),
|
||||
);
|
||||
}
|
||||
|
||||
const proactivePause = parseRetryAfterMs(parsed.headers, nowMs);
|
||||
if (proactivePause !== null) context.deferPollsUntil(proactivePause);
|
||||
|
||||
const data = parseJsonBody({ args, cwd, body: parsed.body, schema });
|
||||
return { data, headers: parsed.headers };
|
||||
};
|
||||
|
||||
return {
|
||||
get,
|
||||
all(reads) {
|
||||
return Promise.all(reads).catch(async (error: unknown) => {
|
||||
// Stop admitting reads from this poll and hold its host slot until
|
||||
// requests already sent (including late rate limits) settle.
|
||||
active = false;
|
||||
await Promise.allSettled(reads);
|
||||
throw error;
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function teaApiGetAllPages<T>(params: {
|
||||
get: TeaApiGet;
|
||||
endpoint: string;
|
||||
itemSchema: z.ZodType<T>;
|
||||
}): Promise<T[]> {
|
||||
const items: T[] = [];
|
||||
const schema = z.array(params.itemSchema);
|
||||
let minPageSize = 1;
|
||||
for (let page = 1; ; page += 1) {
|
||||
const sep = params.endpoint.includes("?") ? "&" : "?";
|
||||
const { data, headers } = await params.get(
|
||||
`${params.endpoint}${sep}page=${page}&limit=${GITEA_PAGE_SIZE}`,
|
||||
schema,
|
||||
);
|
||||
items.push(...data);
|
||||
if (headers.has("link")) {
|
||||
if (hasNextLinkHeader(headers)) continue;
|
||||
break;
|
||||
}
|
||||
|
||||
const totalCount = parseTotalCountHeader(headers);
|
||||
if (totalCount !== null) {
|
||||
// Gitea can cap limit below the requested value and filter pending
|
||||
// reviews after pagination. The largest page is a lower bound on
|
||||
// the number of records advanced on every page.
|
||||
minPageSize = Math.max(minPageSize, data.length);
|
||||
if (page * minPageSize < totalCount) continue;
|
||||
break;
|
||||
}
|
||||
if (data.length < GITEA_PAGE_SIZE) break;
|
||||
}
|
||||
|
||||
return items;
|
||||
}
|
||||
|
||||
async function readCommitStatuses(params: {
|
||||
get: TeaApiGet;
|
||||
repoPrefix: string;
|
||||
headSha: string;
|
||||
isObserved(): boolean;
|
||||
}): Promise<{ statuses: GiteaCommitStatus[]; pagesRead: number }> {
|
||||
const statuses: GiteaCommitStatus[] = [];
|
||||
const seenIds = new Set<number>();
|
||||
let page = 1;
|
||||
let pagesRead = 0;
|
||||
|
||||
while (true) {
|
||||
if (!params.isObserved()) return { statuses, pagesRead };
|
||||
const response = await params.get(
|
||||
`${params.repoPrefix}/commits/${encodeURIComponent(params.headSha)}/status?limit=${GITEA_PAGE_SIZE}&page=${page}`,
|
||||
GiteaCombinedCommitStatusSchema,
|
||||
);
|
||||
pagesRead += 1;
|
||||
const pageStatuses = response.data.statuses;
|
||||
if (pageStatuses.length === 0) break;
|
||||
for (const status of pageStatuses) {
|
||||
if (seenIds.has(status.id)) {
|
||||
throw new Error("Gitea commit status pages overlap. Retry the poll.");
|
||||
}
|
||||
seenIds.add(status.id);
|
||||
statuses.push(status);
|
||||
}
|
||||
|
||||
// Gitea sets body `total_count` to the current page length; the full total
|
||||
// lives only in the `X-Total-Count` response header.
|
||||
const headerTotal = parseTotalCountHeader(response.headers);
|
||||
if (headerTotal !== null) {
|
||||
if (statuses.length >= headerTotal) break;
|
||||
page += 1;
|
||||
continue;
|
||||
}
|
||||
if (hasNextLinkHeader(response.headers) || pageStatuses.length >= GITEA_PAGE_SIZE) {
|
||||
page += 1;
|
||||
continue;
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
return { statuses, pagesRead };
|
||||
}
|
||||
|
||||
async function readBoundedActionTasks(params: {
|
||||
get: TeaApiGet;
|
||||
repoPrefix: string;
|
||||
isObserved(): boolean;
|
||||
}): Promise<{ items: unknown[]; pagesRead: number }> {
|
||||
const items: unknown[] = [];
|
||||
let fetched = 0;
|
||||
let pagesRead = 0;
|
||||
|
||||
for (let page = 1; page <= GITEA_ACTION_MAX_PAGES; page += 1) {
|
||||
if (!params.isObserved()) return { items, pagesRead };
|
||||
let response: { data: z.infer<typeof GiteaActionsListResponseSchema> };
|
||||
try {
|
||||
response = await params.get(
|
||||
`${params.repoPrefix}/actions/tasks?limit=${GITEA_PAGE_SIZE}&page=${page}`,
|
||||
GiteaActionsListResponseSchema,
|
||||
);
|
||||
} catch (error) {
|
||||
if (page === 1 && isOptionalEndpointStatus(error)) {
|
||||
return { items: [], pagesRead: 0 };
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
pagesRead += 1;
|
||||
const runs = response.data.workflow_runs;
|
||||
if (runs.length === 0) break;
|
||||
fetched += runs.length;
|
||||
items.push(...runs);
|
||||
if (response.data.total_count !== undefined && fetched >= response.data.total_count) break;
|
||||
}
|
||||
|
||||
return { items, pagesRead };
|
||||
}
|
||||
|
||||
async function readActionJobs(params: {
|
||||
get: TeaApiGet;
|
||||
origin: string;
|
||||
repoPrefix: string;
|
||||
tasks: GiteaActionTask[];
|
||||
statuses: GiteaCommitStatus[];
|
||||
}): Promise<Map<string, GiteaActionJob[]>> {
|
||||
// Commit statuses identify a job URL. Tasks identify a run, so only a job
|
||||
// list can establish coverage when both sources report the same run.
|
||||
const statusRuns = new Set<string>();
|
||||
for (const status of params.statuses) {
|
||||
const address = nativeActionUrl(status.target_url, params.origin);
|
||||
if (address?.jobUrl) statusRuns.add(address.run);
|
||||
}
|
||||
const runs = new Map<string, string>();
|
||||
for (const task of params.tasks) {
|
||||
const address = nativeActionUrl(task.url, params.origin);
|
||||
if (address && statusRuns.has(address.run)) runs.set(address.run, address.runId);
|
||||
}
|
||||
const jobsByRun = new Map<string, GiteaActionJob[]>();
|
||||
for (const [run, runId] of [...runs].slice(0, GITEA_ACTION_RUN_LOOKUP_LIMIT)) {
|
||||
const endpoint = `${params.repoPrefix}/actions/runs/${runId}/jobs`;
|
||||
const jobs = new Map<number, GiteaActionJob>();
|
||||
for (let page = 1; page <= GITEA_ACTION_MAX_PAGES; page += 1) {
|
||||
try {
|
||||
const { data } = await params.get(
|
||||
`${endpoint}?limit=${GITEA_PAGE_SIZE}&page=${page}`,
|
||||
giteaActionJobsPageSchema,
|
||||
);
|
||||
const items = Array.isArray(data) ? data : data.jobs;
|
||||
const totalCount = Array.isArray(data) ? data.length : data.total_count;
|
||||
if (!items.length) break;
|
||||
// The browser run number and API ID differ on some versions. Keep
|
||||
// the original sources if any job belongs to another run.
|
||||
if (items.some((job) => nativeActionUrl(job.html_url, params.origin)?.run !== run)) {
|
||||
break;
|
||||
}
|
||||
for (const job of items) jobs.set(job.id, job);
|
||||
if (jobs.size >= totalCount) {
|
||||
jobsByRun.set(run, [...jobs.values()]);
|
||||
break;
|
||||
}
|
||||
} catch (error) {
|
||||
if (page === 1 && isOptionalEndpointStatus(error)) break;
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
return jobsByRun;
|
||||
}
|
||||
|
||||
async function readChecks(params: {
|
||||
api: TeaPollApi;
|
||||
origin: string;
|
||||
repoPrefix: string;
|
||||
prEndpoint: string;
|
||||
headSha: string;
|
||||
isObserved(): boolean;
|
||||
}): Promise<ChangeRequestSnapshot["checks"]> {
|
||||
const { get, all } = params.api;
|
||||
const [statusResult, tasksResult] = await all([
|
||||
readCommitStatuses({ ...params, get }),
|
||||
readBoundedActionTasks({ ...params, get }),
|
||||
]);
|
||||
if (!params.isObserved()) {
|
||||
throw new Error("Change request observation ended");
|
||||
}
|
||||
|
||||
const matchingTasks = parseGiteaActionTasks(tasksResult.items).filter(
|
||||
(task) => task.head_sha === params.headSha,
|
||||
);
|
||||
const latestTasks = latestGiteaActionTasksByWorkflow(matchingTasks);
|
||||
|
||||
const jobsByRun = await readActionJobs({
|
||||
...params,
|
||||
get,
|
||||
tasks: latestTasks,
|
||||
statuses: statusResult.statuses,
|
||||
});
|
||||
if (statusResult.pagesRead > 1 || tasksResult.pagesRead > 1 || jobsByRun.size > 0) {
|
||||
const { data: recheck } = await get(params.prEndpoint, giteaWatchPrSchema);
|
||||
if (recheck.head.sha !== params.headSha) {
|
||||
throw new Error("The pull request head changed during pagination.");
|
||||
}
|
||||
}
|
||||
|
||||
return combineWatchChecks(statusResult.statuses, latestTasks, jobsByRun, params.origin);
|
||||
}
|
||||
|
||||
async function readActivity(params: {
|
||||
url: string;
|
||||
api: TeaPollApi;
|
||||
repoPrefix: string;
|
||||
number: number;
|
||||
prWebUrl: string;
|
||||
terminal: boolean;
|
||||
knownActivity(): ReadonlySet<string> | undefined;
|
||||
isObserved(): boolean;
|
||||
}): Promise<ChangeRequestSnapshot["activity"]> {
|
||||
const { get, all } = params.api;
|
||||
const [comments, reviews] = await all([
|
||||
teaApiGetAllPages({
|
||||
get,
|
||||
endpoint: `${params.repoPrefix}/issues/${params.number}/comments`,
|
||||
itemSchema: giteaIssueCommentSchema,
|
||||
}),
|
||||
teaApiGetAllPages({
|
||||
get,
|
||||
endpoint: `${params.repoPrefix}/pulls/${params.number}/reviews`,
|
||||
itemSchema: giteaReviewSchema,
|
||||
}),
|
||||
]);
|
||||
if (!params.isObserved()) {
|
||||
throw new Error("Change request observation ended");
|
||||
}
|
||||
|
||||
const activity: ChangeRequestSnapshot["activity"] = [];
|
||||
for (const comment of comments) {
|
||||
if (comment.type !== undefined && comment.type !== "comment") continue;
|
||||
activity.push({
|
||||
id: `comment:${comment.id}`,
|
||||
kind: "comment",
|
||||
url: comment.html_url || `${params.prWebUrl}#issuecomment-${comment.id}`,
|
||||
});
|
||||
}
|
||||
|
||||
const submittedReviews = reviews.filter(isSubmittedGiteaReview);
|
||||
for (const review of submittedReviews) {
|
||||
activity.push({
|
||||
id: `review:${review.id}`,
|
||||
kind: "review",
|
||||
url: review.html_url || `${params.prWebUrl}#pullrequestreview-${review.id}`,
|
||||
});
|
||||
}
|
||||
|
||||
const known = params.knownActivity();
|
||||
let reviewCache = cachedReviewCommentsByUrl.get(params.url);
|
||||
if (!reviewCache) {
|
||||
reviewCache = new Map<number, CachedReviewComments>();
|
||||
cachedReviewCommentsByUrl.set(params.url, reviewCache);
|
||||
}
|
||||
|
||||
const staleBefore = now() - GITEA_REVIEW_COMMENTS_TTL_MS;
|
||||
const reviewsNeedingFetch = submittedReviews.filter((review) => {
|
||||
if (review.comments_count <= 0) return false;
|
||||
const cached = reviewCache.get(review.id);
|
||||
if (
|
||||
!params.terminal &&
|
||||
cached &&
|
||||
cached.fetchedAt > staleBefore &&
|
||||
cached.count === review.comments_count &&
|
||||
cached.items.every((item) => known?.has(item.id))
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
|
||||
// Gitea's review-comments endpoint returns all comments for a review in one
|
||||
// response and ignores page/limit, so fetch it once without a pagination loop.
|
||||
const fetchedGroups = await all(
|
||||
reviewsNeedingFetch.map((review) =>
|
||||
reviewCommentLimit(async () => {
|
||||
if (!params.isObserved()) {
|
||||
return { reviewId: review.id, count: review.comments_count, items: [] };
|
||||
}
|
||||
const { data: inlineComments } = await get(
|
||||
`${params.repoPrefix}/pulls/${params.number}/reviews/${review.id}/comments`,
|
||||
z.array(giteaReviewCommentSchema),
|
||||
);
|
||||
const items: ChangeRequestSnapshot["activity"] = inlineComments.map((comment) => ({
|
||||
id: `inline:${comment.id}`,
|
||||
kind: "inline comment",
|
||||
url: comment.html_url || `${params.prWebUrl}#issuecomment-${comment.id}`,
|
||||
}));
|
||||
return { reviewId: review.id, count: review.comments_count, items };
|
||||
}),
|
||||
),
|
||||
);
|
||||
if (!params.isObserved()) {
|
||||
throw new Error("Change request observation ended");
|
||||
}
|
||||
|
||||
const fetchedAt = now();
|
||||
for (const group of fetchedGroups) {
|
||||
reviewCache.set(group.reviewId, { count: group.count, fetchedAt, items: group.items });
|
||||
}
|
||||
for (const review of submittedReviews) {
|
||||
if (review.comments_count <= 0) continue;
|
||||
const cached = reviewCache.get(review.id);
|
||||
if (cached) {
|
||||
activity.push(...cached.items);
|
||||
}
|
||||
}
|
||||
|
||||
return activity;
|
||||
}
|
||||
|
||||
async function readPullRequest(context: PerHostReadContext): Promise<ChangeRequestSnapshot> {
|
||||
const identity = parseGiteaPullRequestUrl(context.url);
|
||||
const { baseUrl, owner, repo, number } = identity;
|
||||
const loginName = await resolveLogin(baseUrl);
|
||||
const api = bindTeaApi(context, loginName);
|
||||
const repoPrefix = `repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}`;
|
||||
const prEndpoint = `${repoPrefix}/pulls/${number}`;
|
||||
|
||||
const { data: pr } = await api.get(prEndpoint, giteaWatchPrSchema);
|
||||
if (!pr.head.sha) {
|
||||
throw new Error(`Gitea pull request #${number} did not include a head commit SHA.`);
|
||||
}
|
||||
const prWebUrl = pr.html_url || context.url;
|
||||
const address = parseGiteaPullRequestUrl(prWebUrl);
|
||||
if (
|
||||
address.baseUrl !== baseUrl ||
|
||||
address.owner.toLowerCase() !== owner.toLowerCase() ||
|
||||
address.repo.toLowerCase() !== repo.toLowerCase() ||
|
||||
address.number !== number ||
|
||||
pr.number !== number
|
||||
) {
|
||||
throw new Error("Tea returned a pull request that does not match the watch URL.");
|
||||
}
|
||||
|
||||
const checks = await readChecks({
|
||||
api,
|
||||
origin: context.host,
|
||||
repoPrefix,
|
||||
prEndpoint,
|
||||
headSha: pr.head.sha,
|
||||
isObserved: context.isObserved,
|
||||
});
|
||||
const state = mapGiteaPrState(pr);
|
||||
const activity = await readActivity({
|
||||
url: context.url,
|
||||
api,
|
||||
repoPrefix,
|
||||
number,
|
||||
prWebUrl,
|
||||
terminal: state !== "open",
|
||||
knownActivity: context.knownActivity,
|
||||
isObserved: context.isObserved,
|
||||
});
|
||||
|
||||
return {
|
||||
state,
|
||||
headSha: pr.head.sha,
|
||||
checksState: computeAggregateChecksState(checks),
|
||||
checks,
|
||||
reviewDecision: null,
|
||||
activity,
|
||||
};
|
||||
}
|
||||
|
||||
const poller = createPerHostChangeRequestPoller({
|
||||
hostOf: (url) => new URL(url).origin,
|
||||
read: readPullRequest,
|
||||
now,
|
||||
pollIntervalMs: options.pollIntervalMs,
|
||||
initialDelayMs: options.initialDelayMs,
|
||||
});
|
||||
|
||||
return {
|
||||
resolve: resolveGiteaChangeRequest,
|
||||
describe: describeGiteaChangeRequest,
|
||||
observe(url, callbacks) {
|
||||
const release = poller.observe(url, callbacks);
|
||||
return () => {
|
||||
cachedReviewCommentsByUrl.delete(url);
|
||||
release();
|
||||
};
|
||||
},
|
||||
dispose() {
|
||||
cachedReviewCommentsByUrl.clear();
|
||||
poller.dispose();
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -1,253 +0,0 @@
|
||||
import { z } from "zod";
|
||||
import { normalizeHost } from "@getpaseo/protocol/git-remote";
|
||||
|
||||
// 50 is the page-size cap Gitea enforces on list endpoints; five pages bounds
|
||||
// the sweep to the 250 most recent Actions tasks.
|
||||
export const GITEA_ACTION_PAGE_LIMIT = 50;
|
||||
export const GITEA_ACTION_MAX_PAGES = 5;
|
||||
|
||||
const GITEA_RELATIVE_URL_ORIGIN = "https://gitea.invalid";
|
||||
|
||||
export const GiteaLoginSchema = z
|
||||
.object({
|
||||
name: z.string().optional(),
|
||||
url: z.string().optional(),
|
||||
ssh_host: z.string().optional(),
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
export const GiteaCommitStatusSchema = z
|
||||
.object({
|
||||
id: z.number(),
|
||||
status: z.string(),
|
||||
target_url: z.string().nullable().optional(),
|
||||
description: z.string().nullable().optional(),
|
||||
url: z.string().nullable().optional(),
|
||||
context: z.string().optional().default(""),
|
||||
creator: z.unknown().nullable().optional(),
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
export const GiteaCombinedCommitStatusSchema = z
|
||||
.object({
|
||||
state: z.string().optional().default(""),
|
||||
sha: z.string().optional(),
|
||||
total_count: z.number().optional(),
|
||||
statuses: z
|
||||
.array(GiteaCommitStatusSchema)
|
||||
.nullable()
|
||||
.optional()
|
||||
.transform((value) => value ?? []),
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
export const GiteaActionTaskSchema = z
|
||||
.object({
|
||||
id: z.number(),
|
||||
name: z.string().nullable().optional(),
|
||||
head_branch: z.string().nullable().optional(),
|
||||
head_sha: z.string(),
|
||||
run_number: z.number().optional(),
|
||||
event: z.string().nullable().optional(),
|
||||
display_title: z.string().nullable().optional(),
|
||||
status: z.string(),
|
||||
need_approval: z.boolean().optional().default(false),
|
||||
workflow_id: z.string().nullable().optional(),
|
||||
url: z.string().nullable().optional(),
|
||||
created_at: z.string().nullable().optional(),
|
||||
run_started_at: z.string().nullable().optional(),
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
// The item shape is validated per-task rather than as `z.array(GiteaActionTaskSchema)`
|
||||
// so one malformed task (missing id/status/head_sha) drops only itself instead of
|
||||
// throwing out the whole page and zeroing every Actions check for the PR.
|
||||
export const GiteaActionsListResponseSchema = z
|
||||
.object({
|
||||
workflow_runs: z
|
||||
.array(z.unknown())
|
||||
.nullable()
|
||||
.optional()
|
||||
.transform((value) => value ?? []),
|
||||
total_count: z.number().optional(),
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
export type GiteaCommitStatus = z.infer<typeof GiteaCommitStatusSchema>;
|
||||
export type GiteaCombinedCommitStatus = z.infer<typeof GiteaCombinedCommitStatusSchema>;
|
||||
export type GiteaActionTask = z.infer<typeof GiteaActionTaskSchema>;
|
||||
|
||||
export function getGiteaActionTaskName(task: GiteaActionTask): string {
|
||||
return task.name || task.display_title || task.workflow_id || `actions-${task.id}`;
|
||||
}
|
||||
|
||||
export function getUrlOrigin(value: string | null | undefined): string | null {
|
||||
if (!value) return null;
|
||||
try {
|
||||
return new URL(value).origin;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function getGiteaActionRunIdFromUrl(value: string | null | undefined): number | null {
|
||||
if (!value) return null;
|
||||
try {
|
||||
const url = new URL(value, GITEA_RELATIVE_URL_ORIGIN);
|
||||
const match = url.pathname.match(/\/actions\/runs\/(\d+)(?:\/jobs\/\d+)?\/?$/);
|
||||
return match?.[1] ? Number.parseInt(match[1], 10) : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function isNativeActionJobUrl(
|
||||
targetUrl: string | null | undefined,
|
||||
nativeOrigins: ReadonlySet<string>,
|
||||
nativeRunIds: ReadonlySet<number>,
|
||||
): boolean {
|
||||
if (!targetUrl) return false;
|
||||
try {
|
||||
const url = new URL(targetUrl, GITEA_RELATIVE_URL_ORIGIN);
|
||||
if (!/\/actions\/runs\/\d+\/jobs\/\d+\/?$/.test(url.pathname)) return false;
|
||||
if (url.origin !== GITEA_RELATIVE_URL_ORIGIN && !nativeOrigins.has(url.origin)) return false;
|
||||
const runId = getGiteaActionRunIdFromUrl(targetUrl);
|
||||
return runId !== null && nativeRunIds.has(runId);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// A "shadow" is the commit status Gitea synthesizes to mirror one of its own
|
||||
// Actions jobs; keeping both would double-report every job. Detection is purely
|
||||
// structural: Gitea always creates these statuses with a target_url of the form
|
||||
// "<run link>/jobs/<job id>" (services/actions/commit_status.go upstream), so a
|
||||
// status is a shadow exactly when its URL points at a job of a run we actually
|
||||
// fetched from the Actions API. Anything else - external CI, URL-less statuses,
|
||||
// contexts that merely look like "<workflow> / <job> (<event>)" - is kept.
|
||||
export function isGiteaActionShadowStatus(
|
||||
status: GiteaCommitStatus,
|
||||
nativeOrigins: ReadonlySet<string>,
|
||||
nativeRunIds: ReadonlySet<number>,
|
||||
): boolean {
|
||||
return isNativeActionJobUrl(status.target_url, nativeOrigins, nativeRunIds);
|
||||
}
|
||||
|
||||
function getGiteaActionWorkflowIdentity(task: GiteaActionTask): string {
|
||||
if (task.workflow_id) {
|
||||
return `workflow\u0000${task.workflow_id}`;
|
||||
}
|
||||
// Instances that omit workflow_id (older Gitea/Forgejo payloads) still need
|
||||
// reruns of the same job collapsed to the latest execution, so fall back to
|
||||
// the job name before treating the task as its own group.
|
||||
const name = task.name || task.display_title;
|
||||
if (name) {
|
||||
return `name\u0000${name}`;
|
||||
}
|
||||
return `task\u0000${getGiteaActionExecutionIdentity(task)}`;
|
||||
}
|
||||
|
||||
function getGiteaActionExecutionIdentity(task: GiteaActionTask): string {
|
||||
if (task.run_number !== undefined) return `run-number\u0000${task.run_number}`;
|
||||
const runId = getGiteaActionRunIdFromUrl(task.url);
|
||||
if (runId !== null) return `run-id\u0000${runId}`;
|
||||
if (task.url) return `url\u0000${task.url}`;
|
||||
return `task\u0000${task.id}`;
|
||||
}
|
||||
|
||||
function parseGiteaActionTaskTime(task: GiteaActionTask): number {
|
||||
const timestamp = task.created_at ?? task.run_started_at ?? null;
|
||||
if (!timestamp) {
|
||||
return 0;
|
||||
}
|
||||
const time = Date.parse(timestamp);
|
||||
return Number.isNaN(time) ? 0 : time;
|
||||
}
|
||||
|
||||
function compareGiteaActionTaskRecency(left: GiteaActionTask, right: GiteaActionTask): number {
|
||||
const leftRunNumber = left.run_number ?? 0;
|
||||
const rightRunNumber = right.run_number ?? 0;
|
||||
if (leftRunNumber !== rightRunNumber) {
|
||||
return leftRunNumber - rightRunNumber;
|
||||
}
|
||||
|
||||
const leftTime = parseGiteaActionTaskTime(left);
|
||||
const rightTime = parseGiteaActionTaskTime(right);
|
||||
if (leftTime !== rightTime) {
|
||||
return leftTime - rightTime;
|
||||
}
|
||||
|
||||
return left.id - right.id;
|
||||
}
|
||||
|
||||
export function parseGiteaActionTasks(rawTasks: unknown[]): GiteaActionTask[] {
|
||||
const tasks: GiteaActionTask[] = [];
|
||||
for (const raw of rawTasks) {
|
||||
const parsed = GiteaActionTaskSchema.safeParse(raw);
|
||||
if (parsed.success) {
|
||||
tasks.push(parsed.data);
|
||||
}
|
||||
}
|
||||
return tasks;
|
||||
}
|
||||
|
||||
/**
|
||||
* Keep all sibling tasks from the latest execution of each workflow.
|
||||
* Per docs/forge-providers.md, ambiguous same-run tasks are preserved because
|
||||
* display names are not stable job identities and `/actions/tasks` omits rerun
|
||||
* attempt numbers.
|
||||
*/
|
||||
export function latestGiteaActionTasksByWorkflow(tasks: GiteaActionTask[]): GiteaActionTask[] {
|
||||
const latestExecutions = new Map<string, GiteaActionTask>();
|
||||
for (const task of tasks) {
|
||||
const identity = getGiteaActionWorkflowIdentity(task);
|
||||
const current = latestExecutions.get(identity);
|
||||
if (!current || compareGiteaActionTaskRecency(current, task) < 0) {
|
||||
latestExecutions.set(identity, task);
|
||||
}
|
||||
}
|
||||
return tasks.filter((task) => {
|
||||
const latest = latestExecutions.get(getGiteaActionWorkflowIdentity(task));
|
||||
return (
|
||||
latest !== undefined &&
|
||||
getGiteaActionExecutionIdentity(task) === getGiteaActionExecutionIdentity(latest)
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
function parseTeaLogins(stdout: string): z.infer<typeof GiteaLoginSchema>[] {
|
||||
try {
|
||||
return z.array(GiteaLoginSchema).safeParse(JSON.parse(stdout)).data ?? [];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
export function findTeaLoginNameForBaseUrl(stdout: string, baseUrl: string): string | null {
|
||||
const match = parseTeaLogins(stdout).find((login) => {
|
||||
if (!login.name || !login.url) return false;
|
||||
try {
|
||||
const url = new URL(login.url);
|
||||
return `${url.origin}${url.pathname.replace(/\/+$/, "")}` === baseUrl;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
});
|
||||
return match?.name ?? null;
|
||||
}
|
||||
|
||||
export function findTeaLoginNameForHost(stdout: string, host: string): string | null {
|
||||
const targetHost = normalizeHost(host);
|
||||
const match = parseTeaLogins(stdout).find((login) => {
|
||||
const candidates = [login.ssh_host, login.name];
|
||||
if (login.url) {
|
||||
try {
|
||||
candidates.push(new URL(login.url).hostname);
|
||||
} catch {
|
||||
// ignore malformed login url
|
||||
}
|
||||
}
|
||||
return candidates.some((candidate) => candidate && normalizeHost(candidate) === targetHost);
|
||||
});
|
||||
return match?.name ?? null;
|
||||
}
|
||||
@@ -61,23 +61,6 @@ import type {
|
||||
SearchIssuesAndPrsOptions,
|
||||
SearchResult,
|
||||
} from "./forge-service.js";
|
||||
import {
|
||||
findTeaLoginNameForHost,
|
||||
getGiteaActionRunIdFromUrl,
|
||||
getGiteaActionTaskName,
|
||||
getUrlOrigin,
|
||||
GITEA_ACTION_MAX_PAGES,
|
||||
GITEA_ACTION_PAGE_LIMIT,
|
||||
GiteaActionsListResponseSchema,
|
||||
GiteaCombinedCommitStatusSchema,
|
||||
isGiteaActionShadowStatus,
|
||||
latestGiteaActionTasksByWorkflow,
|
||||
parseGiteaActionTasks,
|
||||
type GiteaActionTask,
|
||||
type GiteaCombinedCommitStatus,
|
||||
type GiteaCommitStatus,
|
||||
} from "./gitea-checks.js";
|
||||
import { createGiteaChangeRequestSource } from "./gitea-change-requests.js";
|
||||
import { isGiteaStatusFacts, type GiteaStatusFacts } from "./gitea-facts.js";
|
||||
|
||||
const TEA_ENV = {
|
||||
@@ -94,6 +77,10 @@ const reviewCommentsLimit = pLimit(REVIEW_COMMENTS_FAN_OUT_CONCURRENCY);
|
||||
// short cache, each poll re-derives the PR head SHA from scratch (branch name +
|
||||
// PR lookup + PR view). The TTL keeps a new push visible within one poll cycle.
|
||||
const CURRENT_PR_HEAD_SHA_CACHE_TTL_MS = 30_000;
|
||||
// 50 is the page-size cap Gitea enforces on list endpoints; five pages bounds
|
||||
// the sweep to the 250 most recent Actions tasks.
|
||||
const GITEA_ACTION_PAGE_LIMIT = 50;
|
||||
const GITEA_ACTION_MAX_PAGES = 5;
|
||||
// PullRequestFlowAGit in forgejo models/issues/pull.go
|
||||
const GITEA_PULL_REQUEST_FLOW_AGIT = 1;
|
||||
|
||||
@@ -155,8 +142,6 @@ export interface CreateGiteaServiceOptions {
|
||||
resolveRemoteUrl?: (cwd: string) => Promise<string | null>;
|
||||
resolveCurrentBranch?: (cwd: string) => Promise<string | null>;
|
||||
now?: () => number;
|
||||
watchPollMs?: number;
|
||||
watchInitialDelayMs?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -195,6 +180,14 @@ const GiteaIssueListItemSchema = z
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
const GiteaLoginSchema = z
|
||||
.object({
|
||||
name: z.string().optional(),
|
||||
url: z.string().optional(),
|
||||
ssh_host: z.string().optional(),
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
const GiteaUserSchema = z
|
||||
.object({
|
||||
login: z.string().optional(),
|
||||
@@ -295,6 +288,55 @@ const GiteaCurrentPullRequestApiSchema = z
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
const GiteaCommitStatusSchema = z
|
||||
.object({
|
||||
id: z.number(),
|
||||
status: z.string(),
|
||||
target_url: z.string().nullable().optional(),
|
||||
description: z.string().nullable().optional(),
|
||||
url: z.string().nullable().optional(),
|
||||
context: z.string().optional().default(""),
|
||||
creator: z.unknown().nullable().optional(),
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
const GiteaCombinedCommitStatusSchema = z
|
||||
.object({
|
||||
state: z.string().optional().default(""),
|
||||
sha: z.string().optional(),
|
||||
total_count: z.number().optional(),
|
||||
statuses: z.array(GiteaCommitStatusSchema).optional().default([]),
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
const GiteaActionTaskSchema = z
|
||||
.object({
|
||||
id: z.number(),
|
||||
name: z.string().nullable().optional(),
|
||||
head_branch: z.string().nullable().optional(),
|
||||
head_sha: z.string(),
|
||||
run_number: z.number().optional(),
|
||||
event: z.string().nullable().optional(),
|
||||
display_title: z.string().nullable().optional(),
|
||||
status: z.string(),
|
||||
need_approval: z.boolean().optional().default(false),
|
||||
workflow_id: z.string().nullable().optional(),
|
||||
url: z.string().nullable().optional(),
|
||||
created_at: z.string().nullable().optional(),
|
||||
run_started_at: z.string().nullable().optional(),
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
// The item shape is validated per-task rather than as `z.array(GiteaActionTaskSchema)`
|
||||
// so one malformed task (missing id/status/head_sha) drops only itself instead of
|
||||
// throwing out the whole page and zeroing every Actions check for the PR.
|
||||
const GiteaActionsListResponseSchema = z
|
||||
.object({
|
||||
workflow_runs: z.array(z.unknown()).optional().default([]),
|
||||
total_count: z.number().optional(),
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
const GiteaActionRunPullRequestRefSchema = z
|
||||
.object({
|
||||
repo: z.object({ id: z.number().optional() }).passthrough().nullable().optional(),
|
||||
@@ -368,6 +410,9 @@ type GiteaPrListItem = z.infer<typeof GiteaPrListItemSchema>;
|
||||
type GiteaIssueListItem = z.infer<typeof GiteaIssueListItemSchema>;
|
||||
type GiteaPullRequestView = z.infer<typeof GiteaPullRequestViewSchema>;
|
||||
type GiteaCurrentPullRequestApi = z.infer<typeof GiteaCurrentPullRequestApiSchema>;
|
||||
type GiteaCommitStatus = z.infer<typeof GiteaCommitStatusSchema>;
|
||||
type GiteaCombinedCommitStatus = z.infer<typeof GiteaCombinedCommitStatusSchema>;
|
||||
type GiteaActionTask = z.infer<typeof GiteaActionTaskSchema>;
|
||||
type GiteaIssueComment = z.infer<typeof GiteaIssueCommentSchema>;
|
||||
type GiteaReview = z.infer<typeof GiteaReviewSchema>;
|
||||
type GiteaReviewComment = z.infer<typeof GiteaReviewCommentSchema>;
|
||||
@@ -752,6 +797,10 @@ function deriveGiteaActionRequiredRunIds(runs: unknown[], sha: string): Set<numb
|
||||
return runIds;
|
||||
}
|
||||
|
||||
function getGiteaActionTaskName(task: GiteaActionTask): string {
|
||||
return task.name || task.display_title || task.workflow_id || `actions-${task.id}`;
|
||||
}
|
||||
|
||||
function toGiteaActionTaskCheck(task: GiteaActionTask): PullRequestCheck {
|
||||
const rawStatus = task.status.toLowerCase();
|
||||
return {
|
||||
@@ -765,6 +814,136 @@ function toGiteaActionTaskCheck(task: GiteaActionTask): PullRequestCheck {
|
||||
};
|
||||
}
|
||||
|
||||
function getGiteaActionWorkflowIdentity(task: GiteaActionTask): string {
|
||||
if (task.workflow_id) {
|
||||
return `workflow\u0000${task.workflow_id}`;
|
||||
}
|
||||
// Instances that omit workflow_id (older Gitea/Forgejo payloads) still need
|
||||
// reruns of the same job collapsed to the latest execution, so fall back to
|
||||
// the job name before treating the task as its own group.
|
||||
const name = task.name || task.display_title;
|
||||
if (name) {
|
||||
return `name\u0000${name}`;
|
||||
}
|
||||
return `task\u0000${getGiteaActionExecutionIdentity(task)}`;
|
||||
}
|
||||
|
||||
function getGiteaActionExecutionIdentity(task: GiteaActionTask): string {
|
||||
if (task.run_number !== undefined) return `run-number\u0000${task.run_number}`;
|
||||
const runId = getGiteaActionRunIdFromUrl(task.url);
|
||||
if (runId !== null) return `run-id\u0000${runId}`;
|
||||
if (task.url) return `url\u0000${task.url}`;
|
||||
return `task\u0000${task.id}`;
|
||||
}
|
||||
|
||||
function parseGiteaActionTaskTime(task: GiteaActionTask): number {
|
||||
const timestamp = task.created_at ?? task.run_started_at ?? null;
|
||||
if (!timestamp) {
|
||||
return 0;
|
||||
}
|
||||
const time = Date.parse(timestamp);
|
||||
return Number.isNaN(time) ? 0 : time;
|
||||
}
|
||||
|
||||
function compareGiteaActionTaskRecency(left: GiteaActionTask, right: GiteaActionTask): number {
|
||||
const leftRunNumber = left.run_number ?? 0;
|
||||
const rightRunNumber = right.run_number ?? 0;
|
||||
if (leftRunNumber !== rightRunNumber) {
|
||||
return leftRunNumber - rightRunNumber;
|
||||
}
|
||||
|
||||
const leftTime = parseGiteaActionTaskTime(left);
|
||||
const rightTime = parseGiteaActionTaskTime(right);
|
||||
if (leftTime !== rightTime) {
|
||||
return leftTime - rightTime;
|
||||
}
|
||||
|
||||
return left.id - right.id;
|
||||
}
|
||||
|
||||
function parseGiteaActionTasks(rawTasks: unknown[]): GiteaActionTask[] {
|
||||
const tasks: GiteaActionTask[] = [];
|
||||
for (const raw of rawTasks) {
|
||||
const parsed = GiteaActionTaskSchema.safeParse(raw);
|
||||
if (parsed.success) {
|
||||
tasks.push(parsed.data);
|
||||
}
|
||||
}
|
||||
return tasks;
|
||||
}
|
||||
|
||||
function latestGiteaActionTasksByWorkflow(tasks: GiteaActionTask[]): GiteaActionTask[] {
|
||||
const latestExecutions = new Map<string, GiteaActionTask>();
|
||||
for (const task of tasks) {
|
||||
const identity = getGiteaActionWorkflowIdentity(task);
|
||||
const current = latestExecutions.get(identity);
|
||||
if (!current || compareGiteaActionTaskRecency(current, task) < 0) {
|
||||
latestExecutions.set(identity, task);
|
||||
}
|
||||
}
|
||||
return tasks.filter((task) => {
|
||||
const latest = latestExecutions.get(getGiteaActionWorkflowIdentity(task));
|
||||
return (
|
||||
latest !== undefined &&
|
||||
getGiteaActionExecutionIdentity(task) === getGiteaActionExecutionIdentity(latest)
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
function getUrlOrigin(value: string | null | undefined): string | null {
|
||||
if (!value) return null;
|
||||
try {
|
||||
return new URL(value).origin;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
const GITEA_RELATIVE_URL_ORIGIN = "https://gitea.invalid";
|
||||
|
||||
function getGiteaActionRunIdFromUrl(value: string | null | undefined): number | null {
|
||||
if (!value) return null;
|
||||
try {
|
||||
const url = new URL(value, GITEA_RELATIVE_URL_ORIGIN);
|
||||
const match = url.pathname.match(/\/actions\/runs\/(\d+)(?:\/jobs\/\d+)?\/?$/);
|
||||
return match?.[1] ? Number.parseInt(match[1], 10) : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function isNativeActionJobUrl(
|
||||
targetUrl: string | null | undefined,
|
||||
nativeOrigins: ReadonlySet<string>,
|
||||
nativeRunIds: ReadonlySet<number>,
|
||||
): boolean {
|
||||
if (!targetUrl) return false;
|
||||
try {
|
||||
const url = new URL(targetUrl, GITEA_RELATIVE_URL_ORIGIN);
|
||||
if (!/\/actions\/runs\/\d+\/jobs\/\d+\/?$/.test(url.pathname)) return false;
|
||||
if (url.origin !== GITEA_RELATIVE_URL_ORIGIN && !nativeOrigins.has(url.origin)) return false;
|
||||
const runId = getGiteaActionRunIdFromUrl(targetUrl);
|
||||
return runId !== null && nativeRunIds.has(runId);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// A "shadow" is the commit status Gitea synthesizes to mirror one of its own
|
||||
// Actions jobs; keeping both would double-report every job. Detection is purely
|
||||
// structural: Gitea always creates these statuses with a target_url of the form
|
||||
// "<run link>/jobs/<job id>" (services/actions/commit_status.go upstream), so a
|
||||
// status is a shadow exactly when its URL points at a job of a run we actually
|
||||
// fetched from the Actions API. Anything else - external CI, URL-less statuses,
|
||||
// contexts that merely look like "<workflow> / <job> (<event>)" - is kept.
|
||||
function isGiteaActionShadowStatus(
|
||||
status: GiteaCommitStatus,
|
||||
nativeOrigins: ReadonlySet<string>,
|
||||
nativeRunIds: ReadonlySet<number>,
|
||||
): boolean {
|
||||
return isNativeActionJobUrl(status.target_url, nativeOrigins, nativeRunIds);
|
||||
}
|
||||
|
||||
function combineGiteaChecks(
|
||||
commitStatuses: GiteaCommitStatus[],
|
||||
actionTasks: GiteaActionTask[],
|
||||
@@ -1040,6 +1219,32 @@ export async function probeGiteaHost(host: string): Promise<boolean> {
|
||||
}
|
||||
}
|
||||
|
||||
function findTeaLoginNameForHost(stdout: string, host: string): string | null {
|
||||
let data: unknown;
|
||||
try {
|
||||
data = JSON.parse(stdout);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
const parsed = z.array(GiteaLoginSchema).safeParse(data);
|
||||
if (!parsed.success) {
|
||||
return null;
|
||||
}
|
||||
const target = host.toLowerCase();
|
||||
const match = parsed.data.find((login) => {
|
||||
const candidates = [login.ssh_host, login.name];
|
||||
if (login.url) {
|
||||
try {
|
||||
candidates.push(new URL(login.url).hostname);
|
||||
} catch {
|
||||
// ignore malformed login url
|
||||
}
|
||||
}
|
||||
return candidates.some((candidate) => candidate?.toLowerCase() === target);
|
||||
});
|
||||
return match?.name ?? null;
|
||||
}
|
||||
|
||||
function hostHasLogin(stdout: string, host: string): boolean {
|
||||
return findTeaLoginNameForHost(stdout, host) !== null;
|
||||
}
|
||||
@@ -1204,35 +1409,19 @@ export function createGiteaService(options: CreateGiteaServiceOptions = {}): For
|
||||
const now = options.now ?? Date.now;
|
||||
const currentPrHeadShaCache = new Map<string, { sha: string; expiresAt: number }>();
|
||||
|
||||
async function runRaw(
|
||||
args: string[],
|
||||
runOptions: TeaCommandRunnerOptions,
|
||||
): Promise<TeaCommandResult> {
|
||||
async function run(args: string[], runOptions: TeaCommandRunnerOptions): Promise<string> {
|
||||
const teaPath = await resolveTea();
|
||||
if (!teaPath) {
|
||||
throw new TeaCliMissingError();
|
||||
}
|
||||
try {
|
||||
return await runner(args, runOptions);
|
||||
const result = await runner(args, runOptions);
|
||||
return result.stdout.trim();
|
||||
} catch (error) {
|
||||
throw teaCliRunner.normalizeError(error, { args: redactTeaArgs(args), cwd: runOptions.cwd });
|
||||
}
|
||||
}
|
||||
|
||||
async function run(args: string[], runOptions: TeaCommandRunnerOptions): Promise<string> {
|
||||
const result = await runRaw(args, runOptions);
|
||||
return result.stdout.trim();
|
||||
}
|
||||
|
||||
const changeRequests = createGiteaChangeRequestSource({
|
||||
runCommand: runRaw,
|
||||
createAuthError: (stderr) => new TeaAuthenticationError({ stderr }),
|
||||
createCommandError: (params) => new TeaCommandError(params),
|
||||
now,
|
||||
pollIntervalMs: options.watchPollMs,
|
||||
initialDelayMs: options.watchInitialDelayMs,
|
||||
});
|
||||
|
||||
function runJsonParse<T>(
|
||||
args: string[],
|
||||
runOptions: TeaCommandRunnerOptions,
|
||||
@@ -2170,8 +2359,6 @@ export function createGiteaService(options: CreateGiteaServiceOptions = {}): For
|
||||
return notSupported("disablePullRequestAutoMerge");
|
||||
},
|
||||
|
||||
changeRequests,
|
||||
|
||||
invalidate(input: { cwd: string }): void {
|
||||
const prefix = `${input.cwd}:`;
|
||||
for (const key of currentPrHeadShaCache.keys()) {
|
||||
@@ -2180,9 +2367,5 @@ export function createGiteaService(options: CreateGiteaServiceOptions = {}): For
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
dispose(): void {
|
||||
changeRequests.dispose();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,917 +0,0 @@
|
||||
import { z } from "zod";
|
||||
import { normalizeHost } from "@getpaseo/protocol/git-remote";
|
||||
import { GITLAB_ACTIVE_PIPELINE_STATUS_SET } from "@getpaseo/protocol/gitlab-pipeline";
|
||||
import {
|
||||
ChangeRequestRateLimitError,
|
||||
createPerHostChangeRequestPoller,
|
||||
parseCliHttpResponse,
|
||||
parseRetryAfterMs,
|
||||
type PerHostReadContext,
|
||||
} from "./change-request-poller.js";
|
||||
import type { ChangeRequestSnapshot, ChangeRequestSource } from "./change-request-source.js";
|
||||
|
||||
const GITLAB_CLOUD_HOST = "gitlab.com";
|
||||
const GITLAB_PAGE_SIZE = 100;
|
||||
const GITLAB_MR_TABS = new Set(["diffs", "commits", "pipelines", "builds", "reports"]);
|
||||
|
||||
const checkUrlSchema = z.url({ protocol: /^https?$/ });
|
||||
|
||||
const gitLabWatchPipelineSchema = z
|
||||
.object({
|
||||
id: z.number(),
|
||||
project_id: z.number().nullable().optional(),
|
||||
sha: z.string().nullable().optional(),
|
||||
status: z.string(),
|
||||
web_url: z.string().nullable().optional(),
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
const gitLabWatchMrSchema = z
|
||||
.object({
|
||||
iid: z.number(),
|
||||
state: z.string(),
|
||||
sha: z.string().nullable().optional(),
|
||||
diff_refs: z
|
||||
.object({
|
||||
head_sha: z.string().nullable().optional(),
|
||||
})
|
||||
.passthrough()
|
||||
.nullable()
|
||||
.optional(),
|
||||
web_url: checkUrlSchema,
|
||||
target_project_id: z.number().nullable().optional(),
|
||||
merged_at: z.string().nullable().optional(),
|
||||
head_pipeline: gitLabWatchPipelineSchema.nullable().optional(),
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
const gitLabWatchJobSchema = z
|
||||
.object({
|
||||
id: z.number(),
|
||||
name: z.string(),
|
||||
status: z.string(),
|
||||
allow_failure: z.boolean().optional(),
|
||||
web_url: z.string().nullable().optional(),
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
const gitLabWatchNoteAuthorSchema = z
|
||||
.object({
|
||||
username: z.string().optional(),
|
||||
name: z.string().optional(),
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
const gitLabWatchNoteSchema = z
|
||||
.object({
|
||||
id: z.number(),
|
||||
body: z.string().nullable().optional(),
|
||||
system: z.boolean().optional(),
|
||||
type: z.string().nullable().optional(),
|
||||
position: z.unknown().nullable().optional(),
|
||||
author: gitLabWatchNoteAuthorSchema.nullable().optional(),
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
const gitLabWatchDiscussionSchema = z
|
||||
.object({
|
||||
id: z.string(),
|
||||
notes: z.array(gitLabWatchNoteSchema).optional().default([]),
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
const gitLabWatchApprovalsSchema = z
|
||||
.object({
|
||||
approvals_required: z.number().nullable().optional(),
|
||||
approvals_left: z.number().nullable().optional(),
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
type GitLabWatchMr = z.infer<typeof gitLabWatchMrSchema>;
|
||||
type GitLabWatchJob = z.infer<typeof gitLabWatchJobSchema>;
|
||||
type GitLabWatchNote = z.infer<typeof gitLabWatchNoteSchema>;
|
||||
type GitLabWatchDiscussion = z.infer<typeof gitLabWatchDiscussionSchema>;
|
||||
type GitLabWatchApprovals = z.infer<typeof gitLabWatchApprovalsSchema>;
|
||||
|
||||
interface GitLabMergeRequestIdentity {
|
||||
protocol: "http:" | "https:";
|
||||
host: string;
|
||||
port: string;
|
||||
hostWithPort: string;
|
||||
projectPath: string;
|
||||
iid: number;
|
||||
}
|
||||
|
||||
function invalidGitLabUrl(): never {
|
||||
throw new Error("Enter a GitLab merge request URL.");
|
||||
}
|
||||
|
||||
function parseGitLabUrlOrigin(input: string): {
|
||||
protocol: "http:" | "https:";
|
||||
host: string;
|
||||
port: string;
|
||||
hostWithPort: string;
|
||||
pathname: string;
|
||||
} {
|
||||
const trimmed = input.trim();
|
||||
if (!trimmed || /\s/.test(trimmed)) invalidGitLabUrl();
|
||||
let parsed: URL;
|
||||
try {
|
||||
parsed = new URL(trimmed);
|
||||
} catch {
|
||||
invalidGitLabUrl();
|
||||
}
|
||||
const protocol = parsed.protocol.toLowerCase();
|
||||
if ((protocol !== "https:" && protocol !== "http:") || parsed.username || parsed.password) {
|
||||
invalidGitLabUrl();
|
||||
}
|
||||
const host = normalizeHost(parsed.hostname);
|
||||
if (!host || (host === GITLAB_CLOUD_HOST && protocol !== "https:")) {
|
||||
invalidGitLabUrl();
|
||||
}
|
||||
return {
|
||||
protocol: protocol as "http:" | "https:",
|
||||
host,
|
||||
port: parsed.port,
|
||||
hostWithPort: parsed.port ? `${host}:${parsed.port}` : host,
|
||||
pathname: parsed.pathname,
|
||||
};
|
||||
}
|
||||
|
||||
function decodeGitLabProjectPath(rawSegments: string[]): string {
|
||||
if (rawSegments.length < 2) invalidGitLabUrl();
|
||||
const decodedSegments: string[] = [];
|
||||
for (const segment of rawSegments) {
|
||||
let decoded: string;
|
||||
try {
|
||||
decoded = decodeURIComponent(segment);
|
||||
} catch {
|
||||
invalidGitLabUrl();
|
||||
}
|
||||
const invalidSegment =
|
||||
!decoded ||
|
||||
decoded === "." ||
|
||||
decoded === ".." ||
|
||||
decoded === "-" ||
|
||||
decoded.includes("/") ||
|
||||
decoded.includes("\\");
|
||||
if (invalidSegment) invalidGitLabUrl();
|
||||
decodedSegments.push(decoded);
|
||||
}
|
||||
return decodedSegments.join("/");
|
||||
}
|
||||
|
||||
function parseGitLabMergeRequestUrl(input: string): GitLabMergeRequestIdentity {
|
||||
const origin = parseGitLabUrlOrigin(input);
|
||||
const rawSegments = origin.pathname.split("/").filter((segment) => segment.length > 0);
|
||||
if (rawSegments.length < 4) invalidGitLabUrl();
|
||||
|
||||
// Strip an optional browser tab suffix (e.g. /diffs, /commits, /pipelines).
|
||||
if (
|
||||
rawSegments.length >= 5 &&
|
||||
GITLAB_MR_TABS.has(rawSegments[rawSegments.length - 1]!.toLowerCase()) &&
|
||||
/^\d+$/.test(rawSegments[rawSegments.length - 2]!)
|
||||
) {
|
||||
rawSegments.pop();
|
||||
}
|
||||
|
||||
const iidRaw = rawSegments.pop();
|
||||
const resource = rawSegments.pop();
|
||||
if (!iidRaw || !/^\d+$/.test(iidRaw) || resource?.toLowerCase() !== "merge_requests") {
|
||||
invalidGitLabUrl();
|
||||
}
|
||||
const iid = Number(iidRaw);
|
||||
if (!Number.isInteger(iid) || iid < 1 || iid > 2_147_483_647) {
|
||||
invalidGitLabUrl();
|
||||
}
|
||||
|
||||
// Modern GitLab URLs place `-` before `merge_requests`; legacy URLs omit it.
|
||||
if (rawSegments[rawSegments.length - 1] === "-") {
|
||||
rawSegments.pop();
|
||||
}
|
||||
|
||||
return {
|
||||
protocol: origin.protocol,
|
||||
host: origin.host,
|
||||
port: origin.port,
|
||||
hostWithPort: origin.hostWithPort,
|
||||
projectPath: decodeGitLabProjectPath(rawSegments),
|
||||
iid,
|
||||
};
|
||||
}
|
||||
|
||||
export function resolveGitLabChangeRequest(input: string): string {
|
||||
const { protocol, hostWithPort, projectPath, iid } = parseGitLabMergeRequestUrl(input);
|
||||
return `${protocol}//${hostWithPort}/${projectPath}/-/merge_requests/${iid}`;
|
||||
}
|
||||
|
||||
export function gitlabChangeRequestHost(url: string): string {
|
||||
return parseGitLabMergeRequestUrl(url).hostWithPort;
|
||||
}
|
||||
|
||||
export function describeGitLabChangeRequest(url: string): string {
|
||||
const { host, port, hostWithPort, projectPath, iid } = parseGitLabMergeRequestUrl(url);
|
||||
const project =
|
||||
host === GITLAB_CLOUD_HOST && !port ? projectPath : `${hostWithPort}/${projectPath}`;
|
||||
return `${project} !${iid}`;
|
||||
}
|
||||
|
||||
function mapGitLabMrState(mr: GitLabWatchMr): ChangeRequestSnapshot["state"] {
|
||||
const state = mr.state.toLowerCase();
|
||||
// GitLab reports "locked" while a merge is actively in progress; treat it as
|
||||
// open so polling continues until GitLab transitions to "merged" (or "closed").
|
||||
if (state === "opened" || state === "locked") return "open";
|
||||
if (state === "merged" || mr.merged_at != null) return "merged";
|
||||
return "closed";
|
||||
}
|
||||
|
||||
function mapGitLabPipelineState(
|
||||
status: string | null | undefined,
|
||||
): ChangeRequestSnapshot["checksState"] {
|
||||
if (!status) return "neutral";
|
||||
const normalized = status.toLowerCase();
|
||||
if (normalized === "success" || normalized === "passed") return "passed";
|
||||
if (normalized === "failed") return "failed";
|
||||
if (normalized === "manual" || GITLAB_ACTIVE_PIPELINE_STATUS_SET.has(normalized)) {
|
||||
return "pending";
|
||||
}
|
||||
return "neutral";
|
||||
}
|
||||
|
||||
function mapGitLabJobState(job: GitLabWatchJob): ChangeRequestSnapshot["checks"][number]["state"] {
|
||||
const raw = job.status.toLowerCase();
|
||||
const allowFailure = job.allow_failure ?? false;
|
||||
if (raw === "failed") return allowFailure ? "neutral" : "failed";
|
||||
if (raw === "success" || raw === "passed") return "passed";
|
||||
if (raw === "manual") return allowFailure ? "neutral" : "pending";
|
||||
if (GITLAB_ACTIVE_PIPELINE_STATUS_SET.has(raw)) return "pending";
|
||||
return "neutral";
|
||||
}
|
||||
|
||||
function toWatchCheck(
|
||||
job: GitLabWatchJob,
|
||||
prefix: "job" | "bridge",
|
||||
): ChangeRequestSnapshot["checks"][number] {
|
||||
const url = checkUrlSchema.safeParse(job.web_url).data;
|
||||
return {
|
||||
id: `${prefix}:${job.id}`,
|
||||
name: job.name,
|
||||
state: mapGitLabJobState(job),
|
||||
...(url ? { url } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
type ApprovalNoteAction = "approved" | "unapproved" | "reset";
|
||||
|
||||
interface ParsedApprovalNote {
|
||||
id: string;
|
||||
action: ApprovalNoteAction;
|
||||
actor: string | null;
|
||||
url: string;
|
||||
}
|
||||
|
||||
function parseGitLabApprovalNote(
|
||||
note: GitLabWatchNote,
|
||||
mrWebUrl: string,
|
||||
): ParsedApprovalNote | null {
|
||||
if (note.system !== true) return null;
|
||||
const body = note.body?.trim().toLowerCase() ?? "";
|
||||
if (!body) return null;
|
||||
|
||||
let action: ApprovalNoteAction | null = null;
|
||||
if (body === "approved this merge request" || body.startsWith("approved this merge request")) {
|
||||
action = "approved";
|
||||
} else if (
|
||||
body === "unapproved this merge request" ||
|
||||
body.startsWith("unapproved this merge request") ||
|
||||
body.startsWith("removed approval") ||
|
||||
body.startsWith("revoked approval")
|
||||
) {
|
||||
action = "unapproved";
|
||||
} else if (body.startsWith("reset approvals")) {
|
||||
action = "reset";
|
||||
}
|
||||
if (!action) return null;
|
||||
|
||||
const actor = note.author?.username?.trim() || note.author?.name?.trim() || null;
|
||||
return {
|
||||
id: `approval-note:${note.id}`,
|
||||
action,
|
||||
actor,
|
||||
url: `${mrWebUrl}#note_${note.id}`,
|
||||
};
|
||||
}
|
||||
|
||||
interface ApprovalCount {
|
||||
given: number;
|
||||
required: number;
|
||||
}
|
||||
|
||||
function summarizeApprovalCount(approvals: GitLabWatchApprovals): ApprovalCount | null {
|
||||
const { approvals_required: required, approvals_left: remaining } = approvals;
|
||||
if (required == null || remaining == null) return null;
|
||||
return { given: Math.max(0, required - remaining), required };
|
||||
}
|
||||
|
||||
function formatApprovalCount(summary: ApprovalCount | null): string {
|
||||
if (!summary || summary.required <= 0) return "";
|
||||
return ` (${summary.given}/${summary.required} approvals)`;
|
||||
}
|
||||
|
||||
function formatApprovalActor(actor: string | null): string {
|
||||
if (!actor) return "";
|
||||
return actor.startsWith("@") ? actor : `@${actor}`;
|
||||
}
|
||||
|
||||
function formatApprovalNoteMessage(
|
||||
note: ParsedApprovalNote,
|
||||
summary: ApprovalCount | null,
|
||||
): string {
|
||||
const actor = formatApprovalActor(note.actor);
|
||||
const count = formatApprovalCount(summary);
|
||||
if (note.action === "approved") {
|
||||
return `Merge request approved${actor ? ` by ${actor}` : ""}${count}: ${note.url}`;
|
||||
}
|
||||
if (note.action === "unapproved") {
|
||||
return `Merge request approval removed${actor ? ` by ${actor}` : ""}${count}: ${note.url}`;
|
||||
}
|
||||
return `Merge request approvals reset${actor ? ` by ${actor}` : ""}${count}: ${note.url}`;
|
||||
}
|
||||
|
||||
interface ParsedDiscussionItems {
|
||||
humanActivity: ChangeRequestSnapshot["activity"];
|
||||
approvalNotes: ParsedApprovalNote[];
|
||||
}
|
||||
|
||||
function parseDiscussionItems(
|
||||
discussions: GitLabWatchDiscussion[],
|
||||
mrWebUrl: string,
|
||||
): ParsedDiscussionItems {
|
||||
const humanActivity: ChangeRequestSnapshot["activity"] = [];
|
||||
const approvalNotes: ParsedApprovalNote[] = [];
|
||||
|
||||
for (const discussion of discussions) {
|
||||
for (const note of discussion.notes) {
|
||||
if (note.system === true) {
|
||||
const approvalNote = parseGitLabApprovalNote(note, mrWebUrl);
|
||||
if (approvalNote) approvalNotes.push(approvalNote);
|
||||
continue;
|
||||
}
|
||||
const isInline = note.position != null || note.type === "DiffNote";
|
||||
humanActivity.push({
|
||||
id: isInline ? `inline:${note.id}` : `comment:${note.id}`,
|
||||
kind: isInline ? "inline comment" : "comment",
|
||||
url: `${mrWebUrl}#note_${note.id}`,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return { humanActivity, approvalNotes };
|
||||
}
|
||||
|
||||
function resolvePipelineProjectId(
|
||||
pipeline: z.infer<typeof gitLabWatchPipelineSchema>,
|
||||
mr: GitLabWatchMr,
|
||||
encodedProject: string,
|
||||
): string {
|
||||
if (pipeline.project_id != null) return String(pipeline.project_id);
|
||||
if (mr.target_project_id != null) return String(mr.target_project_id);
|
||||
return encodedProject;
|
||||
}
|
||||
|
||||
function pipelineFailureCheck(
|
||||
pipeline: z.infer<typeof gitLabWatchPipelineSchema>,
|
||||
): ChangeRequestSnapshot["checks"][number] {
|
||||
const url = checkUrlSchema.safeParse(pipeline.web_url).data;
|
||||
return {
|
||||
id: `pipeline:${pipeline.id}`,
|
||||
name: `Pipeline #${pipeline.id}`,
|
||||
state: "failed",
|
||||
...(url ? { url } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function createRateLimitError(
|
||||
host: string,
|
||||
nowMs: number,
|
||||
headers: ReadonlyMap<string, string>,
|
||||
): ChangeRequestRateLimitError {
|
||||
const resetAtMs = parseRetryAfterMs(headers, nowMs, {
|
||||
forceOnMissing: true,
|
||||
defaultPauseMs: 60_000,
|
||||
})!;
|
||||
return new ChangeRequestRateLimitError({ host, resetAtMs });
|
||||
}
|
||||
|
||||
function extractRateLimitFromFailedCommand(
|
||||
host: string,
|
||||
nowMs: number,
|
||||
status: number | null,
|
||||
headers: ReadonlyMap<string, string>,
|
||||
text: string,
|
||||
): ChangeRequestRateLimitError | null {
|
||||
if (status !== null) {
|
||||
return status === 429 ? createRateLimitError(host, nowMs, headers) : null;
|
||||
}
|
||||
if (!/\b(429|too many requests|rate limit)\b/i.test(text)) return null;
|
||||
return createRateLimitError(host, nowMs, headers);
|
||||
}
|
||||
|
||||
export interface CreateGitLabChangeRequestSourceOptions {
|
||||
runCommand(
|
||||
args: string[],
|
||||
options: { cwd: string; envOverlay?: Record<string, string> },
|
||||
): Promise<{ stdout: string; stderr: string }>;
|
||||
isAuthError(error: unknown): boolean;
|
||||
isCommandError(error: unknown): error is Error & { stderr: string; stdout?: string };
|
||||
createAuthError(stderr: string): Error;
|
||||
createCommandError(params: {
|
||||
args: string[];
|
||||
cwd: string;
|
||||
exitCode: number | null;
|
||||
stderr: string;
|
||||
stdout?: string;
|
||||
}): Error;
|
||||
now?: () => number;
|
||||
pollIntervalMs?: number;
|
||||
initialDelayMs?: number;
|
||||
}
|
||||
|
||||
export function createGitLabChangeRequestSource(
|
||||
options: CreateGitLabChangeRequestSourceOptions,
|
||||
): ChangeRequestSource & { dispose(): void } {
|
||||
const now = options.now ?? Date.now;
|
||||
|
||||
async function readConfig(
|
||||
host: string,
|
||||
key: string,
|
||||
envOverlay: Record<string, string> = {},
|
||||
): Promise<string> {
|
||||
const config = await options.runCommand(["config", "get", key, "--host", host], {
|
||||
cwd: process.cwd(),
|
||||
envOverlay: { GITLAB_HOST: host, ...envOverlay },
|
||||
});
|
||||
return config.stdout.trim();
|
||||
}
|
||||
|
||||
async function preferredProfileHost(identity: GitLabMergeRequestIdentity): Promise<string> {
|
||||
const { host, hostWithPort } = identity;
|
||||
if (hostWithPort === host) return host;
|
||||
|
||||
// An API host override applies to either profile. Use the configured value
|
||||
// to decide which profile to try first, then check access through the MR.
|
||||
const exactProfile = await readConfig(hostWithPort, "api_host", { GITLAB_API_HOST: "" });
|
||||
return exactProfile ? hostWithPort : host;
|
||||
}
|
||||
|
||||
async function readApiPrefix(profileHost: string): Promise<string> {
|
||||
if (profileHost === GITLAB_CLOUD_HOST) return "";
|
||||
const trimSlashes = /^\/+|\/+$/g;
|
||||
let prefix = (await readConfig(profileHost, "subfolder")).replace(trimSlashes, "");
|
||||
if (!prefix) {
|
||||
const apiHost = await readConfig(profileHost, "api_host");
|
||||
if (apiHost) {
|
||||
const apiUrl = new URL(apiHost.includes("://") ? apiHost : `https://${apiHost}`);
|
||||
prefix = apiUrl.pathname.replace(trimSlashes, "");
|
||||
}
|
||||
}
|
||||
return decodeURI(prefix);
|
||||
}
|
||||
|
||||
function parseJsonResponseBody<T>(params: {
|
||||
args: string[];
|
||||
cwd: string;
|
||||
body: string;
|
||||
schema: z.ZodType<T>;
|
||||
}): T {
|
||||
let json: unknown;
|
||||
try {
|
||||
json = JSON.parse(params.body);
|
||||
} catch {
|
||||
throw options.createCommandError({
|
||||
args: params.args,
|
||||
cwd: params.cwd,
|
||||
exitCode: null,
|
||||
stderr: `glab did not return valid JSON (${params.body.length} bytes)`,
|
||||
});
|
||||
}
|
||||
const validated = params.schema.safeParse(json);
|
||||
if (!validated.success) {
|
||||
throw options.createCommandError({
|
||||
args: params.args,
|
||||
cwd: params.cwd,
|
||||
exitCode: null,
|
||||
stderr: `glab JSON did not match the expected schema: ${validated.error.message}`,
|
||||
});
|
||||
}
|
||||
return validated.data;
|
||||
}
|
||||
|
||||
function checkHttpStatus(params: {
|
||||
host: string;
|
||||
args: string[];
|
||||
cwd: string;
|
||||
status: number | null;
|
||||
headers: ReadonlyMap<string, string>;
|
||||
body: string;
|
||||
rawStdout: string;
|
||||
rawStderr: string;
|
||||
pauseHost(untilMs: number): void;
|
||||
}): void {
|
||||
// Only decide rate limits from the HTTP status code on parsed responses so
|
||||
// ordinary MR titles, comments, or IIDs mentioning "429" or "rate limit"
|
||||
// never trip a false rate-limit pause.
|
||||
if (params.status === null) return;
|
||||
if (params.status === 429) {
|
||||
const error = createRateLimitError(params.host, now(), params.headers);
|
||||
params.pauseHost(error.resetAtMs);
|
||||
throw error;
|
||||
}
|
||||
if (params.status === 401) {
|
||||
throw options.createAuthError(params.body || params.rawStderr || "401 Unauthorized");
|
||||
}
|
||||
if (params.status < 200 || params.status >= 300) {
|
||||
throw options.createCommandError({
|
||||
args: params.args,
|
||||
cwd: params.cwd,
|
||||
exitCode: null,
|
||||
stderr: `HTTP ${params.status}: ${params.body || params.rawStderr}`.trim(),
|
||||
stdout: params.rawStdout,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async function apiGet<T>(params: {
|
||||
host: string;
|
||||
endpoint: string;
|
||||
schema: z.ZodType<T>;
|
||||
poll: PerHostReadContext;
|
||||
}): Promise<{ data: T; headers: ReadonlyMap<string, string> }> {
|
||||
if (!params.poll.isObserved()) throw new Error("Change request observation ended");
|
||||
params.poll.assertHostAvailable();
|
||||
// glab api rejects a port in --hostname. GITLAB_HOST selects that profile.
|
||||
const args = params.host.includes(":")
|
||||
? ["api", "-i", params.endpoint]
|
||||
: ["api", "--hostname", params.host, "-i", params.endpoint];
|
||||
const cwd = process.cwd();
|
||||
let result: { stdout: string; stderr: string };
|
||||
try {
|
||||
result = await options.runCommand(args, {
|
||||
cwd,
|
||||
envOverlay: { GITLAB_HOST: params.host },
|
||||
});
|
||||
} catch (error) {
|
||||
if (options.isCommandError(error)) {
|
||||
const parsedError = error.stdout ? parseCliHttpResponse(error.stdout) : null;
|
||||
const rateLimit = extractRateLimitFromFailedCommand(
|
||||
params.host,
|
||||
now(),
|
||||
parsedError?.status ?? null,
|
||||
parsedError?.headers ?? new Map(),
|
||||
`${error.stderr}\n${error.stdout ?? ""}`,
|
||||
);
|
||||
if (rateLimit) {
|
||||
params.poll.pauseHost(rateLimit.resetAtMs);
|
||||
throw rateLimit;
|
||||
}
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
const parsed = parseCliHttpResponse(result.stdout);
|
||||
checkHttpStatus({
|
||||
host: params.host,
|
||||
args,
|
||||
cwd,
|
||||
status: parsed.status,
|
||||
headers: parsed.headers,
|
||||
body: parsed.body,
|
||||
rawStdout: result.stdout,
|
||||
rawStderr: result.stderr,
|
||||
pauseHost: params.poll.pauseHost,
|
||||
});
|
||||
|
||||
const proactivePause = parseRetryAfterMs(parsed.headers, now());
|
||||
if (proactivePause !== null) {
|
||||
params.poll.deferPollsUntil(proactivePause);
|
||||
}
|
||||
|
||||
const data = parseJsonResponseBody({ args, cwd, body: parsed.body, schema: params.schema });
|
||||
return { data, headers: parsed.headers };
|
||||
}
|
||||
|
||||
async function apiGetAllPages<T>(params: {
|
||||
host: string;
|
||||
endpoint: string;
|
||||
itemSchema: z.ZodType<T>;
|
||||
poll: PerHostReadContext;
|
||||
}): Promise<{ items: T[]; pagesRead: number }> {
|
||||
const items: T[] = [];
|
||||
const schema = z.array(params.itemSchema);
|
||||
const seenPages = new Set<number>([1]);
|
||||
let page = 1;
|
||||
let pagesRead = 0;
|
||||
|
||||
while (true) {
|
||||
if (!params.poll.isObserved()) {
|
||||
return { items, pagesRead };
|
||||
}
|
||||
const sep = params.endpoint.includes("?") ? "&" : "?";
|
||||
const response = await apiGet({
|
||||
host: params.host,
|
||||
endpoint: `${params.endpoint}${sep}per_page=${GITLAB_PAGE_SIZE}&page=${page}`,
|
||||
schema,
|
||||
poll: params.poll,
|
||||
});
|
||||
pagesRead += 1;
|
||||
items.push(...response.data);
|
||||
|
||||
const nextPageHeader = response.headers.get("x-next-page");
|
||||
if (nextPageHeader !== undefined) {
|
||||
const trimmed = nextPageHeader.trim();
|
||||
if (!trimmed) break;
|
||||
const nextPage = Number(trimmed);
|
||||
if (!Number.isInteger(nextPage) || nextPage <= 0 || seenPages.has(nextPage)) {
|
||||
throw new Error("GitLab returned an invalid pagination header.");
|
||||
}
|
||||
seenPages.add(nextPage);
|
||||
page = nextPage;
|
||||
} else {
|
||||
if (response.data.length < GITLAB_PAGE_SIZE) break;
|
||||
page += 1;
|
||||
seenPages.add(page);
|
||||
}
|
||||
}
|
||||
|
||||
return { items, pagesRead };
|
||||
}
|
||||
|
||||
function commandErrorStatus(error: unknown): number | null {
|
||||
return options.isCommandError(error) && error.stdout
|
||||
? parseCliHttpResponse(error.stdout).status
|
||||
: null;
|
||||
}
|
||||
|
||||
async function readMergeRequestMetadata(params: {
|
||||
host: string;
|
||||
identity: GitLabMergeRequestIdentity;
|
||||
endpoint: string;
|
||||
poll: PerHostReadContext;
|
||||
}): Promise<GitLabWatchMr> {
|
||||
const { data: mr } = await apiGet({
|
||||
host: params.host,
|
||||
endpoint: params.endpoint,
|
||||
schema: gitLabWatchMrSchema,
|
||||
poll: params.poll,
|
||||
});
|
||||
const address = parseGitLabMergeRequestUrl(mr.web_url);
|
||||
const expected = params.identity;
|
||||
if (address.protocol !== expected.protocol || address.hostWithPort !== expected.hostWithPort) {
|
||||
throw new Error(
|
||||
`GitLab returned a merge request from a different web origin: ${address.protocol}//${address.hostWithPort}`,
|
||||
);
|
||||
}
|
||||
if (address.projectPath.toLowerCase() !== expected.projectPath.toLowerCase()) {
|
||||
throw new Error("GitLab returned a merge request from a different project.");
|
||||
}
|
||||
if (address.iid !== expected.iid || mr.iid !== expected.iid) {
|
||||
throw new Error("GitLab returned a different merge request number.");
|
||||
}
|
||||
return mr;
|
||||
}
|
||||
|
||||
function pipelineDetailsUnavailable(error: unknown): boolean {
|
||||
const status = commandErrorStatus(error);
|
||||
return status === 403 || status === 404;
|
||||
}
|
||||
|
||||
async function readPipelineChecks(params: {
|
||||
host: string;
|
||||
identity: GitLabMergeRequestIdentity;
|
||||
mrEndpoint: string;
|
||||
encodedProject: string;
|
||||
mr: GitLabWatchMr;
|
||||
headSha: string;
|
||||
poll: PerHostReadContext;
|
||||
}): Promise<ChangeRequestSnapshot["checks"]> {
|
||||
const pipeline = params.mr.head_pipeline;
|
||||
if (!pipeline) return [];
|
||||
|
||||
const pipelineProject = resolvePipelineProjectId(pipeline, params.mr, params.encodedProject);
|
||||
let jobsResult: { items: GitLabWatchJob[]; pagesRead: number };
|
||||
try {
|
||||
jobsResult = await apiGetAllPages({
|
||||
host: params.host,
|
||||
endpoint: `projects/${pipelineProject}/pipelines/${pipeline.id}/jobs`,
|
||||
itemSchema: gitLabWatchJobSchema,
|
||||
poll: params.poll,
|
||||
});
|
||||
} catch (error) {
|
||||
if (!pipelineDetailsUnavailable(error)) throw error;
|
||||
// The MR can expose pipeline status even when its jobs are restricted.
|
||||
return mapGitLabPipelineState(pipeline.status) === "failed"
|
||||
? [pipelineFailureCheck(pipeline)]
|
||||
: [];
|
||||
}
|
||||
if (!params.poll.isObserved()) {
|
||||
throw new Error("Change request observation ended");
|
||||
}
|
||||
|
||||
const checks = jobsResult.items.map((job) => toWatchCheck(job, "job"));
|
||||
let fetchedBridges = false;
|
||||
if (
|
||||
mapGitLabPipelineState(pipeline.status) === "failed" &&
|
||||
!checks.some((check) => check.state === "failed")
|
||||
) {
|
||||
fetchedBridges = true;
|
||||
await appendFailedBridgeOrPipelineChecks({
|
||||
host: params.host,
|
||||
pipelineProject,
|
||||
pipeline,
|
||||
checks,
|
||||
poll: params.poll,
|
||||
});
|
||||
}
|
||||
|
||||
// Guard against headSha or head_pipeline shifting while paginating check pages.
|
||||
if (jobsResult.pagesRead > 1 || fetchedBridges) {
|
||||
const recheck = await readMergeRequestMetadata({
|
||||
host: params.host,
|
||||
identity: params.identity,
|
||||
endpoint: params.mrEndpoint,
|
||||
poll: params.poll,
|
||||
});
|
||||
const recheckSha = recheck.sha || recheck.diff_refs?.head_sha || "";
|
||||
if (
|
||||
recheckSha !== params.headSha ||
|
||||
recheck.head_pipeline?.id !== pipeline.id ||
|
||||
recheck.head_pipeline?.status !== pipeline.status
|
||||
) {
|
||||
throw new Error("The merge request head or pipeline changed during pagination.");
|
||||
}
|
||||
}
|
||||
return checks;
|
||||
}
|
||||
|
||||
async function appendFailedBridgeOrPipelineChecks(params: {
|
||||
host: string;
|
||||
pipelineProject: string;
|
||||
pipeline: z.infer<typeof gitLabWatchPipelineSchema>;
|
||||
checks: ChangeRequestSnapshot["checks"];
|
||||
poll: PerHostReadContext;
|
||||
}): Promise<void> {
|
||||
try {
|
||||
const bridgesResult = await apiGetAllPages({
|
||||
host: params.host,
|
||||
endpoint: `projects/${params.pipelineProject}/pipelines/${params.pipeline.id}/bridges`,
|
||||
itemSchema: gitLabWatchJobSchema,
|
||||
poll: params.poll,
|
||||
});
|
||||
for (const bridge of bridgesResult.items) {
|
||||
params.checks.push(toWatchCheck(bridge, "bridge"));
|
||||
}
|
||||
} catch (error) {
|
||||
if (!pipelineDetailsUnavailable(error)) throw error;
|
||||
}
|
||||
if (!params.checks.some((check) => check.state === "failed")) {
|
||||
params.checks.push(pipelineFailureCheck(params.pipeline));
|
||||
}
|
||||
}
|
||||
|
||||
async function readOptionalApprovalCount(params: {
|
||||
host: string;
|
||||
endpoint: string;
|
||||
poll: PerHostReadContext;
|
||||
}): Promise<ApprovalCount | null> {
|
||||
try {
|
||||
const { data: approvals } = await apiGet({
|
||||
host: params.host,
|
||||
endpoint: params.endpoint,
|
||||
schema: gitLabWatchApprovalsSchema,
|
||||
poll: params.poll,
|
||||
});
|
||||
return summarizeApprovalCount(approvals);
|
||||
} catch {
|
||||
// The approval system note is complete without an API count.
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async function readInitialMergeRequest(
|
||||
identity: GitLabMergeRequestIdentity,
|
||||
poll: PerHostReadContext,
|
||||
) {
|
||||
async function readUsing(host: string) {
|
||||
const { projectPath, iid } = identity;
|
||||
const prefix = await readApiPrefix(host);
|
||||
const relativePath =
|
||||
prefix && projectPath.startsWith(`${prefix}/`)
|
||||
? projectPath.slice(prefix.length + 1)
|
||||
: projectPath;
|
||||
const encodedProject = encodeURIComponent(
|
||||
relativePath.includes("/") ? relativePath : projectPath,
|
||||
);
|
||||
const mrEndpoint = `projects/${encodedProject}/merge_requests/${iid}`;
|
||||
const mr = await readMergeRequestMetadata({ host, identity, endpoint: mrEndpoint, poll });
|
||||
return { host, encodedProject, mrEndpoint, mr };
|
||||
}
|
||||
|
||||
const preferred = await preferredProfileHost(identity);
|
||||
try {
|
||||
return await readUsing(preferred);
|
||||
} catch (error) {
|
||||
const status = commandErrorStatus(error);
|
||||
const accessDenied = options.isAuthError(error) || status === 403 || status === 404;
|
||||
if (preferred === identity.host || !accessDenied) throw error;
|
||||
return readUsing(identity.host);
|
||||
}
|
||||
}
|
||||
|
||||
async function readMergeRequest(context: PerHostReadContext): Promise<ChangeRequestSnapshot> {
|
||||
const identity = parseGitLabMergeRequestUrl(context.url);
|
||||
const { iid } = identity;
|
||||
const { host, encodedProject, mrEndpoint, mr } = await readInitialMergeRequest(
|
||||
identity,
|
||||
context,
|
||||
);
|
||||
const headSha = mr.sha || mr.diff_refs?.head_sha || "";
|
||||
if (!headSha) {
|
||||
throw new Error(`GitLab merge request !${iid} did not include a head commit SHA.`);
|
||||
}
|
||||
|
||||
const checks = await readPipelineChecks({
|
||||
host,
|
||||
identity,
|
||||
mrEndpoint,
|
||||
encodedProject,
|
||||
mr,
|
||||
headSha,
|
||||
poll: context,
|
||||
});
|
||||
const discussionsResult = await apiGetAllPages({
|
||||
host,
|
||||
endpoint: `projects/${encodedProject}/merge_requests/${iid}/discussions`,
|
||||
itemSchema: gitLabWatchDiscussionSchema,
|
||||
poll: context,
|
||||
});
|
||||
if (!context.isObserved()) {
|
||||
throw new Error("Change request observation ended");
|
||||
}
|
||||
|
||||
const { humanActivity, approvalNotes } = parseDiscussionItems(
|
||||
discussionsResult.items,
|
||||
mr.web_url,
|
||||
);
|
||||
const known = context.knownActivity();
|
||||
const hasNewApprovalNote =
|
||||
known !== undefined && approvalNotes.some((note) => !known.has(note.id));
|
||||
// Fetch /approvals only to enrich a newly observed approval system note with
|
||||
// current counts — keeping seenActivity as the single persisted owner of
|
||||
// approval transition baselines.
|
||||
const approvalCount = hasNewApprovalNote
|
||||
? await readOptionalApprovalCount({
|
||||
host,
|
||||
endpoint: `projects/${encodedProject}/merge_requests/${iid}/approvals`,
|
||||
poll: context,
|
||||
})
|
||||
: null;
|
||||
|
||||
const activity: ChangeRequestSnapshot["activity"] = [
|
||||
...humanActivity,
|
||||
...approvalNotes.map((note) => ({
|
||||
id: note.id,
|
||||
kind: "approval" as const,
|
||||
url: note.url,
|
||||
message: formatApprovalNoteMessage(note, approvalCount),
|
||||
})),
|
||||
];
|
||||
|
||||
return {
|
||||
state: mapGitLabMrState(mr),
|
||||
headSha,
|
||||
checksState: mapGitLabPipelineState(mr.head_pipeline?.status),
|
||||
checks,
|
||||
reviewDecision: null,
|
||||
activity,
|
||||
};
|
||||
}
|
||||
|
||||
const poller = createPerHostChangeRequestPoller({
|
||||
hostOf: gitlabChangeRequestHost,
|
||||
read: readMergeRequest,
|
||||
now,
|
||||
pollIntervalMs: options.pollIntervalMs,
|
||||
initialDelayMs: options.initialDelayMs,
|
||||
});
|
||||
|
||||
return {
|
||||
resolve: resolveGitLabChangeRequest,
|
||||
describe: describeGitLabChangeRequest,
|
||||
observe(url, callbacks) {
|
||||
return poller.observe(url, callbacks);
|
||||
},
|
||||
dispose() {
|
||||
poller.dispose();
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -60,7 +60,6 @@ import {
|
||||
CHECK_TRAIT_WARNING,
|
||||
} from "@getpaseo/protocol/check-traits";
|
||||
import { GITLAB_ACTIVE_PIPELINE_STATUS_SET } from "@getpaseo/protocol/gitlab-pipeline";
|
||||
import { createGitLabChangeRequestSource } from "./gitlab-change-requests.js";
|
||||
import { isGitLabStatusFacts, type GitLabStatusFacts } from "./gitlab-facts.js";
|
||||
|
||||
const GLAB_ENV = {
|
||||
@@ -113,9 +112,6 @@ export interface CreateGitLabServiceOptions {
|
||||
runner?: GlabCommandRunner;
|
||||
resolveGlabPath?: () => Promise<string | null>;
|
||||
resolveRemoteUrl?: (cwd: string) => Promise<string | null>;
|
||||
now?: () => number;
|
||||
watchPollMs?: number;
|
||||
watchInitialDelayMs?: number;
|
||||
}
|
||||
|
||||
const GitLabPipelineSchema = z
|
||||
@@ -929,37 +925,19 @@ export function createGitLabService(options: CreateGitLabServiceOptions = {}): F
|
||||
const resolveGlab = createCachedCliPathResolver(options.resolveGlabPath ?? resolveGlabPath);
|
||||
const resolveRemoteUrl = options.resolveRemoteUrl ?? defaultResolveRemoteUrl;
|
||||
|
||||
async function runRaw(
|
||||
args: string[],
|
||||
runOptions: GlabCommandRunnerOptions,
|
||||
): Promise<GlabCommandResult> {
|
||||
async function run(args: string[], runOptions: GlabCommandRunnerOptions): Promise<string> {
|
||||
const glabPath = await resolveGlab();
|
||||
if (!glabPath) {
|
||||
throw new GlabCliMissingError();
|
||||
}
|
||||
try {
|
||||
return await runner(args, runOptions);
|
||||
const result = await runner(args, runOptions);
|
||||
return result.stdout.trim();
|
||||
} catch (error) {
|
||||
throw glabCliRunner.normalizeError(error, { args, cwd: runOptions.cwd });
|
||||
}
|
||||
}
|
||||
|
||||
async function run(args: string[], runOptions: GlabCommandRunnerOptions): Promise<string> {
|
||||
const result = await runRaw(args, runOptions);
|
||||
return result.stdout.trim();
|
||||
}
|
||||
|
||||
const changeRequests = createGitLabChangeRequestSource({
|
||||
runCommand: runRaw,
|
||||
isAuthError: (error) => error instanceof GlabAuthenticationError,
|
||||
isCommandError: (error): error is GlabCommandError => error instanceof GlabCommandError,
|
||||
createAuthError: (stderr) => new GlabAuthenticationError({ stderr }),
|
||||
createCommandError: (params) => new GlabCommandError(params),
|
||||
now: options.now,
|
||||
pollIntervalMs: options.watchPollMs,
|
||||
initialDelayMs: options.watchInitialDelayMs,
|
||||
});
|
||||
|
||||
// Centralize parse + validate so a malformed or empty glab payload surfaces as
|
||||
// a classified GlabCommandError (with args + cwd) instead of a raw
|
||||
// SyntaxError/ZodError that bypasses the Glab* error classification.
|
||||
@@ -1508,12 +1486,6 @@ export function createGitLabService(options: CreateGitLabServiceOptions = {}): F
|
||||
return { success: true };
|
||||
},
|
||||
|
||||
changeRequests,
|
||||
|
||||
invalidate(_input: { cwd: string }): void {},
|
||||
|
||||
dispose(): void {
|
||||
changeRequests.dispose();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -350,18 +350,10 @@ 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..021debd 100644
|
||||
index 2bac5b1..ff2d2c2 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
|
||||
@@ -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(
|
||||
@@ -16,7 +16,7 @@ class ListRenderer(
|
||||
override fun render(
|
||||
node: MarkdownASTNode,
|
||||
builder: SpannableStringBuilder,
|
||||
@@ -370,23 +362,6 @@ index 2bac5b1..021debd 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
|
||||
@@ -3031,18 +3006,10 @@ 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..6b7e61f 100644
|
||||
index f4840e4..e36b444 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
|
||||
@@ -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 {
|
||||
@@ -66,9 +66,11 @@ object MeasurementStore {
|
||||
val spannable: CharSequence?,
|
||||
val paintParams: PaintParams,
|
||||
val markdownHash: Int,
|
||||
@@ -3054,7 +3021,7 @@ index f4840e4..6b7e61f 100644
|
||||
|
||||
// Store font scaling settings per view ID
|
||||
private data class FontScalingSettings(
|
||||
@@ -133,7 +136,10 @@ object MeasurementStore {
|
||||
@@ -133,7 +135,10 @@ object MeasurementStore {
|
||||
YogaMeasureOutput.getHeight(newSize) + PixelUtil.toDIPFromPixel(trailingMarginBottomPx),
|
||||
)
|
||||
}
|
||||
@@ -3066,7 +3033,7 @@ index f4840e4..6b7e61f 100644
|
||||
return oldSize != newSize
|
||||
}
|
||||
|
||||
@@ -144,7 +150,7 @@ object MeasurementStore {
|
||||
@@ -144,7 +149,7 @@ object MeasurementStore {
|
||||
}
|
||||
|
||||
fun invalidate(id: Int) {
|
||||
@@ -3075,7 +3042,7 @@ index f4840e4..6b7e61f 100644
|
||||
}
|
||||
|
||||
// Content-box width (px) the measure pass last wrapped at; the display view insets to match (#805).
|
||||
@@ -212,7 +218,7 @@ object MeasurementStore {
|
||||
@@ -212,7 +217,7 @@ object MeasurementStore {
|
||||
val previous = fontScalingSettings[viewId]
|
||||
fontScalingSettings[viewId] = FontScalingSettings(allowFontScaling, maxFontSizeMultiplier)
|
||||
if (previous != null && (previous.allowFontScaling != allowFontScaling || previous.maxFontSizeMultiplier != maxFontSizeMultiplier)) {
|
||||
@@ -3084,7 +3051,7 @@ index f4840e4..6b7e61f 100644
|
||||
}
|
||||
}
|
||||
|
||||
@@ -285,7 +291,43 @@ object MeasurementStore {
|
||||
@@ -285,7 +290,43 @@ object MeasurementStore {
|
||||
|
||||
val fontScale = checkAndUpdateFontScale(context, allowFontScaling, maxFontSizeMultiplier)
|
||||
|
||||
@@ -3129,7 +3096,7 @@ index f4840e4..6b7e61f 100644
|
||||
if (splitTableSegments) {
|
||||
return measureAndCacheSplit(context, id, width, props, allowFontScaling, fontScale, maxFontSizeMultiplier)
|
||||
}
|
||||
@@ -295,7 +337,7 @@ object MeasurementStore {
|
||||
@@ -295,7 +336,7 @@ object MeasurementStore {
|
||||
|
||||
val currentHash = computePropsHash(props, allowFontScaling, fontScale, maxFontSizeMultiplier)
|
||||
|
||||
@@ -3138,7 +3105,7 @@ index f4840e4..6b7e61f 100644
|
||||
return measureAndCache(context, safeId, width, props, allowFontScaling, fontScale, maxFontSizeMultiplier)
|
||||
}
|
||||
|
||||
@@ -332,8 +374,11 @@ object MeasurementStore {
|
||||
@@ -332,8 +373,11 @@ object MeasurementStore {
|
||||
val imageRequestHeaders = parseImageRequestHeaders(props.getArrayOrNull("imageRequestHeaders"))
|
||||
val linkPillContent = parseLinkPillContent(props.getArrayOrNull("linkPillContent"))
|
||||
var result = markdown.hashCode()
|
||||
@@ -3152,7 +3119,7 @@ index f4840e4..6b7e61f 100644
|
||||
result = 31 * result + parseLinkRecognition(props.getMapOrNull("linkRecognition")).hashCode()
|
||||
result = 31 * result + fontScale.toBits()
|
||||
result = 31 * result + allowFontScaling.hashCode()
|
||||
@@ -356,6 +401,7 @@ object MeasurementStore {
|
||||
@@ -356,6 +400,7 @@ object MeasurementStore {
|
||||
if (lastKnownFontScale != 1.0f) {
|
||||
lastKnownFontScale = 1.0f
|
||||
data.clear()
|
||||
@@ -3160,7 +3127,7 @@ index f4840e4..6b7e61f 100644
|
||||
}
|
||||
return 1.0f
|
||||
}
|
||||
@@ -368,6 +414,7 @@ object MeasurementStore {
|
||||
@@ -368,6 +413,7 @@ object MeasurementStore {
|
||||
if (currentFontScale != lastKnownFontScale) {
|
||||
lastKnownFontScale = currentFontScale
|
||||
data.clear()
|
||||
@@ -3168,52 +3135,6 @@ index f4840e4..6b7e61f 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
|
||||
@@ -4075,290 +3996,3 @@ 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,17 +56,6 @@ function shortWindow(window: string): string {
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
function windowDurationSeconds(window: string): number | undefined {
|
||||
switch (window.trim().toLowerCase()) {
|
||||
case "5h":
|
||||
return 5 * 3600;
|
||||
case "weekly":
|
||||
return 7 * 86400;
|
||||
default:
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
function shortGroupName(name: string): string {
|
||||
return name
|
||||
.trim()
|
||||
@@ -140,7 +129,6 @@ export class Usage {
|
||||
shortLabel: formatShortLabel(group.name, bucket.window, includeGroup),
|
||||
summary: !bucket.disabled && bucket.window === "weekly",
|
||||
utilizationPct: used,
|
||||
durationSeconds: windowDurationSeconds(bucket.window),
|
||||
resetsAt: bucket.disabled ? null : bucket.reset_time,
|
||||
tone: used === null ? "default" : toneFromUsedPct(used),
|
||||
}),
|
||||
|
||||
@@ -263,7 +263,6 @@ function unscopedWindows(resp: ClaudeUsageResponse): UsageWindow[] {
|
||||
shortLabel: spec.shortLabel,
|
||||
summary: spec.summary,
|
||||
utilizationPct: window.utilization,
|
||||
durationSeconds: spec.field === "five_hour" ? 5 * 3600 : 7 * 86400,
|
||||
resetsAt: window.resets_at ?? null,
|
||||
tone: toneFromUsedPct(window.utilization),
|
||||
}),
|
||||
@@ -284,7 +283,6 @@ function scopedWindows(limits: ScopedLimit[]): UsageWindow[] {
|
||||
label: `Weekly \u00b7 ${limit.name}`,
|
||||
shortLabel: `wk ${limit.name}`,
|
||||
utilizationPct: limit.usedPct,
|
||||
durationSeconds: 7 * 86400,
|
||||
resetsAt: limit.resetsAt,
|
||||
tone: toneFromUsedPct(limit.usedPct),
|
||||
});
|
||||
|
||||
@@ -21,6 +21,7 @@ export class Children {
|
||||
private readonly parentId: string,
|
||||
private readonly cwd: string,
|
||||
private readonly emit: (event: ProviderEvent) => void,
|
||||
private readonly canProjectChild: () => boolean,
|
||||
) {}
|
||||
|
||||
async update(item: WireItem): Promise<void> {
|
||||
@@ -34,6 +35,7 @@ export class Children {
|
||||
)
|
||||
)
|
||||
return;
|
||||
if (!this.canProjectChild()) return;
|
||||
const id = item.childSessionId;
|
||||
if (!this.children.has(id)) {
|
||||
const { session } = await this.host.request(
|
||||
@@ -41,6 +43,8 @@ export class Children {
|
||||
{ sessionId: id },
|
||||
childSessionSchema,
|
||||
);
|
||||
// The parent can close while Muse reads the child.
|
||||
if (!this.canProjectChild()) return;
|
||||
this.emit({
|
||||
type: "session.opened",
|
||||
sessionId: id,
|
||||
|
||||
@@ -32,6 +32,7 @@ const capabilities = [
|
||||
"session.persistence",
|
||||
"permission",
|
||||
"session.list",
|
||||
"session.subsession",
|
||||
] as const;
|
||||
|
||||
export interface MuseProviderOptions {
|
||||
|
||||
@@ -142,7 +142,13 @@ export class Session {
|
||||
const nativeId = response.session.sessionId;
|
||||
this.liveState = {
|
||||
nativeId,
|
||||
children: new Children(this.host, this.options.id, this.config.cwd, this.options.emit),
|
||||
children: new Children(
|
||||
this.host,
|
||||
this.options.id,
|
||||
this.config.cwd,
|
||||
this.options.emit,
|
||||
() => !this.closing && this.options.capabilities.includes("session.subsession"),
|
||||
),
|
||||
timeline: new Timeline(
|
||||
this.host,
|
||||
nativeId,
|
||||
@@ -394,12 +400,15 @@ export class Session {
|
||||
.catch((error: unknown) => this.runtimeFailed(error));
|
||||
}
|
||||
private runtimeFailed(error: unknown): void {
|
||||
this.live().recovery.close();
|
||||
this.options.emit({
|
||||
type: "session.runtime_failed",
|
||||
sessionId: this.options.id,
|
||||
error: actionableError(error, this.options.launch),
|
||||
});
|
||||
// Closing the host can reject a notification's request. Let the close finish.
|
||||
if (!this.closing) {
|
||||
this.live().recovery.close();
|
||||
this.options.emit({
|
||||
type: "session.runtime_failed",
|
||||
sessionId: this.options.id,
|
||||
error: actionableError(error, this.options.launch),
|
||||
});
|
||||
}
|
||||
const interrupt = this.interruptCompletion;
|
||||
if (interrupt) interrupt.reject(error instanceof Error ? error : new Error(String(error)));
|
||||
}
|
||||
|
||||
@@ -86,10 +86,8 @@ export class Usage {
|
||||
try {
|
||||
const { usage } = await this.read(account, launch);
|
||||
if (!usage) return unavailable({ kind: "no_quota", detail: "No usage quota reported" });
|
||||
const observedAt = new Date(usage.observedAtMs).toISOString();
|
||||
return {
|
||||
status: "available",
|
||||
observedAt,
|
||||
planLabel: usage.tier,
|
||||
windows: [
|
||||
windowFromReportedDuration({
|
||||
@@ -114,7 +112,7 @@ export class Usage {
|
||||
{
|
||||
id: "observed",
|
||||
label: "Observed",
|
||||
value: observedAt,
|
||||
value: new Date(usage.observedAtMs).toISOString(),
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { appendFileSync, readFileSync } from "node:fs";
|
||||
import { appendFileSync, existsSync, readFileSync } from "node:fs";
|
||||
import { createInterface } from "node:readline";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
@@ -166,9 +166,7 @@ function parityResponse(frame) {
|
||||
return true;
|
||||
}
|
||||
if (frame.method === "session/read") {
|
||||
const result = responseFor(readFixture("phase3-child-read"), "session/read");
|
||||
result.session.sessionId = frame.params.sessionId;
|
||||
respond(frame, result);
|
||||
respondToChildRead(frame);
|
||||
return true;
|
||||
}
|
||||
if (frame.method === "usage/read") {
|
||||
@@ -223,6 +221,20 @@ function parityResponse(frame) {
|
||||
if (skillResponse(frame)) return true;
|
||||
return false;
|
||||
}
|
||||
function respondToChildRead(frame) {
|
||||
const result = responseFor(readFixture("phase3-child-read"), "session/read");
|
||||
result.session.sessionId = frame.params.sessionId;
|
||||
const releaseFile = process.env.MUSE_TEST_CHILD_READ_RELEASE;
|
||||
if (releaseFile && !existsSync(releaseFile)) {
|
||||
const waiting = setInterval(() => {
|
||||
if (!existsSync(releaseFile)) return;
|
||||
clearInterval(waiting);
|
||||
respond(frame, result);
|
||||
}, 10);
|
||||
} else {
|
||||
respond(frame, result);
|
||||
}
|
||||
}
|
||||
function skillResponse(frame) {
|
||||
if (frame.method === "skill/list") {
|
||||
const skillRows =
|
||||
|
||||
@@ -46,6 +46,7 @@ async function harness(
|
||||
scenario = "text-reasoning",
|
||||
env: Record<string, string> = {},
|
||||
providerOptions?: Record<string, unknown>,
|
||||
connectCapabilities: readonly string[] = PROVIDER_CAPABILITIES,
|
||||
) {
|
||||
const root = await mkdtemp(path.join(os.tmpdir(), "muse-provider-test-"));
|
||||
roots.push(root);
|
||||
@@ -63,7 +64,7 @@ async function harness(
|
||||
const connection = await provider.connect({
|
||||
launch,
|
||||
versions: [1],
|
||||
capabilities: PROVIDER_CAPABILITIES,
|
||||
capabilities: connectCapabilities,
|
||||
});
|
||||
connections.push(connection);
|
||||
const events: ProviderEvent[] = [];
|
||||
@@ -1254,6 +1255,20 @@ for (const variant of ["tool", "dedicated", "workflow"]) {
|
||||
).toHaveLength(1);
|
||||
});
|
||||
}
|
||||
|
||||
test("subagent children are not projected when session.subsession is not negotiated", async () => {
|
||||
const h = await harness(
|
||||
"subagent",
|
||||
{ MUSE_TEST_CHILD: "tool" },
|
||||
undefined,
|
||||
PROVIDER_CAPABILITIES.filter((capability) => capability !== "session.subsession"),
|
||||
);
|
||||
await h.open();
|
||||
await h.prompt();
|
||||
await h.wait((e) => e.type === "session.turn" && e.state === "completed");
|
||||
expect(h.events.filter((e) => e.type === "session.opened" && e.parentSessionId)).toHaveLength(0);
|
||||
expect((await h.recorded()).filter((f) => f.method === "session/read")).toEqual([]);
|
||||
});
|
||||
test("gap backfill repairs a missing completion without duplicating item revisions", async () => {
|
||||
const h = await harness("text-reasoning", { MUSE_TEST_GAP: "1" });
|
||||
await h.open();
|
||||
@@ -1505,7 +1520,6 @@ for (const usage of [
|
||||
expect(report).toMatchObject({
|
||||
status: "available",
|
||||
planLabel: "Pro",
|
||||
observedAt: new Date(usage.usage.observedAtMs).toISOString(),
|
||||
windows: [
|
||||
{
|
||||
id: "five_hour",
|
||||
@@ -1801,10 +1815,7 @@ test("Muse reports belong only to the session's account and remain available glo
|
||||
for (const [index, agentId] of ["muse-home", "muse-work"].entries()) {
|
||||
const reports = await registry.listReports({ agentId });
|
||||
expect(reports.map((report) => report.id)).toEqual([accountIds[index]]);
|
||||
expect(reports[0]!.report).toMatchObject({
|
||||
status: "available",
|
||||
observedAt: "2023-11-14T22:13:20.000Z",
|
||||
});
|
||||
expect(reports[0]!.report.status).toBe("available");
|
||||
}
|
||||
expect(await registry.listReports({ agentId: "muse-unknown" })).toEqual([]);
|
||||
expect((await registry.listReports()).map((report) => report.id)).toEqual(accountIds);
|
||||
|
||||
@@ -314,7 +314,8 @@ children. File-only rewind keeps the current session and conversation history.
|
||||
|
||||
Use `restoration: "core"` when Paseo can reopen a session from persistence. A provider-owned child
|
||||
uses `restoration: "parent"`; emit it as another `session.opened` event with `parentSessionId` and
|
||||
recreate it while restoring the parent.
|
||||
recreate it while restoring the parent. The parent's `session.opened` capabilities must include
|
||||
`session.subsession`. Paseo fails the whole connection when a parent without it opens a child.
|
||||
|
||||
## Add commands and steering
|
||||
|
||||
|
||||
@@ -616,11 +616,7 @@ For numeric durations, use `windowFromReportedDuration()` from
|
||||
`@getpaseo/plugin/server/usage` (Paseo 0.11+). Pass the reported seconds or `null`, a neutral
|
||||
`unknown` identity and name, and an optional stable quota `scope`. The helper derives the ID,
|
||||
label, and short label together; it accepts no duration-label override. For named API periods,
|
||||
use `windowFromUsedPct()` with names justified by that field. Set `durationSeconds` when
|
||||
the period has a known fixed length. Usage Details uses it with the reset time and the
|
||||
latest reading to estimate whether the quota will last until reset. If the source returns
|
||||
a previous reading, include its measurement time as an ISO timestamp in the report’s
|
||||
`observedAt` field.
|
||||
use `windowFromUsedPct()` with names justified by that field.
|
||||
|
||||
A window ID identifies a quota scope and period, never its response position, utilization, or
|
||||
reset instant. Scope model-specific quotas by the provider's stable feature ID, falling back to
|
||||
|
||||
Reference in New Issue
Block a user