mirror of
https://github.com/getpaseo/paseo.git
synced 2026-11-21 07:45:38 +00:00
Compare commits
16
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ab1aa2e237 | ||
|
|
571297e02b | ||
|
|
5e783c9ce8 | ||
|
|
fd2f885afd | ||
|
|
988cf4bec8 | ||
|
|
a6a9d0b8c7 | ||
|
|
b71b4d584a | ||
|
|
c9a7d523f8 | ||
|
|
ca514b34a7 | ||
|
|
efb65d7b82 | ||
|
|
27c126d352 | ||
|
|
7e3826ad6c | ||
|
|
c853f98b90 | ||
|
|
c3da87ee4c | ||
|
|
2298effb0b | ||
|
|
a7fed94e51 |
+7
-2
@@ -582,12 +582,17 @@ host, kinds, and ids. Opening a cached workspace uses exact workspace and projec
|
||||
directory scan. One invalid row is deleted and returned as a miss without affecting other rows.
|
||||
An invalid directory row and its affected checkpoint cursor are repaired in one transaction, so a
|
||||
later launch cannot accept a checkpoint for a partial baseline. Directory changes and their
|
||||
checkpoint are also applied in one transaction. Reads wait for accepted changes to reach storage,
|
||||
checkpoint are also applied in one transaction. A stored checkpoint carries a version. When a writer
|
||||
bug could have stored a checkpoint without its directory, bump the version: older checkpoints are
|
||||
rejected on read, cached rows still paint, and each host re-syncs its directory once. Reads wait for
|
||||
accepted changes to reach storage,
|
||||
then retry only when a requested row changes during the read. Unrelated agent streams do not
|
||||
invalidate the read. Directory baseline replacements and host removal or renaming still invalidate
|
||||
the affected reads.
|
||||
|
||||
The cache is capped at 32 MiB and evicts whole hosts in least-recently-written order. Budget
|
||||
The cache is capped at 32 MiB and evicts whole hosts in least-recently-written order. After an
|
||||
eviction, only a baseline replacement stores that host's directory again. Mutations queued around
|
||||
the eviction are dropped when they are written, so a checkpoint never outlives its rows. Budget
|
||||
bookkeeping may scan opaque row sizes during a deferred write, never during host registry startup or
|
||||
before a requested cache row can paint. The row store is not encrypted. A cached timeline can contain
|
||||
source code, prompts, and tool output; encrypted-at-rest storage is a separate security decision.
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
import { test, expect, type Page } from "../support/fixtures";
|
||||
import { gotoAppShell } from "../support/helpers/app";
|
||||
import { seedWorkspace, type SeededWorkspace } from "../support/helpers/seed-client";
|
||||
import { selectSidebarStatusGrouping } from "../support/helpers/sidebar";
|
||||
import {
|
||||
createGatedTeardown,
|
||||
pressArchiveShortcut,
|
||||
workspaceRow,
|
||||
} from "../support/helpers/workspace-archive-undo";
|
||||
|
||||
// The archive shortcut used to be registered by the sidebar row itself, so it did nothing whenever
|
||||
// the row was unmounted — a collapsed project section being the common case. It now lives in a
|
||||
// single always-mounted handler keyed on the active route selection, like the pin shortcut.
|
||||
// Returns the workspace route, so the test can assert archiving redirected off it.
|
||||
async function openWorkspace(page: Page, workspaceId: string): Promise<string> {
|
||||
const row = workspaceRow(page, workspaceId);
|
||||
await expect(row).toBeVisible({ timeout: 30_000 });
|
||||
await row.click();
|
||||
await expect(page).toHaveURL((url) => url.pathname.endsWith(`/workspace/${workspaceId}`), {
|
||||
timeout: 30_000,
|
||||
});
|
||||
return page.url();
|
||||
}
|
||||
|
||||
async function collapseProjectSection(page: Page, project: SeededWorkspace): Promise<void> {
|
||||
const header = page
|
||||
.locator('[data-testid^="sidebar-project-row-"]')
|
||||
.filter({ hasText: project.projectDisplayName });
|
||||
await expect(header).toHaveCount(1, { timeout: 30_000 });
|
||||
|
||||
await header.click();
|
||||
await expect(workspaceRow(page, project.workspaceId)).toHaveCount(0, { timeout: 10_000 });
|
||||
}
|
||||
|
||||
async function collapseStatusGroupContaining(page: Page, workspaceId: string): Promise<void> {
|
||||
const rows = page
|
||||
.locator('[data-testid^="sidebar-status-group-rows-"]')
|
||||
.filter({ has: workspaceRow(page, workspaceId) });
|
||||
await expect(rows).toHaveCount(1, { timeout: 30_000 });
|
||||
|
||||
const rowsTestId = await rows.getAttribute("data-testid");
|
||||
const bucket = rowsTestId?.replace("sidebar-status-group-rows-", "");
|
||||
expect(bucket).toBeTruthy();
|
||||
|
||||
await page.getByTestId(`sidebar-status-group-${bucket}`).click();
|
||||
await expect(workspaceRow(page, workspaceId)).toHaveCount(0, { timeout: 10_000 });
|
||||
}
|
||||
|
||||
async function expectArchived(page: Page, workspace: SeededWorkspace, workspaceUrl: string) {
|
||||
await expect(page).not.toHaveURL(workspaceUrl);
|
||||
await expect
|
||||
.poll(async () => {
|
||||
const { entries } = await workspace.client.fetchWorkspaces();
|
||||
return entries.some((entry) => entry.id === workspace.workspaceId);
|
||||
})
|
||||
.toBe(false);
|
||||
}
|
||||
|
||||
test.describe("Archive workspace shortcut", () => {
|
||||
test("archives the active workspace while its row is rendered", async ({ page }) => {
|
||||
const workspace = await seedWorkspace({ repoPrefix: "archive-shortcut-expanded-" });
|
||||
|
||||
try {
|
||||
await gotoAppShell(page);
|
||||
const workspaceUrl = await openWorkspace(page, workspace.workspaceId);
|
||||
|
||||
await pressArchiveShortcut(page);
|
||||
|
||||
await expectArchived(page, workspace, workspaceUrl);
|
||||
} finally {
|
||||
await workspace.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("archives the active workspace while its project section is collapsed", async ({ page }) => {
|
||||
const workspace = await seedWorkspace({ repoPrefix: "archive-shortcut-collapsed-" });
|
||||
|
||||
try {
|
||||
await gotoAppShell(page);
|
||||
const workspaceUrl = await openWorkspace(page, workspace.workspaceId);
|
||||
await collapseProjectSection(page, workspace);
|
||||
|
||||
await pressArchiveShortcut(page);
|
||||
|
||||
await expectArchived(page, workspace, workspaceUrl);
|
||||
} finally {
|
||||
await workspace.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("archives the active workspace while its status group is collapsed", async ({ page }) => {
|
||||
const workspace = await seedWorkspace({ repoPrefix: "archive-shortcut-status-" });
|
||||
|
||||
try {
|
||||
await gotoAppShell(page);
|
||||
const workspaceUrl = await openWorkspace(page, workspace.workspaceId);
|
||||
await selectSidebarStatusGrouping(page);
|
||||
await expect(page.getByTestId("sidebar-status-list-scroll")).toBeVisible({
|
||||
timeout: 10_000,
|
||||
});
|
||||
await collapseStatusGroupContaining(page, workspace.workspaceId);
|
||||
|
||||
await pressArchiveShortcut(page);
|
||||
|
||||
await expectArchived(page, workspace, workspaceUrl);
|
||||
} finally {
|
||||
await workspace.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("archives a different workspace while the first worktree is still tearing down", async ({
|
||||
page,
|
||||
}) => {
|
||||
const teardown = createGatedTeardown();
|
||||
const project = await seedWorkspace({
|
||||
repoPrefix: "archive-shortcut-teardown-",
|
||||
repo: { paseoConfig: teardown.paseoConfig },
|
||||
});
|
||||
const next = await seedWorkspace({ repoPrefix: "archive-shortcut-next-" });
|
||||
|
||||
try {
|
||||
const { workspace: worktree, error } = await project.client.createWorkspace({
|
||||
source: {
|
||||
kind: "worktree",
|
||||
cwd: project.repoPath,
|
||||
worktreeSlug: "archive-shortcut-teardown",
|
||||
},
|
||||
});
|
||||
if (!worktree) throw new Error(error ?? "Could not seed the worktree");
|
||||
await gotoAppShell(page);
|
||||
|
||||
await test.step("start the first archive and wait for its teardown", async () => {
|
||||
await openWorkspace(page, worktree.id);
|
||||
await pressArchiveShortcut(page);
|
||||
await teardown.expectStarted();
|
||||
});
|
||||
|
||||
await test.step("archive the second workspace before the first archive finishes", async () => {
|
||||
const workspaceUrl = await openWorkspace(page, next.workspaceId);
|
||||
await pressArchiveShortcut(page);
|
||||
await expectArchived(page, next, workspaceUrl);
|
||||
});
|
||||
} finally {
|
||||
teardown.release();
|
||||
await project.cleanup();
|
||||
await next.cleanup();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -206,13 +206,14 @@ async function simulateDamagedLegacyDirectoryCache(
|
||||
return;
|
||||
}
|
||||
const stored = JSON.parse(checkpoint.payload);
|
||||
// Accept either writer so this fixture also reproduces on the unfixed client.
|
||||
const cursors = stored.version === 1 ? stored.cursors : stored;
|
||||
if (!cursors.workspaces?.generation) {
|
||||
// Read the cursors from whichever version wrote them, then store them as version 1:
|
||||
// the format whose writer could keep a checkpoint after evicting the rows it describes.
|
||||
const cursors = typeof stored.version === "number" ? stored.cursors : stored;
|
||||
if (!cursors?.workspaces?.generation) {
|
||||
transaction.abort();
|
||||
return;
|
||||
}
|
||||
store.put({ ...checkpoint, payload: JSON.stringify(cursors) });
|
||||
store.put({ ...checkpoint, payload: JSON.stringify({ version: 1, cursors }) });
|
||||
for (const row of rows) {
|
||||
if (
|
||||
row.serverId === serverId &&
|
||||
|
||||
@@ -503,6 +503,34 @@ test.describe("terminal history with a finger", () => {
|
||||
await expectMouseWheelScrollsHistory(page);
|
||||
});
|
||||
|
||||
test("finger scrolling leaves terminal input unfocused until a tap", async ({ page }) => {
|
||||
await openPhoneTerminalHistory(page);
|
||||
await blurTerminalInput(page);
|
||||
|
||||
await expectSingleFingerScroll(page, 24);
|
||||
await expect(input(page)).not.toBeFocused();
|
||||
await expectSingleFingerScroll(page, 1);
|
||||
await expect(input(page)).not.toBeFocused();
|
||||
|
||||
await tapTerminalScreen(page);
|
||||
await expect(input(page)).toBeFocused();
|
||||
});
|
||||
|
||||
test("finger scrolling keeps a floating keyboard's input focused", async ({ page }) => {
|
||||
await openPhoneTerminalHistory(page);
|
||||
await tapTerminalScreen(page);
|
||||
await expect(input(page)).toBeFocused();
|
||||
|
||||
// A floating keyboard leaves the visual viewport unchanged.
|
||||
await expectSingleFingerScroll(page, 24);
|
||||
await expect(input(page)).toBeFocused();
|
||||
await expect(input(page)).toHaveAttribute("virtualkeyboardpolicy", "manual");
|
||||
|
||||
// Android Back also leaves the input focused. A tap restores automatic keyboard opening.
|
||||
await tapTerminalScreen(page);
|
||||
await expect(input(page)).not.toHaveAttribute("virtualkeyboardpolicy");
|
||||
});
|
||||
|
||||
for (const mode of ["alternate", "mouse"] as const) {
|
||||
test(`preserves finger navigation in ${mode} input mode`, async ({ page }) => {
|
||||
await openPhoneInputCapture(page, mode);
|
||||
@@ -531,6 +559,26 @@ async function openPhoneTerminalHistory(page: Page) {
|
||||
});
|
||||
await openPhoneTerminal(page);
|
||||
await expect.poll(() => getTerminalBufferText(page)).toContain("HISTORY_150");
|
||||
await expect
|
||||
.poll(() => page.evaluate(() => window.__paseoTerminal!.buffer.active.baseY))
|
||||
.toBeGreaterThan(0);
|
||||
await page.evaluate(() => window.__paseoTerminal!.scrollToBottom());
|
||||
await expect.poll(() => viewport(page)).toBeGreaterThan(0);
|
||||
}
|
||||
|
||||
function terminalScreen(page: Page) {
|
||||
return page.getByTestId("terminal-surface").filter({ visible: true }).locator(".xterm-screen");
|
||||
}
|
||||
|
||||
async function tapTerminalScreen(page: Page) {
|
||||
const box = await terminalScreen(page).boundingBox();
|
||||
expect(box).not.toBeNull();
|
||||
await page.touchscreen.tap(box!.x + box!.width / 2, box!.y + box!.height / 3);
|
||||
}
|
||||
|
||||
async function blurTerminalInput(page: Page) {
|
||||
await input(page).evaluate((element) => element.blur());
|
||||
await expect(input(page)).not.toBeFocused();
|
||||
}
|
||||
|
||||
async function openPhoneInputCapture(page: Page, mode: "alternate" | "mouse") {
|
||||
@@ -570,6 +618,20 @@ async function openPhoneTerminal(page: Page) {
|
||||
await page.getByTestId(`sidebar-workspace-row-${getServerId()}:${harness.workspaceId}`).click();
|
||||
await expect(page.getByRole("textbox", { name: "Terminal input" })).toBeVisible();
|
||||
await expect(page.getByTestId("terminal-surface").filter({ visible: true })).toBeVisible();
|
||||
// The terminal stays mounted while the sidebar's closing backdrop still intercepts input.
|
||||
await expect
|
||||
.poll(() =>
|
||||
page
|
||||
.getByTestId("terminal-surface")
|
||||
.filter({ visible: true })
|
||||
.evaluate((root) => {
|
||||
const box = root.querySelector(".xterm-screen")!.getBoundingClientRect();
|
||||
return root.contains(
|
||||
document.elementFromPoint(box.x + box.width / 2, box.y + box.height / 3),
|
||||
);
|
||||
}),
|
||||
)
|
||||
.toBe(true);
|
||||
}
|
||||
|
||||
async function expectMouseWheelScrollsHistory(page: Page) {
|
||||
|
||||
@@ -2,13 +2,14 @@ import { tmpdir } from "node:os";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import path from "node:path";
|
||||
import type { Page } from "@playwright/test";
|
||||
import type { UsageReportEntry } from "@getpaseo/protocol/messages";
|
||||
import type { UsageReport, UsageReportEntry } from "@getpaseo/protocol/messages";
|
||||
import { expect, test } from "../support/fixtures";
|
||||
import { gotoAppShell, openSettings } from "../support/helpers/app";
|
||||
import { addConnectedHostAndReload } from "../support/helpers/hosts";
|
||||
import { startIsolatedHostDaemon } from "../support/helpers/isolated-host-daemon";
|
||||
import { openSettingsSection } from "../support/helpers/settings";
|
||||
import { gate } from "../support/helpers/context-window";
|
||||
import { installDaemonWebSocketGate } from "../support/helpers/daemon-websocket-gate";
|
||||
import { getServerId } from "../support/helpers/server-id";
|
||||
import { seedSidebarFooterPreferences } from "../support/helpers/sidebar-nav-settings";
|
||||
import {
|
||||
@@ -45,6 +46,7 @@ import {
|
||||
refreshAllUsage,
|
||||
togglePin,
|
||||
usageItem,
|
||||
usageModal,
|
||||
} from "../support/helpers/usage-sidebar-item";
|
||||
|
||||
const emptyHome = path.join(tmpdir(), `paseo-usage-empty-${randomUUID()}`);
|
||||
@@ -865,6 +867,106 @@ test("open usage clocks advance without refreshing or reopening", async ({ page
|
||||
}
|
||||
});
|
||||
|
||||
test("Refresh all keeps quota visible and restores the forecast after a timeout", async ({
|
||||
page,
|
||||
}) => {
|
||||
const reading = new Date();
|
||||
const login = await installLoginUsage(usageReading(reading, 40));
|
||||
try {
|
||||
const transport = await installDaemonWebSocketGate(page);
|
||||
await openCompactUsageWithClock(page, reading);
|
||||
await expectQuota(page, "40% used", /runs out in /);
|
||||
|
||||
await timeOutUsageRefresh(page, transport);
|
||||
await expectQuota(page, "40% used", null);
|
||||
await expectUsageRefreshError(page).toBeVisible();
|
||||
|
||||
await login.setReport(usageReading(reading, 10));
|
||||
transport.releaseHeldClientRequest();
|
||||
await refreshAllUsage(page);
|
||||
await expectQuota(page, "10% used", "~50% left at reset");
|
||||
await expectUsageRefreshError(page).toBeHidden();
|
||||
} finally {
|
||||
await login.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("a card refresh timeout is visible alongside a newer quota forecast", async ({ page }) => {
|
||||
const reading = new Date();
|
||||
const login = await installLoginUsage(usageReading(reading, 40));
|
||||
try {
|
||||
const transport = await installDaemonWebSocketGate(page);
|
||||
await openCompactUsageWithClock(page, reading);
|
||||
await expectQuota(page, "40% used", /runs out in /);
|
||||
|
||||
await delayCardRefreshResponse(page, transport);
|
||||
await login.setReport(usageReading(reading, 10));
|
||||
await refreshAllUsage(page);
|
||||
await expectQuota(page, "10% used", "~50% left at reset");
|
||||
|
||||
await advanceUsageClock(page, 61_000);
|
||||
await expectUsageRefreshError(page).toBeVisible();
|
||||
await expectQuota(page, "10% used", "~50% left at reset");
|
||||
} finally {
|
||||
await login.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
function expectUsageRefreshError(page: Page) {
|
||||
return expect(usageModal(page).getByText("Unable to refresh usage", { exact: true }));
|
||||
}
|
||||
|
||||
async function delayCardRefreshResponse(
|
||||
page: Page,
|
||||
transport: Awaited<ReturnType<typeof installDaemonWebSocketGate>>,
|
||||
) {
|
||||
await expect(page.getByRole("button", { name: "Refresh all", exact: true })).toBeEnabled();
|
||||
transport.holdNextServerMessage("usage.list_reports.response");
|
||||
await refreshLoginUsage(page);
|
||||
await transport.waitForHeldServerMessage("usage.list_reports.response");
|
||||
}
|
||||
|
||||
function usageReading(observed: Date, usedPct: number): UsageReport {
|
||||
return {
|
||||
status: "available",
|
||||
observedAt: observed.toISOString(),
|
||||
windows: [
|
||||
{
|
||||
id: "session",
|
||||
label: "Session",
|
||||
usedPct,
|
||||
durationSeconds: 18_000,
|
||||
resetsAt: new Date(observed.getTime() + 4 * 3_600_000).toISOString(),
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
async function expectQuota(page: Page, amount: string, forecast: string | RegExp | null) {
|
||||
const usage = usageModal(page);
|
||||
await expect(usage.getByText(amount, { exact: true })).toBeVisible();
|
||||
await expect(usage.getByText(/^resets in /)).toBeVisible();
|
||||
if (forecast === null) {
|
||||
await expect(usage.getByText(/^runs out in /)).toBeHidden();
|
||||
return;
|
||||
}
|
||||
await expect(usage.getByText(forecast)).toBeVisible();
|
||||
}
|
||||
|
||||
async function timeOutUsageRefresh(
|
||||
page: Page,
|
||||
transport: Awaited<ReturnType<typeof installDaemonWebSocketGate>>,
|
||||
) {
|
||||
const refresh = page.getByRole("button", { name: "Refresh all", exact: true });
|
||||
await expect(refresh).toBeEnabled();
|
||||
transport.holdNextClientRequest("usage.list_reports.request");
|
||||
await refreshAllUsage(page);
|
||||
await transport.waitForHeldClientRequest();
|
||||
await expect(refresh).toBeDisabled();
|
||||
await advanceUsageClock(page, 61_000);
|
||||
await expect(refresh).toBeEnabled();
|
||||
}
|
||||
|
||||
async function openCompactUsageWithClock(page: Page, now: Date) {
|
||||
await page.setViewportSize({ width: 390, height: 844 });
|
||||
await page.clock.install({ time: now });
|
||||
|
||||
@@ -318,6 +318,37 @@ test.describe("Workspace archive undo", () => {
|
||||
}
|
||||
});
|
||||
|
||||
test("archives a restored workspace while its undo is queued", async ({ page }) => {
|
||||
const teardown = createGatedTeardown();
|
||||
const repo = await createTempGitRepo("archive-undo-archive-", {
|
||||
paseoConfig: teardown.paseoConfig,
|
||||
});
|
||||
|
||||
try {
|
||||
await openProjectViaDaemon(client, repo.path);
|
||||
const worktree = await createWorktreeViaDaemon(client, {
|
||||
cwd: repo.path,
|
||||
slug: "archive-undo-archive",
|
||||
});
|
||||
worktreeDirectories.add(worktree.workspaceDirectory);
|
||||
await gotoAppShell(page);
|
||||
await archiveFromRowButton(page, worktree.workspaceId);
|
||||
await teardown.expectStarted();
|
||||
|
||||
await undoButton(page).click();
|
||||
await workspaceRow(page, worktree.workspaceId).click();
|
||||
await expect(page).toHaveURL(new RegExp(`/workspace/${worktree.workspaceId}$`));
|
||||
|
||||
await pressArchiveShortcut(page);
|
||||
await expectWorkspaceAbsentFromSidebar(page, worktree.workspaceId);
|
||||
teardown.release();
|
||||
await expectDirectoryPresence(worktree.workspaceDirectory, false);
|
||||
} finally {
|
||||
teardown.release();
|
||||
await repo.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("Cmd/Ctrl+Z without an archive to undo leaves the sidebar alone", async ({ page }) => {
|
||||
const worktree = await seedWorktree(page, "archive-undo-none");
|
||||
|
||||
|
||||
@@ -20,6 +20,7 @@ import {
|
||||
} from "../support/helpers/sidebar";
|
||||
import { createTempGitRepo } from "../support/helpers/workspace";
|
||||
import {
|
||||
pressArchiveShortcut,
|
||||
rowArchiveButton,
|
||||
undoButton,
|
||||
workspaceRow,
|
||||
@@ -98,6 +99,18 @@ async function clickRowArchiveButton(page: Page, workspaceId: string): Promise<v
|
||||
await rowArchiveButton(page, workspaceId).click();
|
||||
}
|
||||
|
||||
async function cycleThemeAndWaitForSidebar(page: Page, workspaceId: string): Promise<void> {
|
||||
const rowBeforeThemeChange = await workspaceRow(page, workspaceId).elementHandle();
|
||||
if (!rowBeforeThemeChange)
|
||||
throw new Error("The workspace row must be mounted before cycling the theme");
|
||||
await page.keyboard.press("ControlOrMeta+Alt+t");
|
||||
await expect
|
||||
.poll(() => rowBeforeThemeChange.evaluate((element) => element.isConnected), {
|
||||
message: "the sidebar remounts after the theme changes",
|
||||
})
|
||||
.toBe(false);
|
||||
}
|
||||
|
||||
interface SessionEnvelope {
|
||||
type?: unknown;
|
||||
message?: {
|
||||
@@ -211,18 +224,28 @@ async function relayDaemon(
|
||||
* Holds the app's next checkout status request for `directory` once armed, so a test can act
|
||||
* while the archive waits for the host's answer.
|
||||
*/
|
||||
async function holdCheckoutStatusRequest(page: Page, directory: string) {
|
||||
async function holdCheckoutStatusRequest(
|
||||
page: Page,
|
||||
worktree: { workspaceDirectory: string; workspaceId: string },
|
||||
) {
|
||||
let armed = false;
|
||||
let held: (() => void) | null = null;
|
||||
let archiveRequests = 0;
|
||||
await page.routeWebSocket(daemonWsRoutePattern(), (browser) => {
|
||||
const server = browser.connectToServer();
|
||||
browser.onMessage((message) => {
|
||||
const request = typeof message === "string" ? parseSessionEnvelope(message)?.message : null;
|
||||
if (
|
||||
request?.type === "archive_workspace_request" &&
|
||||
request.workspaceId === worktree.workspaceId
|
||||
) {
|
||||
archiveRequests += 1;
|
||||
}
|
||||
if (
|
||||
armed &&
|
||||
!held &&
|
||||
request?.type === "checkout_status_request" &&
|
||||
request.cwd === directory
|
||||
request.cwd === worktree.workspaceDirectory
|
||||
) {
|
||||
held = () => server.send(message);
|
||||
return;
|
||||
@@ -236,6 +259,7 @@ async function holdCheckoutStatusRequest(page: Page, directory: string) {
|
||||
armed = true;
|
||||
},
|
||||
waitForHeld: () => expect.poll(() => held !== null).toBe(true),
|
||||
archiveRequests: () => archiveRequests,
|
||||
release: () => {
|
||||
if (!held) throw new Error("No checkout status request is held");
|
||||
held();
|
||||
@@ -388,7 +412,7 @@ test.describe("Workspace archive risk warning for worktree backing", () => {
|
||||
): Promise<string> {
|
||||
const serverId = getServerId();
|
||||
const worktree = await createWorktree(slug);
|
||||
const statusRequest = await holdCheckoutStatusRequest(page, worktree.workspaceDirectory);
|
||||
const statusRequest = await holdCheckoutStatusRequest(page, worktree);
|
||||
await openSidebarRow(page, worktree.workspaceId);
|
||||
await workspaceRow(page, worktree.workspaceId).click();
|
||||
await expectAppRoute(page, buildHostWorkspaceRoute(serverId, worktree.workspaceId));
|
||||
@@ -432,6 +456,82 @@ test.describe("Workspace archive risk warning for worktree backing", () => {
|
||||
await expectAppRoute(page, openedRoute);
|
||||
});
|
||||
|
||||
async function openWorktreeWithCheckoutHeld(page: Page, slug: string) {
|
||||
const worktree = await createWorktree(slug);
|
||||
const statusRequest = await holdCheckoutStatusRequest(page, worktree);
|
||||
// Opening the workspace can start a checkout read that the archive reuses.
|
||||
statusRequest.arm();
|
||||
await openSidebarRow(page, worktree.workspaceId);
|
||||
await workspaceRow(page, worktree.workspaceId).click();
|
||||
await expectAppRoute(page, buildHostWorkspaceRoute(getServerId(), worktree.workspaceId));
|
||||
return { worktree, statusRequest };
|
||||
}
|
||||
|
||||
test("the archive shortcut works in another workspace while a checkout check is pending", async ({
|
||||
page,
|
||||
}) => {
|
||||
const { worktree, statusRequest } = await openWorktreeWithCheckoutHeld(
|
||||
page,
|
||||
"archive-risk-switch-shortcut",
|
||||
);
|
||||
|
||||
await pressArchiveShortcut(page);
|
||||
await statusRequest.waitForHeld();
|
||||
try {
|
||||
const otherWorkspaceId = worktree.project.workspaceId;
|
||||
await workspaceRow(page, otherWorkspaceId).click();
|
||||
await expectAppRoute(page, buildHostWorkspaceRoute(getServerId(), otherWorkspaceId));
|
||||
|
||||
await pressArchiveShortcut(page);
|
||||
await expect.poll(() => hostListsWorkspace(otherWorkspaceId)).toBe(false);
|
||||
} finally {
|
||||
statusRequest.release();
|
||||
}
|
||||
await expect.poll(() => hostListsWorkspace(worktree.workspaceId)).toBe(false);
|
||||
});
|
||||
|
||||
test("the row button and shortcut send one archive for the same worktree", async ({ page }) => {
|
||||
const { worktree, statusRequest } = await openWorktreeWithCheckoutHeld(
|
||||
page,
|
||||
"archive-risk-repeat-shortcut",
|
||||
);
|
||||
|
||||
await clickRowArchiveButton(page, worktree.workspaceId);
|
||||
await statusRequest.waitForHeld();
|
||||
try {
|
||||
await pressArchiveShortcut(page);
|
||||
} finally {
|
||||
statusRequest.release();
|
||||
}
|
||||
|
||||
await expect.poll(() => hostListsWorkspace(worktree.workspaceId)).toBe(false);
|
||||
expect(statusRequest.archiveRequests()).toBe(1);
|
||||
});
|
||||
|
||||
test("keeps the newly opened workspace after a theme change during an archive check", async ({
|
||||
page,
|
||||
}) => {
|
||||
const { worktree, statusRequest } = await openWorktreeWithCheckoutHeld(
|
||||
page,
|
||||
"archive-risk-theme",
|
||||
);
|
||||
|
||||
await pressArchiveShortcut(page);
|
||||
await statusRequest.waitForHeld();
|
||||
const otherWorkspaceId = worktree.project.workspaceId;
|
||||
const otherRoute = buildHostWorkspaceRoute(getServerId(), otherWorkspaceId);
|
||||
try {
|
||||
await cycleThemeAndWaitForSidebar(page, otherWorkspaceId);
|
||||
await workspaceRow(page, otherWorkspaceId).click();
|
||||
await expectAppRoute(page, otherRoute);
|
||||
} finally {
|
||||
statusRequest.release();
|
||||
}
|
||||
|
||||
await expect.poll(() => hostListsWorkspace(worktree.workspaceId)).toBe(false);
|
||||
await expectAppRoute(page, otherRoute);
|
||||
});
|
||||
|
||||
test("archiving the open worktree from its git actions leaves it for a new workspace", async ({
|
||||
page,
|
||||
}) => {
|
||||
|
||||
@@ -185,13 +185,15 @@ function onLogin(report: UsageReportEntry, login: string): UsageReportEntry {
|
||||
}
|
||||
|
||||
export function expiredLogin(report: UsageReportEntry): UsageReportEntry {
|
||||
const fetchedAt = Date.now();
|
||||
return {
|
||||
...report,
|
||||
fetchedAt: new Date(fetchedAt).toISOString(),
|
||||
report: {
|
||||
status: "unavailable",
|
||||
problem: {
|
||||
kind: "expired",
|
||||
expiresAt: new Date(Date.now() - 2 * 60 * 60_000).toISOString(),
|
||||
expiresAt: new Date(fetchedAt - 2 * 60 * 60_000).toISOString(),
|
||||
refreshedBy: "claude",
|
||||
},
|
||||
},
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { expect, type Page } from "@playwright/test";
|
||||
import { expect, test, type Page } from "@playwright/test";
|
||||
import { openChangesPanel } from "./branch-switcher";
|
||||
|
||||
export async function restoreArchivedWorkspace(page: Page): Promise<void> {
|
||||
@@ -32,7 +32,11 @@ export async function expectCommittedFile(page: Page, filename: string): Promise
|
||||
}
|
||||
|
||||
export async function expectCommittedFileAfterReload(page: Page, filename: string): Promise<void> {
|
||||
await expectCommittedFile(page, filename);
|
||||
await page.reload();
|
||||
await expectCommittedFile(page, filename);
|
||||
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);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -66,6 +66,7 @@
|
||||
[role="slider"],
|
||||
[role="menuitem"],
|
||||
[tabindex],
|
||||
[data-window-no-drag],
|
||||
[contenteditable="true"] {
|
||||
-webkit-app-region: no-drag !important;
|
||||
}
|
||||
|
||||
@@ -54,6 +54,7 @@ import { WindowSidebarMenuToggle } from "@/components/headers/sidebar-menu-toggl
|
||||
import { DesktopWindowControls } from "@/components/desktop/window-controls";
|
||||
import { SidebarModelProvider } from "@/components/sidebar/sidebar-model";
|
||||
import { WorkspacePinShortcutHandler } from "@/components/workspace-pin-shortcut-handler";
|
||||
import { WorkspaceArchiveShortcutHandler } from "@/components/workspace-archive-shortcut-handler";
|
||||
import { WorkspaceRenameHost } from "@/components/workspace-rename-host";
|
||||
import { WorkspaceArchiveUndoShortcutHost } from "@/workspace/archive-undo";
|
||||
import { WorkspaceExplorerOpenGesture } from "@/mobile-panels/explorer-open-gesture";
|
||||
@@ -537,6 +538,7 @@ function AppContainer({ children, chromeEnabled: chromeEnabledOverride }: AppCon
|
||||
<View style={layoutStyles.surfaceFill}>
|
||||
{workspaceChrome}
|
||||
<AddHostFlowHost />
|
||||
<WorkspaceArchiveShortcutHandler />
|
||||
<AppearanceStyleBoundary>
|
||||
{!isCompactLayout && appChromeLayout.sidebarToggleOwner === "window" ? (
|
||||
<WindowChromeRegion corners="top-left">
|
||||
|
||||
@@ -24,6 +24,9 @@ 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,6 +27,7 @@ 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;
|
||||
@@ -49,6 +50,7 @@ interface CompactHeaderProps {
|
||||
*/
|
||||
export function CompactHeader({
|
||||
navigation,
|
||||
inDesktopTitlebar = false,
|
||||
onBack,
|
||||
title,
|
||||
titleTestID,
|
||||
@@ -58,22 +60,28 @@ export function CompactHeader({
|
||||
}: CompactHeaderProps) {
|
||||
const insets = useSafeAreaInsets();
|
||||
const inTopBand = useTopBand() !== null;
|
||||
const usesTitlebarHeight = inTopBand || inDesktopTitlebar;
|
||||
const rootStyle = useMemo(
|
||||
() => [
|
||||
styles.root,
|
||||
{
|
||||
paddingTop: insets.top + (inTopBand ? 0 : HEADER_TOP_PADDING_MOBILE),
|
||||
paddingTop: insets.top + (usesTitlebarHeight ? 0 : HEADER_TOP_PADDING_MOBILE),
|
||||
marginLeft: insets.left,
|
||||
marginRight: insets.right,
|
||||
},
|
||||
],
|
||||
[inTopBand, insets.top, insets.left, insets.right],
|
||||
[usesTitlebarHeight, insets.top, insets.left, insets.right],
|
||||
);
|
||||
|
||||
return (
|
||||
<IconButtonChromeProvider value="header-island">
|
||||
<View style={rootStyle}>
|
||||
<View style={inTopBand ? styles.topBandRow : styles.row}>
|
||||
<View
|
||||
style={[
|
||||
usesTitlebarHeight ? styles.titlebarRow : styles.row,
|
||||
inDesktopTitlebar && styles.desktopTitlebarDividerSpace,
|
||||
]}
|
||||
>
|
||||
<View style={styles.island}>
|
||||
{navigation === "menu" ? <SidebarMenuToggle /> : <BackButton onBack={onBack} />}
|
||||
</View>
|
||||
@@ -155,12 +163,16 @@ const styles = StyleSheet.create((theme) => ({
|
||||
alignItems: "center",
|
||||
gap: theme.spacing[2],
|
||||
},
|
||||
topBandRow: {
|
||||
titlebarRow: {
|
||||
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,7 +128,6 @@ import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip
|
||||
import { Shortcut } from "@/components/ui/shortcut";
|
||||
import type { ShortcutKey } from "@/utils/format-shortcut";
|
||||
import { useShortcutKeys } from "@/hooks/use-shortcut-keys";
|
||||
import { useKeyboardActionHandler } from "@/hooks/use-keyboard-action-handler";
|
||||
import { useWorkspaceReadState } from "@/hooks/use-workspace-read-state";
|
||||
import type { PrHint } from "@/git/use-pr-status-query";
|
||||
import {
|
||||
@@ -1298,17 +1297,6 @@ function WorkspaceRowWithMenu({
|
||||
});
|
||||
}, [markUnread, toast]);
|
||||
|
||||
useKeyboardActionHandler({
|
||||
handlerId: `workspace-archive-${workspace.workspaceKey}`,
|
||||
actions: ["workspace.archive"],
|
||||
enabled: selected && !isArchiving,
|
||||
priority: 0,
|
||||
handle: () => {
|
||||
handleArchive();
|
||||
return true;
|
||||
},
|
||||
});
|
||||
|
||||
return (
|
||||
<>
|
||||
<WorkspaceRowInner
|
||||
|
||||
@@ -42,7 +42,6 @@ import { redirectIfArchivingActiveWorkspace } from "@/utils/sidebar-workspace-ar
|
||||
import { useWorkspaceArchive } from "@/workspace/use-workspace-archive";
|
||||
import type { ShortcutKey } from "@/utils/format-shortcut";
|
||||
import { useShortcutKeys } from "@/hooks/use-shortcut-keys";
|
||||
import { useKeyboardActionHandler } from "@/hooks/use-keyboard-action-handler";
|
||||
import { useWorkspaceReadState } from "@/hooks/use-workspace-read-state";
|
||||
import {
|
||||
SidebarWorkspaceRowFrame,
|
||||
@@ -702,17 +701,6 @@ function StatusWorkspaceRowWithMenu({
|
||||
});
|
||||
}, [markUnread, toast]);
|
||||
|
||||
useKeyboardActionHandler({
|
||||
handlerId: `workspace-archive-${workspace.workspaceKey}`,
|
||||
actions: ["workspace.archive"],
|
||||
enabled: selected && !isArchiving,
|
||||
priority: 0,
|
||||
handle: () => {
|
||||
handleArchive();
|
||||
return true;
|
||||
},
|
||||
});
|
||||
|
||||
return (
|
||||
<>
|
||||
<StatusWorkspaceRowInner
|
||||
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
useRef,
|
||||
type CSSProperties,
|
||||
type MouseEvent as ReactMouseEvent,
|
||||
type PointerEvent as ReactPointerEvent,
|
||||
type Ref,
|
||||
} from "react";
|
||||
import type { DOMProps } from "expo/dom";
|
||||
@@ -63,6 +64,12 @@ const HOST_DIV_STYLE: CSSProperties = {
|
||||
paddingRight: 0,
|
||||
};
|
||||
|
||||
interface TerminalTouchFocus {
|
||||
pointerId: number;
|
||||
x: number;
|
||||
y: number;
|
||||
}
|
||||
|
||||
function buildXtermThemeKey(theme: ITheme): string {
|
||||
const values: Array<string> = [
|
||||
theme.background,
|
||||
@@ -553,10 +560,46 @@ export default function TerminalEmulator({
|
||||
});
|
||||
}, []);
|
||||
|
||||
const handleRootPointerDown = useCallback(() => {
|
||||
onFocus?.();
|
||||
runtimeRef.current?.focus();
|
||||
}, [onFocus]);
|
||||
const touchFocusRef = useRef<TerminalTouchFocus | null>(null);
|
||||
|
||||
const handleRootPointerDown = useCallback(
|
||||
(event: ReactPointerEvent) => {
|
||||
onFocus?.();
|
||||
touchFocusRef.current = null;
|
||||
if (event.pointerType !== "touch") {
|
||||
runtimeRef.current?.focus();
|
||||
return;
|
||||
}
|
||||
// Focusing before a touch becomes a tap opens the keyboard during a scroll.
|
||||
if (event.isPrimary) {
|
||||
touchFocusRef.current = {
|
||||
pointerId: event.pointerId,
|
||||
x: event.clientX,
|
||||
y: event.clientY,
|
||||
};
|
||||
}
|
||||
},
|
||||
[onFocus],
|
||||
);
|
||||
|
||||
const handleRootPointerMove = useCallback((event: ReactPointerEvent) => {
|
||||
const touch = touchFocusRef.current;
|
||||
if (touch?.pointerId !== event.pointerId) return;
|
||||
if (Math.hypot(event.clientX - touch.x, event.clientY - touch.y) > 8) {
|
||||
touchFocusRef.current = null;
|
||||
runtimeRef.current?.suppressAutomaticKeyboard();
|
||||
}
|
||||
}, []);
|
||||
|
||||
const handleRootPointerUp = useCallback((event: ReactPointerEvent) => {
|
||||
const touch = touchFocusRef.current;
|
||||
touchFocusRef.current = null;
|
||||
if (touch?.pointerId === event.pointerId) runtimeRef.current?.focus();
|
||||
}, []);
|
||||
|
||||
const handleRootPointerCancel = useCallback(() => {
|
||||
touchFocusRef.current = null;
|
||||
}, []);
|
||||
|
||||
const handleRootContextMenu = useCallback(
|
||||
(event: ReactMouseEvent) => {
|
||||
@@ -588,6 +631,9 @@ export default function TerminalEmulator({
|
||||
data-terminal-scrollbar-root="true"
|
||||
style={rootDivStyle}
|
||||
onPointerDown={handleRootPointerDown}
|
||||
onPointerMove={handleRootPointerMove}
|
||||
onPointerUp={handleRootPointerUp}
|
||||
onPointerCancel={handleRootPointerCancel}
|
||||
onContextMenu={handleRootContextMenu}
|
||||
>
|
||||
<div ref={hostRef} style={HOST_DIV_STYLE} />
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
import { useGlobalWorkspaceArchiveAction } from "@/hooks/use-global-workspace-archive-action";
|
||||
|
||||
// Headless host for the archive shortcut, kept out of the root layout for the same reason as
|
||||
// WorkspacePinShortcutHandler: the hook subscribes to the active workspace's fields.
|
||||
export function WorkspaceArchiveShortcutHandler() {
|
||||
useGlobalWorkspaceArchiveAction();
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
import { useCallback } from "react";
|
||||
import { useKeyboardActionHandler } from "@/hooks/use-keyboard-action-handler";
|
||||
import type { KeyboardActionId } from "@/keyboard/keyboard-action-dispatcher";
|
||||
import { useActiveWorkspaceSelection } from "@/stores/navigation-active-workspace-store";
|
||||
import { useWorkspaceFields } from "@/stores/session-store-hooks";
|
||||
import { redirectIfArchivingActiveWorkspace } from "@/utils/sidebar-workspace-archive-redirect";
|
||||
import { useWorkspaceArchive } from "@/workspace/use-workspace-archive";
|
||||
import { isWorkspaceListed, type WorkspaceArchiveTarget } from "@/workspace/workspace-archive";
|
||||
|
||||
const WORKSPACE_ARCHIVE_ACTIONS: readonly KeyboardActionId[] = ["workspace.archive"];
|
||||
|
||||
// The archive shortcut used to live on the sidebar row, so it did nothing whenever the row was not
|
||||
// rendered — a collapsed project or status group, a collapsed Pinned section, or focus mode. Like
|
||||
// the pin shortcut (see use-global-workspace-pin-action.ts), it is one registration keyed on the
|
||||
// active route selection.
|
||||
export function useGlobalWorkspaceArchiveAction() {
|
||||
const selection = useActiveWorkspaceSelection();
|
||||
const serverId = selection?.serverId ?? null;
|
||||
const routeWorkspaceId = selection?.workspaceId ?? null;
|
||||
// `id` is the descriptor id, not the route id; see use-global-workspace-pin-action.ts.
|
||||
const fields = useWorkspaceFields(serverId, routeWorkspaceId, (workspace) => ({
|
||||
id: workspace.id,
|
||||
workspaceKind: workspace.workspaceKind,
|
||||
workspaceDirectory: workspace.workspaceDirectory,
|
||||
name: workspace.name,
|
||||
archivingAt: workspace.archivingAt,
|
||||
diffStat: workspace.diffStat,
|
||||
}));
|
||||
|
||||
// useWorkspaceArchive calls the latest render's callback, so `activeWorkspaceId` is whatever is
|
||||
// routed when the archive starts, after any confirmation. It is the descriptor id, which is what
|
||||
// the redirect compares against.
|
||||
const activeWorkspaceId = fields?.id ?? null;
|
||||
const redirectAfterArchive = useCallback(
|
||||
(workspace: WorkspaceArchiveTarget) => {
|
||||
redirectIfArchivingActiveWorkspace({
|
||||
...workspace,
|
||||
activeWorkspaceSelection:
|
||||
serverId && activeWorkspaceId ? { serverId, workspaceId: activeWorkspaceId } : null,
|
||||
});
|
||||
},
|
||||
[activeWorkspaceId, serverId],
|
||||
);
|
||||
|
||||
const archiveController = useWorkspaceArchive({
|
||||
serverId: serverId ?? "",
|
||||
workspaceId: fields?.id ?? "",
|
||||
workspaceKind: fields?.workspaceKind ?? "directory",
|
||||
workspaceDirectory: fields?.workspaceDirectory ?? "",
|
||||
name: fields?.name ?? "",
|
||||
diffStat: fields?.diffStat,
|
||||
onArchiveStarted: redirectAfterArchive,
|
||||
});
|
||||
|
||||
const canArchive = fields !== null && fields.archivingAt === null;
|
||||
|
||||
const handle = useCallback(() => {
|
||||
if (!canArchive || !serverId) {
|
||||
return false;
|
||||
}
|
||||
// Archiving hides its target immediately. Read the store in case the shortcut
|
||||
// runs again before React renders that update.
|
||||
if (!isWorkspaceListed({ serverId, workspaceId: fields.id })) {
|
||||
return false;
|
||||
}
|
||||
archiveController.archive();
|
||||
return true;
|
||||
}, [archiveController, canArchive, fields, serverId]);
|
||||
|
||||
useKeyboardActionHandler({
|
||||
handlerId: "workspace-archive-global",
|
||||
actions: WORKSPACE_ARCHIVE_ACTIONS,
|
||||
enabled: canArchive,
|
||||
priority: 0,
|
||||
handle,
|
||||
});
|
||||
}
|
||||
@@ -2323,6 +2323,9 @@ export const ar: TranslationResources = {
|
||||
resetsIn: "تتم إعادة التعيين خلال {{duration}}",
|
||||
resetsAtWeekday: "{{weekday}} {{time}}",
|
||||
resetsAtDate: "{{date}}، {{time}}",
|
||||
projectedLeftAtReset: "نحو {{percentage}} متبقية عند إعادة التعيين",
|
||||
limitReached: "تم بلوغ الحد",
|
||||
mayHaveRunOut: "ربما نفدت الحصة",
|
||||
runsOutNow: "ينفد الآن",
|
||||
runsOutIn: "ينفد خلال {{duration}}",
|
||||
justNow: "الآن",
|
||||
|
||||
@@ -2333,6 +2333,9 @@ export const en = {
|
||||
resetsIn: "resets in {{duration}}",
|
||||
resetsAtWeekday: "{{weekday}} {{time}}",
|
||||
resetsAtDate: "{{date}}, {{time}}",
|
||||
projectedLeftAtReset: "~{{percentage}} left at reset",
|
||||
limitReached: "Limit reached",
|
||||
mayHaveRunOut: "May have run out",
|
||||
runsOutNow: "runs out now",
|
||||
runsOutIn: "runs out in {{duration}}",
|
||||
justNow: "just now",
|
||||
|
||||
@@ -2354,6 +2354,9 @@ export const es: TranslationResources = {
|
||||
resetsIn: "se restablece en {{duration}}",
|
||||
resetsAtWeekday: "{{weekday}} {{time}}",
|
||||
resetsAtDate: "{{date}}, {{time}}",
|
||||
projectedLeftAtReset: "~{{percentage}} restante al restablecerse",
|
||||
limitReached: "Límite alcanzado",
|
||||
mayHaveRunOut: "Puede que ya se haya agotado",
|
||||
runsOutNow: "se agota ahora",
|
||||
runsOutIn: "se agota en {{duration}}",
|
||||
justNow: "ahora mismo",
|
||||
|
||||
@@ -2355,6 +2355,9 @@ export const fr: TranslationResources = {
|
||||
resetsIn: "se réinitialise dans {{duration}}",
|
||||
resetsAtWeekday: "{{weekday}} {{time}}",
|
||||
resetsAtDate: "{{date}}, {{time}}",
|
||||
projectedLeftAtReset: "~{{percentage}} restant à la réinitialisation",
|
||||
limitReached: "Limite atteinte",
|
||||
mayHaveRunOut: "Le quota est peut-être épuisé",
|
||||
runsOutNow: "s’épuise maintenant",
|
||||
runsOutIn: "s’épuise dans {{duration}}",
|
||||
justNow: "à l’instant",
|
||||
|
||||
@@ -2328,6 +2328,9 @@ export const ja: TranslationResources = {
|
||||
resetsIn: "{{duration}}後にリセット",
|
||||
resetsAtWeekday: "{{weekday}} {{time}}",
|
||||
resetsAtDate: "{{date}} {{time}}",
|
||||
projectedLeftAtReset: "リセット時に約{{percentage}}残る見込み",
|
||||
limitReached: "上限に達しました",
|
||||
mayHaveRunOut: "上限に達した可能性があります",
|
||||
runsOutNow: "まもなく上限に到達",
|
||||
runsOutIn: "{{duration}}後に上限に到達",
|
||||
justNow: "たった今",
|
||||
|
||||
@@ -2316,6 +2316,9 @@ export const ko: TranslationResources = {
|
||||
resetsIn: "{{duration}} 후 재설정",
|
||||
resetsAtWeekday: "{{weekday}} {{time}}",
|
||||
resetsAtDate: "{{date}} {{time}}",
|
||||
projectedLeftAtReset: "초기화 시 약 {{percentage}} 남을 예정",
|
||||
limitReached: "한도에 도달함",
|
||||
mayHaveRunOut: "한도를 소진했을 수 있음",
|
||||
runsOutNow: "지금 한도에 도달",
|
||||
runsOutIn: "{{duration}} 후 한도에 도달",
|
||||
justNow: "방금",
|
||||
|
||||
@@ -2339,6 +2339,9 @@ export const ptBR: TranslationResources = {
|
||||
resetsIn: "redefine em {{duration}}",
|
||||
resetsAtWeekday: "{{weekday}} {{time}}",
|
||||
resetsAtDate: "{{date}}, {{time}}",
|
||||
projectedLeftAtReset: "~{{percentage}} restará na renovação",
|
||||
limitReached: "Limite atingido",
|
||||
mayHaveRunOut: "A cota pode ter se esgotado",
|
||||
runsOutNow: "esgota agora",
|
||||
runsOutIn: "esgota em {{duration}}",
|
||||
justNow: "agora mesmo",
|
||||
|
||||
@@ -2341,6 +2341,9 @@ export const ru: TranslationResources = {
|
||||
resetsIn: "сброс через {{duration}}",
|
||||
resetsAtWeekday: "{{weekday}} {{time}}",
|
||||
resetsAtDate: "{{date}}, {{time}}",
|
||||
projectedLeftAtReset: "К сбросу останется ~{{percentage}}",
|
||||
limitReached: "Лимит исчерпан",
|
||||
mayHaveRunOut: "Лимит мог уже исчерпаться",
|
||||
runsOutNow: "закончится сейчас",
|
||||
runsOutIn: "закончится через {{duration}}",
|
||||
justNow: "только что",
|
||||
|
||||
@@ -2282,6 +2282,9 @@ export const zhCN: TranslationResources = {
|
||||
resetsIn: "将在 {{duration}}后重置",
|
||||
resetsAtWeekday: "{{weekday}} {{time}}",
|
||||
resetsAtDate: "{{date}} {{time}}",
|
||||
projectedLeftAtReset: "重置时约剩余 {{percentage}}",
|
||||
limitReached: "已达到上限",
|
||||
mayHaveRunOut: "额度可能已用完",
|
||||
runsOutNow: "即将用尽",
|
||||
runsOutIn: "将在 {{duration}}后用尽",
|
||||
justNow: "刚刚",
|
||||
|
||||
@@ -10,7 +10,10 @@ import type {
|
||||
DaemonClient,
|
||||
WorkspaceLabelListPayload,
|
||||
} from "@getpaseo/client/internal/daemon-client";
|
||||
import type { SessionOutboundMessage } from "@getpaseo/protocol/messages";
|
||||
import type {
|
||||
SessionOutboundMessage,
|
||||
WorkspaceDescriptorPayload,
|
||||
} from "@getpaseo/protocol/messages";
|
||||
import {
|
||||
normalizeProjectDescriptor,
|
||||
normalizeWorkspaceDescriptor,
|
||||
@@ -1667,6 +1670,187 @@ it("fills every cached workspace beneath live updates received during the SQLite
|
||||
database.close();
|
||||
});
|
||||
|
||||
/**
|
||||
* A host whose cache was damaged before the eviction fix: workspaces survived, project rows did not,
|
||||
* and a version 1 checkpoint still claims the project directory is current. The daemon holds
|
||||
* projects A and B; renaming A is its update at `renameSeq`.
|
||||
*/
|
||||
async function createDamagedLegacyProjectDirectory(serverId: string, renameSeq: number) {
|
||||
serverIds.add(serverId);
|
||||
const { cache, database, storage, reopen, holdRead } = createSqliteCache();
|
||||
cache.setHosts([serverId]);
|
||||
const workspacePayload = (id: string, projectId: string): WorkspaceDescriptorPayload => ({
|
||||
id,
|
||||
projectId,
|
||||
projectDisplayName: projectId,
|
||||
projectRootPath: `/repo/${projectId}`,
|
||||
workspaceDirectory: `/repo/${projectId}`,
|
||||
projectKind: "git",
|
||||
workspaceKind: "local_checkout",
|
||||
name: id,
|
||||
status: "done",
|
||||
statusEnteredAt: null,
|
||||
activityAt: null,
|
||||
archivingAt: null,
|
||||
diffStat: null,
|
||||
scripts: [],
|
||||
});
|
||||
const project = (projectId: string, projectDisplayName: string) => ({
|
||||
projectId,
|
||||
projectDisplayName,
|
||||
projectRootPath: `/repo/${projectId}`,
|
||||
projectKind: "git" as const,
|
||||
});
|
||||
const workspaceEntries = [workspacePayload("wa", "A"), workspacePayload("wb", "B")];
|
||||
cache.replaceDirectoryBaseline(serverId, {
|
||||
agents: new Map(),
|
||||
workspaces: new Map(
|
||||
workspaceEntries.map((entry) => [entry.id, normalizeWorkspaceDescriptor(entry)]),
|
||||
),
|
||||
projects: new Map(),
|
||||
});
|
||||
await cache.flush();
|
||||
await storage.apply({
|
||||
deletes: [],
|
||||
upserts: [
|
||||
{
|
||||
serverId,
|
||||
kind: "checkpoint",
|
||||
id: "singleton",
|
||||
payload: JSON.stringify({
|
||||
version: 1,
|
||||
cursors: { projects: { generation: "g", afterSeq: renameSeq - 1 } },
|
||||
}),
|
||||
},
|
||||
],
|
||||
});
|
||||
const reopened = reopen();
|
||||
reopened.setHosts([serverId]);
|
||||
const client = new FakeDirectoryClient();
|
||||
let failNextProjectRequest = false;
|
||||
client.listProjects = async (options?: unknown): Promise<ProjectListResult> => {
|
||||
client.lastProjectOptions = options;
|
||||
if (failNextProjectRequest) {
|
||||
failNextProjectRequest = false;
|
||||
throw new Error("Request timed out");
|
||||
}
|
||||
const resumesAfterRename =
|
||||
(options as { sync?: { afterSeq?: number } } | undefined)?.sync?.afterSeq === renameSeq;
|
||||
return resumesAfterRename
|
||||
? {
|
||||
requestId: "projects",
|
||||
projects: [],
|
||||
sync: { generation: "g", headSeq: renameSeq, mode: "changes", removals: [] },
|
||||
}
|
||||
: {
|
||||
requestId: "projects",
|
||||
projects: [project("A", "Renamed"), project("B", "B")],
|
||||
sync: { generation: "g", headSeq: renameSeq, mode: "snapshot", removals: [] },
|
||||
};
|
||||
};
|
||||
client.fetchWorkspaces = async (): Promise<WorkspaceFetchResult> => ({
|
||||
requestId: "workspaces",
|
||||
entries: workspaceEntries,
|
||||
emptyProjects: [],
|
||||
pageInfo: { hasMore: false, nextCursor: null, prevCursor: null },
|
||||
sync: { generation: "g", headSeq: 2, mode: "snapshot", removals: [] },
|
||||
});
|
||||
const directory = new DirectorySync(
|
||||
serverId,
|
||||
{
|
||||
onAgentStoppedRunning: () => {},
|
||||
markAgentLoading: () => {},
|
||||
markAgentReady: () => {},
|
||||
markAgentError: () => {},
|
||||
},
|
||||
reopened,
|
||||
);
|
||||
const store = useSessionStore.getState();
|
||||
store.initializeSession(serverId, client as unknown as DaemonClient, 1);
|
||||
store.updateSessionServerInfo(serverId, {
|
||||
serverId,
|
||||
hostname: null,
|
||||
version: "test",
|
||||
features: { workspaceMultiplicity: true, directorySync: true, projectList: true },
|
||||
});
|
||||
directory.connectionChanged({
|
||||
client: client as unknown as DaemonClient,
|
||||
status: "online",
|
||||
source: { clientGeneration: 1, connectionEpoch: 1 },
|
||||
});
|
||||
return {
|
||||
client,
|
||||
directory,
|
||||
holdRead,
|
||||
failNextProjectRequest: () => {
|
||||
failNextProjectRequest = true;
|
||||
},
|
||||
renameProjectA: () =>
|
||||
client.emit({
|
||||
type: "project.update",
|
||||
payload: {
|
||||
kind: "upsert",
|
||||
project: project("A", "Renamed"),
|
||||
generation: "g",
|
||||
seq: renameSeq,
|
||||
},
|
||||
}),
|
||||
sessionProjectIds: () =>
|
||||
[...useSessionStore.getState().sessions[serverId].projects.keys()].sort(),
|
||||
persistedProjectIds: async () => {
|
||||
await reopened.flush();
|
||||
const restarted = reopen();
|
||||
restarted.setHosts([serverId]);
|
||||
return [...(await restarted.readDirectory(serverId)).projects.keys()].sort();
|
||||
},
|
||||
close: async () => {
|
||||
directory.dispose();
|
||||
await reopened.flush();
|
||||
database.close();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
it("re-syncs every project when a project update lands while an untrusted cache loads", async () => {
|
||||
const damaged = await createDamagedLegacyProjectDirectory("untrusted-checkpoint-race", 6);
|
||||
try {
|
||||
let renamed = false;
|
||||
damaged.holdRead(async () => {
|
||||
if (renamed) return;
|
||||
renamed = true;
|
||||
damaged.renameProjectA();
|
||||
});
|
||||
|
||||
damaged.directory.setDemand({}, true);
|
||||
await damaged.directory.refreshDemand();
|
||||
|
||||
expect(renamed).toBe(true);
|
||||
expect(damaged.client.lastProjectOptions).toEqual({ sync: {} });
|
||||
expect(damaged.sessionProjectIds()).toEqual(["A", "B"]);
|
||||
expect(await damaged.persistedProjectIds()).toEqual(["A", "B"]);
|
||||
} finally {
|
||||
await damaged.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("re-syncs every project when a project update lands after the first sync fails", async () => {
|
||||
const damaged = await createDamagedLegacyProjectDirectory("failed-first-sync", 3);
|
||||
try {
|
||||
damaged.failNextProjectRequest();
|
||||
damaged.directory.setDemand({}, true);
|
||||
await expect(damaged.directory.refreshDemand()).rejects.toThrow("Request timed out");
|
||||
|
||||
damaged.renameProjectA();
|
||||
await damaged.directory.refreshDemand();
|
||||
|
||||
expect(damaged.client.lastProjectOptions).toEqual({ sync: {} });
|
||||
expect(damaged.sessionProjectIds()).toEqual(["A", "B"]);
|
||||
expect(await damaged.persistedProjectIds()).toEqual(["A", "B"]);
|
||||
} finally {
|
||||
await damaged.close();
|
||||
}
|
||||
});
|
||||
|
||||
function createWorkspaceLabelDirectory(serverId: string) {
|
||||
const { client, directory } = createDirectory(serverId, { workspaceLabels: true });
|
||||
const store = useSessionStore.getState();
|
||||
|
||||
@@ -288,7 +288,7 @@ export class DirectorySync {
|
||||
this.revision += 1;
|
||||
if (this.agentTransactions.record(source, delta)) return;
|
||||
this.agents.applyDelta(delta);
|
||||
this.noteLiveCursor("agents", delta);
|
||||
if (this.extendsRefreshedBaseline(source)) this.noteLiveCursor("agents", delta);
|
||||
this.persistCheckpoint();
|
||||
}
|
||||
|
||||
@@ -300,7 +300,7 @@ export class DirectorySync {
|
||||
this.workspaceRevision += 1;
|
||||
if (this.workspaceTransactions.record(source, delta)) return;
|
||||
this.applyWorkspaceDelta(delta);
|
||||
if (delta.kind !== "script_status")
|
||||
if (delta.kind !== "script_status" && this.extendsRefreshedBaseline(source))
|
||||
this.noteLiveCursor(
|
||||
"projectId" in delta || "project" in delta ? "projects" : "workspaces",
|
||||
delta,
|
||||
@@ -308,6 +308,20 @@ export class DirectorySync {
|
||||
this.persistCheckpoint();
|
||||
}
|
||||
|
||||
/**
|
||||
* A live event's sequence covers everything before it only when a refresh completed on the
|
||||
* subscriptions that delivered it. Before that (first sync still pending or failed) or after
|
||||
* they lapse, the client may have missed earlier changes, so the event updates rows but leaves
|
||||
* the cursor where the next refresh can still fetch what was missed.
|
||||
*/
|
||||
private extendsRefreshedBaseline(source: DirectorySourceToken): boolean {
|
||||
const refreshed = this.satisfiedDemandSource;
|
||||
return (
|
||||
refreshed?.clientGeneration === source.clientGeneration &&
|
||||
refreshed.connectionEpoch === source.connectionEpoch
|
||||
);
|
||||
}
|
||||
|
||||
private observeDirectoryEvents(): void {
|
||||
if (this.eventSubscription) return;
|
||||
const { client, source } = this.requireOnline();
|
||||
@@ -566,24 +580,16 @@ export class DirectorySync {
|
||||
input: { subscribe?: boolean } | undefined,
|
||||
loadDirectoryCache: boolean,
|
||||
): Promise<void> {
|
||||
if (loadDirectoryCache) await this.loadCachedDirectory();
|
||||
if (loadDirectoryCache) {
|
||||
this.primeWorkspaceTransactionForCacheLoad();
|
||||
await this.loadCachedDirectory();
|
||||
}
|
||||
const onlineConnection = this.getOnlineConnection();
|
||||
if (!onlineConnection) return;
|
||||
const { client, source } = onlineConnection;
|
||||
const transaction = this.workspaceTransactions.begin(source, () => {
|
||||
const baseline = this.workspaces.snapshot();
|
||||
return {
|
||||
workspaces: new Map(baseline.workspaces),
|
||||
projects: new Map(baseline.projects),
|
||||
// Cache hydration can advance the live replica while these requests await responses.
|
||||
// Every page must use the cursors belonging to the maps captured here.
|
||||
requestCursors: { ...this.cursors },
|
||||
syncCursors: {},
|
||||
syncModes: {},
|
||||
touchedWorkspaceIds: new Set(),
|
||||
touchedProjectIds: new Set(),
|
||||
};
|
||||
});
|
||||
const transaction = this.workspaceTransactions.begin(source, () =>
|
||||
this.createWorkspaceRefreshSnapshot(),
|
||||
);
|
||||
try {
|
||||
await this.waitForSessionMetadata(client, source);
|
||||
const serverInfo = useSessionStore.getState().sessions[this.serverId]?.serverInfo;
|
||||
@@ -807,6 +813,31 @@ export class DirectorySync {
|
||||
}));
|
||||
}
|
||||
|
||||
// Updates that arrive before a refresh completes have no trusted baseline to advance from.
|
||||
// Holding them keeps their cursor out of the cache until the refresh they are applied over.
|
||||
private primeWorkspaceTransactionForCacheLoad(): void {
|
||||
const connection = this.getOnlineConnection();
|
||||
if (!connection) return;
|
||||
this.workspaceTransactions.begin(connection.source, () =>
|
||||
this.createWorkspaceRefreshSnapshot(),
|
||||
);
|
||||
}
|
||||
|
||||
private createWorkspaceRefreshSnapshot(): WorkspaceRefreshSnapshot {
|
||||
const baseline = this.workspaces.snapshot();
|
||||
return {
|
||||
workspaces: new Map(baseline.workspaces),
|
||||
projects: new Map(baseline.projects),
|
||||
// Cache hydration can advance the live replica while these requests await responses.
|
||||
// Every page must use the cursors belonging to the maps captured here.
|
||||
requestCursors: { ...this.cursors },
|
||||
syncCursors: {},
|
||||
syncModes: {},
|
||||
touchedWorkspaceIds: new Set(),
|
||||
touchedProjectIds: new Set(),
|
||||
};
|
||||
}
|
||||
|
||||
private supportsDirectorySync(): boolean {
|
||||
return (
|
||||
useSessionStore.getState().sessions[this.serverId]?.serverInfo?.features?.directorySync ===
|
||||
|
||||
@@ -37,6 +37,9 @@ class MemoryStorage implements ReplicaRowStore {
|
||||
onRead: (() => void) | null = null;
|
||||
/** Throws once a read goes past this count, so a non-terminating read loop fails the test. */
|
||||
readLimit: number | null = null;
|
||||
/** Awaited before the store lists every row or deletes a host, so a test can interleave there. */
|
||||
beforeReadAll: (() => Promise<void>) | null = null;
|
||||
beforeDeleteHost: (() => Promise<void>) | null = null;
|
||||
|
||||
private key(row: Pick<ReplicaRow, "serverId" | "kind" | "id">): string {
|
||||
return `${row.serverId}:${row.kind}:${row.id}`;
|
||||
@@ -68,6 +71,7 @@ class MemoryStorage implements ReplicaRowStore {
|
||||
}
|
||||
|
||||
async readAll(): Promise<ReplicaHostRows[]> {
|
||||
await this.beforeReadAll?.();
|
||||
const hosts = new Map<string, ReplicaRow[]>();
|
||||
for (const row of this.rows.values()) {
|
||||
const rows = hosts.get(row.serverId) ?? [];
|
||||
@@ -91,6 +95,7 @@ class MemoryStorage implements ReplicaRowStore {
|
||||
}
|
||||
|
||||
async deleteHost(serverId: string): Promise<void> {
|
||||
await this.beforeDeleteHost?.();
|
||||
for (const [key, row] of this.rows) if (row.serverId === serverId) this.rows.delete(key);
|
||||
}
|
||||
|
||||
@@ -436,40 +441,49 @@ describe("ReplicaCache", () => {
|
||||
await expectLegacyWorkspaceRefresh(cached);
|
||||
});
|
||||
|
||||
it("rejects pre-baseline-fix checkpoints without discarding cached rows or timelines", async () => {
|
||||
const storage = new MemoryStorage();
|
||||
const writer = createCache(storage);
|
||||
const baseline = directory();
|
||||
writer.replaceDirectoryBaseline(SERVER_ID, baseline);
|
||||
writer.commitTimeline(SERVER_ID, "agent-1", timeline());
|
||||
await writer.flush();
|
||||
await storage.apply({
|
||||
deletes: [],
|
||||
upserts: [
|
||||
{
|
||||
serverId: SERVER_ID,
|
||||
kind: "checkpoint",
|
||||
id: "singleton",
|
||||
payload: JSON.stringify(baseline.checkpoint),
|
||||
},
|
||||
],
|
||||
});
|
||||
it.each([
|
||||
["before the baseline fix", (checkpoint: DirectoryCheckpoint): unknown => checkpoint],
|
||||
[
|
||||
"before the eviction fix",
|
||||
(checkpoint: DirectoryCheckpoint): unknown => ({ version: 1, cursors: checkpoint }),
|
||||
],
|
||||
])(
|
||||
"rejects checkpoints written %s without discarding cached rows or timelines",
|
||||
async (_era, legacyPayload) => {
|
||||
const storage = new MemoryStorage();
|
||||
const writer = createCache(storage);
|
||||
const baseline = directory();
|
||||
writer.replaceDirectoryBaseline(SERVER_ID, baseline);
|
||||
writer.commitTimeline(SERVER_ID, "agent-1", timeline());
|
||||
await writer.flush();
|
||||
await storage.apply({
|
||||
deletes: [],
|
||||
upserts: [
|
||||
{
|
||||
serverId: SERVER_ID,
|
||||
kind: "checkpoint",
|
||||
id: "singleton",
|
||||
payload: JSON.stringify(legacyPayload(baseline.checkpoint)),
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const reader = createCache(storage);
|
||||
const restored = await reader.readDirectory(SERVER_ID);
|
||||
expect(restored.checkpoint).toBeUndefined();
|
||||
expect([...restored.workspaces.keys()]).toEqual([...baseline.workspaces.keys()]);
|
||||
expect([...restored.projects.keys()]).toEqual([...baseline.projects.keys()]);
|
||||
expect([...restored.agents.keys()]).toEqual([...baseline.agents.keys()]);
|
||||
expect(await reader.readTimeline(SERVER_ID, "agent-1")).toEqual(timeline());
|
||||
expect(await storage.read(SERVER_ID, ["checkpoint"])).toEqual([]);
|
||||
const reader = createCache(storage);
|
||||
const restored = await reader.readDirectory(SERVER_ID);
|
||||
expect(restored.checkpoint).toBeUndefined();
|
||||
expect([...restored.workspaces.keys()]).toEqual([...baseline.workspaces.keys()]);
|
||||
expect([...restored.projects.keys()]).toEqual([...baseline.projects.keys()]);
|
||||
expect([...restored.agents.keys()]).toEqual([...baseline.agents.keys()]);
|
||||
expect(await reader.readTimeline(SERVER_ID, "agent-1")).toEqual(timeline());
|
||||
expect(await storage.read(SERVER_ID, ["checkpoint"])).toEqual([]);
|
||||
|
||||
reader.replaceDirectoryBaseline(SERVER_ID, baseline);
|
||||
await reader.flush();
|
||||
expect((await createCache(storage).readDirectory(SERVER_ID)).checkpoint).toEqual(
|
||||
baseline.checkpoint,
|
||||
);
|
||||
});
|
||||
reader.replaceDirectoryBaseline(SERVER_ID, baseline);
|
||||
await reader.flush();
|
||||
expect((await createCache(storage).readDirectory(SERVER_ID)).checkpoint).toEqual(
|
||||
baseline.checkpoint,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
it("does nothing until an owner explicitly commits data", async () => {
|
||||
const storage = new MemoryStorage();
|
||||
@@ -1102,6 +1116,113 @@ describe("ReplicaCache", () => {
|
||||
).toEqual(["agent", "checkpoint", "project", "workspace"]);
|
||||
});
|
||||
|
||||
it.each(["beforeReadAll", "beforeDeleteHost"] as const)(
|
||||
"stores no checkpoint for a host evicted after its update was queued (%s)",
|
||||
async (pausePoint) => {
|
||||
const storage = new MemoryStorage();
|
||||
const previousSession = new ReplicaCache(storage, noLegacyCleanup);
|
||||
previousSession.setHosts([SERVER_ID, "other-host"]);
|
||||
previousSession.replaceDirectoryBaseline(SERVER_ID, directory());
|
||||
previousSession.replaceDirectoryBaseline("other-host", directory());
|
||||
await previousSession.flush();
|
||||
|
||||
const cache = new ReplicaCache(storage, { ...noLegacyCleanup, maxBytes: 8_192 });
|
||||
cache.setHosts([SERVER_ID, "other-host"]);
|
||||
const paused = deferred();
|
||||
const resume = deferred();
|
||||
storage[pausePoint] = async () => {
|
||||
storage[pausePoint] = null;
|
||||
paused.resolve();
|
||||
await resume.promise;
|
||||
};
|
||||
// Larger than the whole budget, so this persist evicts both hosts.
|
||||
cache.commitTimeline(SERVER_ID, "agent-1", timeline("x".repeat(16_384)));
|
||||
const eviction = cache.flush();
|
||||
await paused.promise;
|
||||
cache.commitDirectoryMutations(SERVER_ID, [], { agents: { generation: "g", afterSeq: 13 } });
|
||||
resume.resolve();
|
||||
await eviction;
|
||||
await cache.flush();
|
||||
|
||||
const restored = await createCache(storage).readDirectory(SERVER_ID);
|
||||
expect(restored.agents.size).toBe(0);
|
||||
expect(restored.checkpoint).toBeUndefined();
|
||||
},
|
||||
);
|
||||
|
||||
it("stores no checkpoint for a host evicted while a malformed row is repaired", async () => {
|
||||
const { storage } = await cacheWithoutBackgroundVisibility();
|
||||
const reader = createCache(storage, 8_192);
|
||||
storage.onRead = () => {
|
||||
if (!storage.reads.at(-1)?.kinds.includes("checkpoint")) return;
|
||||
storage.onRead = null;
|
||||
// Larger than the whole budget, so this persist evicts the host before the repair writes.
|
||||
reader.commitTimeline(SERVER_ID, "agent-1", timeline("x".repeat(16_384)));
|
||||
void reader.flush();
|
||||
};
|
||||
|
||||
expect(await reader.readWorkspace(SERVER_ID, "workspace-1")).toBeUndefined();
|
||||
await reader.flush();
|
||||
|
||||
const restored = await createCache(storage).readDirectory(SERVER_ID);
|
||||
expect(restored.projects.size).toBe(0);
|
||||
expect(restored.checkpoint).toBeUndefined();
|
||||
});
|
||||
|
||||
it("repairs a malformed row's cursor when the overlapping eviction fails", async () => {
|
||||
const { storage } = await cacheWithoutBackgroundVisibility();
|
||||
const reader = createCache(storage, 8_192);
|
||||
storage.onRead = () => {
|
||||
if (!storage.reads.at(-1)?.kinds.includes("checkpoint")) return;
|
||||
storage.onRead = null;
|
||||
storage.beforeDeleteHost = async () => {
|
||||
storage.beforeDeleteHost = null;
|
||||
throw new Error("Eviction aborted");
|
||||
};
|
||||
reader.commitTimeline(SERVER_ID, "agent-1", timeline("x".repeat(16_384)));
|
||||
void reader.flush();
|
||||
};
|
||||
|
||||
expect(await reader.readWorkspace(SERVER_ID, "workspace-1")).toBeUndefined();
|
||||
// A newer timeline fits the budget, so no later eviction clears the checkpoint.
|
||||
reader.commitTimeline(SERVER_ID, "agent-1", timeline());
|
||||
await reader.flush();
|
||||
|
||||
const restored = await createCache(storage).readDirectory(SERVER_ID);
|
||||
expect(restored.workspaces.size).toBe(0);
|
||||
expect(restored.checkpoint).toEqual({
|
||||
agents: { generation: "g", afterSeq: 12 },
|
||||
projects: { generation: "g", afterSeq: 4 },
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps an update queued behind the baseline that rebuilds an evicted host", async () => {
|
||||
const storage = new MemoryStorage();
|
||||
const cache = new ReplicaCache(storage, { ...noLegacyCleanup, maxBytes: 2_500 });
|
||||
cache.setHosts([SERVER_ID, "other-host"]);
|
||||
const baseline = directory();
|
||||
cache.replaceDirectoryBaseline(SERVER_ID, baseline);
|
||||
await cache.flush();
|
||||
cache.replaceDirectoryBaseline("other-host", baseline);
|
||||
await cache.flush();
|
||||
expect((await cache.readDirectory(SERVER_ID)).agents.size).toBe(0);
|
||||
|
||||
const renamed = { ...agent(), title: "Renamed agent" };
|
||||
cache.replaceDirectoryBaseline(SERVER_ID, baseline);
|
||||
cache.commitDirectoryMutations(
|
||||
SERVER_ID,
|
||||
[{ kind: "agent", type: "upsert", id: renamed.id, value: renamed }],
|
||||
{ agents: { generation: "g", afterSeq: 13 } },
|
||||
);
|
||||
await cache.flush();
|
||||
cache.commitDirectoryMutations(SERVER_ID, [], { agents: { generation: "g", afterSeq: 14 } });
|
||||
await cache.flush();
|
||||
|
||||
const restored = await createCache(storage).readDirectory(SERVER_ID);
|
||||
expect(restored.checkpoint).toEqual({ agents: { generation: "g", afterSeq: 14 } });
|
||||
expect(restored.agents.get(renamed.id)?.title).toBe("Renamed agent");
|
||||
});
|
||||
|
||||
it("runs legacy cleanup once when storage is first used", async () => {
|
||||
const storage = new MemoryStorage();
|
||||
const cache = new ReplicaCache(storage, {
|
||||
|
||||
@@ -397,15 +397,19 @@ const DirectoryCheckpointSchema = z.strictObject({
|
||||
agents: DirectoryCursorSchema.optional(),
|
||||
});
|
||||
|
||||
// Old checkpoints could describe a baseline that an overlapping refresh had discarded.
|
||||
// Revalidate directory contents once without evicting cached rows or timelines.
|
||||
// A checkpoint is trusted only when this version wrote it. Earlier writers could store one for a
|
||||
// directory the cache no longer held: unversioned ones after an overlapping refresh, version 1
|
||||
// after an eviction. Rejecting them revalidates directory contents once without evicting cached
|
||||
// rows or timelines.
|
||||
const DIRECTORY_CHECKPOINT_VERSION = 2;
|
||||
|
||||
const StoredDirectoryCheckpointSchema = z.strictObject({
|
||||
version: z.literal(1),
|
||||
version: z.literal(DIRECTORY_CHECKPOINT_VERSION),
|
||||
cursors: DirectoryCheckpointSchema,
|
||||
});
|
||||
|
||||
function serializeDirectoryCheckpoint(cursors: DirectoryCheckpoint) {
|
||||
return { version: 1 as const, cursors };
|
||||
return { version: DIRECTORY_CHECKPOINT_VERSION, cursors };
|
||||
}
|
||||
|
||||
function deserializeDirectoryCheckpoint(payload: string): DirectoryCheckpoint {
|
||||
@@ -968,6 +972,7 @@ export class ReplicaCache {
|
||||
private pendingUpserts = new Map<string, StructuredReplicaUpsert>();
|
||||
private pendingDeletes = new Map<string, ReplicaRowKey>();
|
||||
private pendingBaselines = new Set<string>();
|
||||
// Hosts whose stored directory was evicted. Only a baseline stores their directory again.
|
||||
private readonly invalidatedHosts = new Set<string>();
|
||||
private readonly maxBytes: number;
|
||||
private totalBytes = 0;
|
||||
@@ -1109,11 +1114,7 @@ export class ReplicaCache {
|
||||
private async deleteInvalidRow(row: ReplicaRow): Promise<void> {
|
||||
const invalidEntity = directoryEntityForRow(row);
|
||||
if (!invalidEntity) {
|
||||
const changes = { upserts: [], deletes: [row] } satisfies ReplicaRowChanges;
|
||||
await this.queueOperation(async () => {
|
||||
await this.rowStore.apply(changes);
|
||||
this.applyStoredChanges(changes);
|
||||
});
|
||||
await this.applyRepair(row.serverId, { upserts: [], deletes: [row] });
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1144,10 +1145,7 @@ export class ReplicaCache {
|
||||
]
|
||||
: [],
|
||||
};
|
||||
await this.queueOperation(async () => {
|
||||
await this.rowStore.apply(changes);
|
||||
this.applyStoredChanges(changes);
|
||||
});
|
||||
await this.applyRepair(row.serverId, changes);
|
||||
}
|
||||
|
||||
private async repairInvalidDirectoryRows(
|
||||
@@ -1170,9 +1168,16 @@ export class ReplicaCache {
|
||||
]
|
||||
: [],
|
||||
};
|
||||
await this.queueOperation(async () => {
|
||||
await this.rowStore.apply(changes);
|
||||
this.applyStoredChanges(changes);
|
||||
await this.applyRepair(serverId, changes);
|
||||
}
|
||||
|
||||
// A repair is queued behind writes that can evict its host. If one did, the host has no
|
||||
// directory left for the repaired checkpoint to describe, so only the deletes still apply.
|
||||
private applyRepair(serverId: string, changes: ReplicaRowChanges): Promise<void> {
|
||||
return this.queueOperation(async () => {
|
||||
const applied = this.invalidatedHosts.has(serverId) ? { ...changes, upserts: [] } : changes;
|
||||
await this.rowStore.apply(applied);
|
||||
this.applyStoredChanges(applied);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1182,7 +1187,6 @@ export class ReplicaCache {
|
||||
checkpoint?: DirectoryCheckpoint,
|
||||
): void {
|
||||
if (!this.activeServerIds.has(serverId)) return;
|
||||
if (this.invalidatedHosts.has(serverId)) return;
|
||||
for (const mutation of mutations) {
|
||||
if (mutation.type === "delete") {
|
||||
this.queueEntityDelete(serverId, mutation.kind, mutation.id);
|
||||
@@ -1412,9 +1416,17 @@ export class ReplicaCache {
|
||||
}
|
||||
|
||||
private materializePendingChanges(pending: PendingReplicaChanges): ReplicaRowChanges {
|
||||
const deletes = new Map(pending.deletes.map((row) => [pendingRowKey(row), row]));
|
||||
// Decided here, inside the serialized write, because eviction happens there too. A mutation
|
||||
// queued before its host was evicted would otherwise store a checkpoint without its directory.
|
||||
const isStorable = (row: ReplicaRowKey): boolean =>
|
||||
row.kind === "timeline" ||
|
||||
!this.invalidatedHosts.has(row.serverId) ||
|
||||
pending.baselines.has(row.serverId);
|
||||
const deletes = new Map(
|
||||
pending.deletes.filter(isStorable).map((row) => [pendingRowKey(row), row]),
|
||||
);
|
||||
const upserts: ReplicaRow[] = [];
|
||||
for (const upsert of pending.upserts) {
|
||||
for (const upsert of pending.upserts.filter(isStorable)) {
|
||||
const row = this.materializeUpsert(upsert);
|
||||
if (row) upserts.push(row);
|
||||
else deletes.set(pendingRowKey(upsert), upsert);
|
||||
@@ -1563,8 +1575,10 @@ export class ReplicaCache {
|
||||
projectedTotal -= bytes;
|
||||
projectedBytes.delete(serverId);
|
||||
evicted.add(serverId);
|
||||
this.invalidatedHosts.add(serverId);
|
||||
if (this.storedRows.has(serverId)) await this.rowStore.deleteHost(serverId);
|
||||
// Only after the delete commits: a failed eviction leaves the rows stored, and writers that
|
||||
// check this set must keep their checkpoint in step with those rows.
|
||||
this.invalidatedHosts.add(serverId);
|
||||
this.removeStoredHost(serverId);
|
||||
}
|
||||
|
||||
|
||||
@@ -20,8 +20,6 @@ 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",
|
||||
@@ -42,9 +40,8 @@ it("updates compact header actions on panel changes without rendering the worksp
|
||||
title="Workspace"
|
||||
subtitle="Project"
|
||||
isSubtitleDistinct
|
||||
onToggleExplorer={noop}
|
||||
explorerToggleLabel="Explorer"
|
||||
explorerToggleAccessibilityState={explorerState}
|
||||
explorerAction={null}
|
||||
inDesktopTitlebar={false}
|
||||
tabSwitcher={null}
|
||||
headerVariant="full"
|
||||
>
|
||||
|
||||
@@ -1,11 +1,6 @@
|
||||
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,
|
||||
@@ -23,10 +18,9 @@ interface CompactWorkspaceHeaderProps {
|
||||
title: string;
|
||||
subtitle: string;
|
||||
isSubtitleDistinct: boolean;
|
||||
onToggleExplorer: () => void;
|
||||
explorerToggleLabel: string;
|
||||
explorerToggleAccessibilityState: { expanded: boolean };
|
||||
explorerAction: ReactNode;
|
||||
tabSwitcher: ReactNode;
|
||||
inDesktopTitlebar: boolean;
|
||||
/** Workspace overflow menu. */
|
||||
children: ReactNode;
|
||||
headerVariant: "compact" | "full";
|
||||
@@ -40,17 +34,15 @@ export function CompactWorkspaceHeader({
|
||||
title,
|
||||
subtitle,
|
||||
isSubtitleDistinct,
|
||||
onToggleExplorer,
|
||||
explorerToggleLabel,
|
||||
explorerToggleAccessibilityState,
|
||||
explorerAction,
|
||||
children,
|
||||
tabSwitcher,
|
||||
inDesktopTitlebar,
|
||||
serverId,
|
||||
headerVariant,
|
||||
isRouteFocused,
|
||||
isCompact,
|
||||
}: CompactWorkspaceHeaderProps) {
|
||||
const { t } = useTranslation();
|
||||
const actionsInBar = resolveWorkspaceActionPlacement(useWindowLayout()) === "vertical-bar";
|
||||
const projectRow = useMemo(
|
||||
() => (
|
||||
@@ -65,16 +57,7 @@ export function CompactWorkspaceHeader({
|
||||
const symbols = {
|
||||
"tab-count": tabSwitcher,
|
||||
overflow: children,
|
||||
explorer: (
|
||||
<WorkspaceExplorerToggle
|
||||
onPress={onToggleExplorer}
|
||||
label={explorerToggleLabel}
|
||||
tooltipLabel={t("workspace.tabs.explorerSidebar.toggle")}
|
||||
tooltipKeys={EXPLORER_TOGGLE_KEYS}
|
||||
accessibilityState={explorerToggleAccessibilityState}
|
||||
mobile
|
||||
/>
|
||||
),
|
||||
explorer: explorerAction,
|
||||
};
|
||||
const actions = resolveWorkspaceBarActions(headerVariant).map((symbol) => (
|
||||
<Fragment key={symbol}>{symbols[symbol]}</Fragment>
|
||||
@@ -85,6 +68,7 @@ export function CompactWorkspaceHeader({
|
||||
{headerVariant === "compact" ? (
|
||||
<CompactHeader
|
||||
navigation="menu"
|
||||
inDesktopTitlebar={inDesktopTitlebar}
|
||||
title={title}
|
||||
titleTestID="workspace-header-title"
|
||||
subtitle={projectRow}
|
||||
|
||||
@@ -1,47 +1,37 @@
|
||||
import { useMemo } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { PanelRight } from "lucide-react-native";
|
||||
import { type StyleProp, type ViewStyle } from "react-native";
|
||||
import { withUnistyles } from "react-native-unistyles";
|
||||
import { HeaderToggleButton } from "@/components/headers/header-toggle-button";
|
||||
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 { 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);
|
||||
|
||||
export const EXPLORER_TOGGLE_KEYS: ShortcutKey[] = ["mod", "E"];
|
||||
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>;
|
||||
}
|
||||
|
||||
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({
|
||||
function WorkspaceExplorerToggle({
|
||||
onPress,
|
||||
label,
|
||||
tooltipLabel,
|
||||
tooltipKeys,
|
||||
accessibilityState,
|
||||
mobile,
|
||||
style,
|
||||
@@ -51,7 +41,7 @@ export function WorkspaceExplorerToggle({
|
||||
testID="workspace-explorer-toggle"
|
||||
onPress={onPress}
|
||||
tooltipLabel={tooltipLabel}
|
||||
tooltipKeys={tooltipKeys}
|
||||
tooltipKeys={EXPLORER_TOGGLE_KEYS}
|
||||
tooltipSide="left"
|
||||
style={style}
|
||||
accessible
|
||||
@@ -68,42 +58,97 @@ export function WorkspaceExplorerToggle({
|
||||
);
|
||||
}
|
||||
|
||||
interface DesktopWorkspaceExplorerToggleProps extends Omit<WorkspaceExplorerToggleProps, "mobile"> {
|
||||
owner: WorkspaceExplorerToggleOwner;
|
||||
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]);
|
||||
}
|
||||
|
||||
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} />;
|
||||
}
|
||||
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,
|
||||
},
|
||||
}));
|
||||
|
||||
@@ -157,17 +157,8 @@ 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 {
|
||||
resolveWorkspaceExplorerToggleOwner,
|
||||
EXPLORER_TOGGLE_KEYS,
|
||||
WorkspaceExplorerSidebarToggle,
|
||||
WorkspaceHeaderExplorerToggle,
|
||||
} from "@/screens/workspace/workspace-explorer-toggle";
|
||||
import {
|
||||
useHasWindowChromeObstruction,
|
||||
WindowChromeRegion,
|
||||
WindowChromeSafeArea,
|
||||
} from "@/utils/desktop-window";
|
||||
import { useWorkspaceExplorerControls } from "@/screens/workspace/workspace-explorer-toggle";
|
||||
import { WindowChromeRegion, WindowChromeSafeArea } from "@/utils/desktop-window";
|
||||
import {
|
||||
resolveWorkspaceHeaderRenderState,
|
||||
type WorkspaceHeaderCheckoutState,
|
||||
@@ -1058,12 +1049,8 @@ 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]);
|
||||
@@ -1308,11 +1295,6 @@ 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
|
||||
@@ -1820,9 +1802,6 @@ function WorkspaceScreenContent({
|
||||
}),
|
||||
[t],
|
||||
);
|
||||
const explorerSidebarToggleLabel = isExplorerSidebarShowing
|
||||
? t("workspace.tabs.explorerSidebar.close")
|
||||
: t("workspace.tabs.explorerSidebar.open");
|
||||
|
||||
const activeTabKey = useMemo(() => activeTabId ?? "", [activeTabId]);
|
||||
const handleCreateDraftTab = useCallback(
|
||||
@@ -3228,6 +3207,13 @@ function WorkspaceScreenContent({
|
||||
workspaceKey: persistenceKey,
|
||||
});
|
||||
|
||||
const explorerControls = useWorkspaceExplorerControls({
|
||||
hasWorkspace: !!workspaceDirectory,
|
||||
compact: isMobile,
|
||||
focusMode: desktopFocusModeEnabled,
|
||||
expanded: isExplorerSidebarShowing,
|
||||
onToggle: handleToggleExplorerSidebar,
|
||||
});
|
||||
const headerRight = useMemo(
|
||||
() => (
|
||||
<View style={styles.headerRight}>
|
||||
@@ -3254,17 +3240,7 @@ function WorkspaceScreenContent({
|
||||
{workspaceDirectory ? (
|
||||
<>
|
||||
<WorkspaceActions serverId={normalizedServerId} cwd={workspaceDirectory} />
|
||||
{workspaceActionsInBar ? null : (
|
||||
<WorkspaceHeaderExplorerToggle
|
||||
owner={explorerToggleOwner}
|
||||
onPress={handleToggleExplorerSidebar}
|
||||
label={explorerSidebarToggleLabel}
|
||||
tooltipLabel={t("workspace.tabs.explorerSidebar.toggle")}
|
||||
tooltipKeys={EXPLORER_TOGGLE_KEYS}
|
||||
style={styles.compactHeaderActionButton}
|
||||
accessibilityState={explorerSidebarToggleAccessibilityState}
|
||||
/>
|
||||
)}
|
||||
{workspaceActionsInBar ? null : explorerControls.headerAction}
|
||||
</>
|
||||
) : null}
|
||||
</View>
|
||||
@@ -3279,12 +3255,8 @@ function WorkspaceScreenContent({
|
||||
scriptActions,
|
||||
handleViewScriptTerminal,
|
||||
handleOpenUrlInBrowserTab,
|
||||
handleToggleExplorerSidebar,
|
||||
explorerSidebarToggleLabel,
|
||||
explorerSidebarToggleAccessibilityState,
|
||||
explorerToggleOwner,
|
||||
explorerControls.headerAction,
|
||||
workspaceActionsInBar,
|
||||
t,
|
||||
],
|
||||
);
|
||||
|
||||
@@ -3292,25 +3264,6 @@ 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],
|
||||
@@ -3333,10 +3286,6 @@ 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}`,
|
||||
@@ -3460,14 +3409,13 @@ 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}
|
||||
@@ -3493,20 +3441,19 @@ function WorkspaceScreenContent({
|
||||
},
|
||||
[
|
||||
renderWorkspaceTabSwitcher,
|
||||
explorerControls.inDesktopTitlebar,
|
||||
explorerControls.compactAction,
|
||||
isFocusModeEnabled,
|
||||
toggleFocusMode,
|
||||
canOpenImportSheet,
|
||||
compactHeaderScripts,
|
||||
createTerminalDisabled,
|
||||
currentBranchName,
|
||||
explorerSidebarToggleAccessibilityState,
|
||||
explorerSidebarToggleLabel,
|
||||
handleCopyBranchName,
|
||||
handleCopyWorkspacePath,
|
||||
handleCreateBrowserTab,
|
||||
handleCreateTerminalWithProfile,
|
||||
handleOpenSetupTab,
|
||||
handleToggleExplorerSidebar,
|
||||
isMobile,
|
||||
isRouteFocused,
|
||||
isWorkspaceHeaderLoading,
|
||||
@@ -3734,7 +3681,7 @@ function WorkspaceScreenContent({
|
||||
onExitFocusMode={toggleFocusMode}
|
||||
onReorderTabsInPane={handleReorderTabsInPane}
|
||||
buildPaneContentModel={buildDesktopPaneContentModel}
|
||||
headerAction={renderExplorerSidebarHeaderAction()}
|
||||
headerAction={explorerControls.dockAction}
|
||||
/>
|
||||
);
|
||||
return (
|
||||
@@ -3775,7 +3722,7 @@ function WorkspaceScreenContent({
|
||||
toggleFocusMode,
|
||||
handleReorderTabsInPane,
|
||||
buildDesktopPaneContentModel,
|
||||
renderExplorerSidebarHeaderAction,
|
||||
explorerControls.dockAction,
|
||||
desktopFocusModeEnabled,
|
||||
]);
|
||||
|
||||
@@ -3849,6 +3796,7 @@ function WorkspaceScreenContent({
|
||||
onReorderTabsInPane={handleReorderTabsInPane}
|
||||
onSplitPane={handleSplitPane}
|
||||
>
|
||||
{explorerControls.titlebarAction}
|
||||
{workspaceCenterColumn}
|
||||
{sharedExplorer}
|
||||
</WorkspaceTabDragScope>
|
||||
@@ -3986,12 +3934,6 @@ const styles = StyleSheet.create((theme) => ({
|
||||
md: theme.spacing[2],
|
||||
},
|
||||
},
|
||||
compactHeaderActionButton: {
|
||||
marginRight: {
|
||||
xs: 0,
|
||||
md: -theme.spacing[2],
|
||||
},
|
||||
},
|
||||
compactHeaderMenuCluster: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
|
||||
@@ -1,10 +1,5 @@
|
||||
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 {
|
||||
@@ -190,37 +185,6 @@ 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,12 +1053,19 @@ export class TerminalEmulatorRuntime {
|
||||
if (!terminal) {
|
||||
return;
|
||||
}
|
||||
terminal.textarea?.removeAttribute("virtualkeyboardpolicy");
|
||||
if (input?.forceRefocus) {
|
||||
terminal.blur();
|
||||
}
|
||||
terminal.focus();
|
||||
}
|
||||
|
||||
suppressAutomaticKeyboard(): void {
|
||||
// Android Chrome can reopen the keyboard during a drag after Back leaves the input
|
||||
// focused. Manual policy prevents that without closing an already open keyboard.
|
||||
this.terminal?.textarea?.setAttribute("virtualkeyboardpolicy", "manual");
|
||||
}
|
||||
|
||||
blur(): void {
|
||||
this.terminal?.blur();
|
||||
}
|
||||
|
||||
@@ -92,13 +92,14 @@ test("visible catch-up settles before hidden open chats start fetching", async (
|
||||
world.sync.dispose();
|
||||
});
|
||||
|
||||
test("a failed visible catch-up releases hidden chats without bypassing its error", async () => {
|
||||
test("a failed visible catch-up with a parked gap releases hidden chats without retrying", async () => {
|
||||
const world = new TimelineWorld();
|
||||
world.openedEarlier(["a-hidden"]);
|
||||
world.sync.replaceVisibleAgentIds("pane", ["z-visible"]);
|
||||
world.sync.setConnected(true);
|
||||
(await world.nextMembership()).succeed();
|
||||
const visible = await world.nextFetch("z-visible");
|
||||
world.sync.recoverGap("z-visible", { epoch: "epoch-z-visible", endSeq: 1 });
|
||||
world.expectNoPendingFetch();
|
||||
visible.fail("temporarily unavailable");
|
||||
const hidden = await world.nextFetch("a-hidden");
|
||||
@@ -127,6 +128,63 @@ test("switching chats promotes the newly visible catch-up while another visible
|
||||
world.sync.dispose();
|
||||
});
|
||||
|
||||
test("reconnect drains hidden chats two at a time after the visible chat settles", async () => {
|
||||
const world = new TimelineWorld();
|
||||
const hidden = Array.from({ length: 15 }, (_, index) => `hidden-${10 + index}`);
|
||||
world.openedEarlier(hidden);
|
||||
world.show("pane", ["visible"]);
|
||||
world.sync.setConnected(true);
|
||||
(await world.nextMembership()).succeed();
|
||||
const beforeDisconnect = await world.nextFetch("visible");
|
||||
world.sync.setConnected(false);
|
||||
beforeDisconnect.respond({ hasNewer: false });
|
||||
world.sync.setConnected(true);
|
||||
(await world.nextMembership()).succeed();
|
||||
const visible = await world.nextFetch("visible");
|
||||
world.expectNoPendingFetch();
|
||||
visible.respond({ hasNewer: false });
|
||||
const first = await world.nextFetch(hidden[0]);
|
||||
let current = await world.nextFetch(hidden[1]);
|
||||
world.expectNoPendingFetch();
|
||||
|
||||
first.fail("timeline request timed out");
|
||||
for (const agentId of hidden.slice(2)) {
|
||||
const next = await world.nextFetch(agentId);
|
||||
world.expectNoPendingFetch();
|
||||
current.respond({ hasNewer: false });
|
||||
current = next;
|
||||
}
|
||||
current.respond({ hasNewer: false });
|
||||
await vi.waitFor(() => {
|
||||
expect(world.sync.getAgentTimelineStatus(hidden[0])).toBe("error");
|
||||
for (const agentId of hidden.slice(1)) {
|
||||
expect(world.sync.getAgentTimelineStatus(agentId)).toBe("ready");
|
||||
}
|
||||
});
|
||||
world.expectNoPendingFetch();
|
||||
world.sync.dispose();
|
||||
});
|
||||
|
||||
test("focusing a queued chat starts it while both hidden catch-ups are running", async () => {
|
||||
const world = new TimelineWorld();
|
||||
world.openedEarlier(["hidden-a", "hidden-b", "next-visible"]);
|
||||
world.show("pane", ["visible"]);
|
||||
world.sync.setConnected(true);
|
||||
(await world.nextMembership()).succeed();
|
||||
(await world.nextFetch("visible")).respond({ hasNewer: false });
|
||||
const first = await world.nextFetch("hidden-a");
|
||||
const second = await world.nextFetch("hidden-b");
|
||||
world.expectNoPendingFetch();
|
||||
|
||||
world.show("pane", ["next-visible"]);
|
||||
expect(world.pendingFetchCount).toBe(1);
|
||||
(await world.nextFetch("next-visible")).respond({ hasNewer: false });
|
||||
await vi.waitFor(() => expect(world.sync.getAgentTimelineStatus("next-visible")).toBe("ready"));
|
||||
first.respond({ hasNewer: false });
|
||||
second.respond({ hasNewer: false });
|
||||
world.sync.dispose();
|
||||
});
|
||||
|
||||
class TimelineWorld {
|
||||
constructor(
|
||||
private readonly observeMembership?: ViewedTimelineSyncPorts["observe"],
|
||||
@@ -441,7 +499,7 @@ test("a gap absorbed by a running tail is recovered after the tail completes", a
|
||||
await vi.waitFor(() => expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("ready"));
|
||||
});
|
||||
|
||||
test("a gap parked behind a running tail resumes after the rows that tail applied", async () => {
|
||||
test("a parked gap pages forward from the coverage established by the running tail", async () => {
|
||||
const world = new TimelineWorld();
|
||||
world.sync.setConnected(true);
|
||||
world.sync.replaceVisibleAgentIds("workspace", ["agent-a"]);
|
||||
@@ -460,7 +518,13 @@ test("a gap parked behind a running tail resumes after the rows that tail applie
|
||||
projection: "projected",
|
||||
wholeTurns: true,
|
||||
});
|
||||
recovery.respond({ hasNewer: false, seq: 7 });
|
||||
recovery.respond({ hasNewer: true, seq: 47 });
|
||||
const followUp = await world.nextFetch("agent-a");
|
||||
expect(followUp.request).toMatchObject({
|
||||
direction: "after",
|
||||
cursor: { epoch: "epoch-agent-a", seq: 47 },
|
||||
});
|
||||
followUp.respond({ hasNewer: false, seq: 55 });
|
||||
await vi.waitFor(() => expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("ready"));
|
||||
world.sync.dispose();
|
||||
});
|
||||
@@ -941,14 +1005,51 @@ test("redeclaring unchanged visibility does not bypass catch-up error", async ()
|
||||
await world.nextError();
|
||||
|
||||
world.sync.replaceVisibleAgentIds("workspace", ["agent-a"]);
|
||||
world.sync.setActive(false);
|
||||
world.sync.setActive(true);
|
||||
|
||||
world.expectNoPendingMembership();
|
||||
world.expectNoPendingFetch();
|
||||
expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("error");
|
||||
});
|
||||
|
||||
test.each(["refocusing", "foregrounding"])(
|
||||
"%s retries a timed-out visible timeline once",
|
||||
async (trigger) => {
|
||||
const world = new TimelineWorld();
|
||||
world.show("pane", ["agent-a"]);
|
||||
world.sync.setConnected(true);
|
||||
(await world.nextMembership()).succeed();
|
||||
(await world.nextFetch("agent-a")).fail("timeline request timed out");
|
||||
await world.nextError();
|
||||
expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("error");
|
||||
|
||||
const revisit = () => {
|
||||
if (trigger === "refocusing") {
|
||||
world.show("pane", []);
|
||||
world.show("pane", ["agent-a"]);
|
||||
} else {
|
||||
world.sync.setActive(false);
|
||||
world.sync.setActive(true);
|
||||
}
|
||||
};
|
||||
revisit();
|
||||
expect(world.pendingFetchCount).toBe(1);
|
||||
expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("pending");
|
||||
(await world.nextFetch("agent-a")).fail("timeline request timed out again");
|
||||
await vi.waitFor(() => expect(world.errors).toHaveLength(2));
|
||||
expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("error");
|
||||
world.show("pane", ["agent-a"]);
|
||||
world.sync.setActive(true);
|
||||
world.expectNoPendingFetch();
|
||||
|
||||
revisit();
|
||||
(await world.nextFetch("agent-a")).respond({ hasNewer: false });
|
||||
await vi.waitFor(() => expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("ready"));
|
||||
expect(world.sync.getAgentTimelineError("agent-a")).toBeNull();
|
||||
world.expectNoPendingMembership();
|
||||
world.sync.dispose();
|
||||
},
|
||||
);
|
||||
|
||||
test("a manual retry that fails returns to the error state", async () => {
|
||||
const world = new TimelineWorld();
|
||||
world.sync.setConnected(true);
|
||||
@@ -968,6 +1069,37 @@ test("a manual retry that fails returns to the error state", async () => {
|
||||
await vi.waitFor(() => expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("error"));
|
||||
});
|
||||
|
||||
test("refocusing during a membership update retries a reconnect without replaying the backlog", async () => {
|
||||
const world = freshnessWorld();
|
||||
world.cursors.set("agent-a", { epoch: "epoch-agent-a", endSeq: 42 });
|
||||
world.show("pane", ["agent-a"]);
|
||||
world.sync.setConnected(true);
|
||||
(await world.nextMembership()).succeed({ "agent-a": "current" });
|
||||
await vi.waitFor(() => expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("ready"));
|
||||
|
||||
world.sync.setConnected(false);
|
||||
world.sync.setConnected(true);
|
||||
(await world.nextMembership()).succeed({ "agent-a": "behind" });
|
||||
const failed = await world.nextFetch("agent-a");
|
||||
expect(failed.request.direction).toBe("after");
|
||||
failed.fail("timeline request timed out");
|
||||
await world.nextError();
|
||||
|
||||
world.show("pane", ["agent-b"]);
|
||||
const membership = await world.nextMembership();
|
||||
world.show("pane", ["agent-a"]);
|
||||
expect(world.pendingFetchCount).toBe(1);
|
||||
const retry = await world.nextFetch("agent-a");
|
||||
expect(retry.request).toEqual(failed.request);
|
||||
membership.succeed();
|
||||
retry.respond({ hasNewer: true, seq: 82 });
|
||||
const tail = await world.nextFetch("agent-a");
|
||||
expect(tail.request.direction).toBe("tail");
|
||||
tail.respond({ hasNewer: false });
|
||||
await vi.waitFor(() => expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("ready"));
|
||||
world.sync.dispose();
|
||||
});
|
||||
|
||||
test("gap recovery supersedes completed catch-up and pages through the current tail", async () => {
|
||||
const world = new TimelineWorld();
|
||||
world.sync.setConnected(true);
|
||||
|
||||
@@ -545,12 +545,27 @@ export function createViewedTimelineOwner(input: {
|
||||
};
|
||||
}
|
||||
|
||||
const MAX_HIDDEN_CATCH_UPS = 2;
|
||||
|
||||
type CatchUpStatus = "running" | "complete" | "error";
|
||||
|
||||
interface CatchUpRequest {
|
||||
page: ProjectedTimelineForwardFetchPlan;
|
||||
kind: "resume" | "gap";
|
||||
}
|
||||
|
||||
interface CatchUpState {
|
||||
generation: number;
|
||||
status: CatchUpStatus;
|
||||
request?: ProjectedTimelineForwardFetchPlan;
|
||||
request?: CatchUpRequest;
|
||||
}
|
||||
|
||||
function planCatchUpRequest(
|
||||
request: CatchUpRequest | undefined,
|
||||
applied: { epoch: string; endSeq: number } | undefined,
|
||||
): CatchUpRequest {
|
||||
if (!request) return { page: planTimelineResumeFetch(applied), kind: "resume" };
|
||||
return { ...request, page: planTimelineCatchUpPastApplied(request.page, applied) };
|
||||
}
|
||||
|
||||
function isSameCatchUpRequest(
|
||||
@@ -573,11 +588,11 @@ function decideCatchUp(input: {
|
||||
if (input.supersede) {
|
||||
if (
|
||||
input.current.status === "running" &&
|
||||
isSameCatchUpRequest(input.current.request, input.request)
|
||||
isSameCatchUpRequest(input.current.request?.page, input.request)
|
||||
) {
|
||||
return "keep";
|
||||
}
|
||||
if (input.current.status === "running" && input.current.request?.direction === "tail") {
|
||||
if (input.current.status === "running" && input.current.request?.page.direction === "tail") {
|
||||
return "keep-and-park";
|
||||
}
|
||||
return "replace";
|
||||
@@ -597,9 +612,11 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
|
||||
const sources = new Map<string, string[]>();
|
||||
const catchUps = new Map<string, CatchUpState>();
|
||||
const catchUpGenerations = new Map<string, number>();
|
||||
// Authoritative fetch owed but not runnable yet: disconnected, unacknowledged, or parked.
|
||||
// Fetches can outlive their catch-up generation when superseded or when a tab closes.
|
||||
const inFlightCatchUps = new Set<{ agentId: string }>();
|
||||
// Authoritative fetch owed but not runnable yet: disconnected, unacknowledged, or queued.
|
||||
// Membership acknowledgement and catch-up completion drain parked requests.
|
||||
const pendingCatchUps = new Map<string, ProjectedTimelineForwardFetchPlan>();
|
||||
const pendingCatchUps = new Map<string, CatchUpRequest>();
|
||||
const visibilityCatchUpPending = new Set<string>();
|
||||
const visibilityCatchUpErrors = new Map<string, string>();
|
||||
// A user-initiated retry owes a pending state until it settles.
|
||||
@@ -723,16 +740,16 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
|
||||
const fetchUntilCurrent = async (
|
||||
agentId: string,
|
||||
generation: number,
|
||||
request: ProjectedTimelineForwardFetchPlan,
|
||||
request: CatchUpRequest,
|
||||
fallbackToLatestTailOnOverflow: boolean,
|
||||
): Promise<void> => {
|
||||
if (!ownsCatchUp(agentId, generation)) return;
|
||||
|
||||
try {
|
||||
const page = await ports.fetchPage(agentId, request);
|
||||
const page = await ports.fetchPage(agentId, request.page);
|
||||
if (!ownsCatchUp(agentId, generation)) return;
|
||||
if (page.hasNewer && page.endCursor) {
|
||||
if (fallbackToLatestTailOnOverflow) {
|
||||
if (request.page.direction === "after" && fallbackToLatestTailOnOverflow) {
|
||||
await ports.fetchLatestTail(agentId);
|
||||
if (!ownsCatchUp(agentId, generation)) return;
|
||||
catchUps.set(agentId, { generation, status: "complete" });
|
||||
@@ -742,10 +759,13 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
|
||||
await fetchUntilCurrent(
|
||||
agentId,
|
||||
generation,
|
||||
planTimelineCatchUpPastApplied(
|
||||
planTimelineCatchUpAfter(page.endCursor),
|
||||
ports.readCursor(agentId),
|
||||
),
|
||||
{
|
||||
...request,
|
||||
page: planTimelineCatchUpPastApplied(
|
||||
planTimelineCatchUpAfter(page.endCursor),
|
||||
ports.readCursor(agentId),
|
||||
),
|
||||
},
|
||||
false,
|
||||
);
|
||||
return;
|
||||
@@ -754,20 +774,15 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
|
||||
throw new Error(`Timeline page for ${agentId} hasNewer without an end cursor`);
|
||||
}
|
||||
catchUps.set(agentId, { generation, status: "complete" });
|
||||
const pendingCatchUp = pendingCatchUps.get(agentId);
|
||||
if (pendingCatchUp) {
|
||||
startCatchUp(agentId, { request: pendingCatchUp, supersede: true });
|
||||
return;
|
||||
}
|
||||
setVisibilityCatchUpReady(agentId);
|
||||
if (!pendingCatchUps.has(agentId)) setVisibilityCatchUpReady(agentId);
|
||||
} catch (error) {
|
||||
if (catchUps.get(agentId)?.generation === generation) {
|
||||
// The parked follow-up belongs to the failed attempt. A retry owns the next request.
|
||||
pendingCatchUps.delete(agentId);
|
||||
catchUps.set(agentId, { generation, status: "error", request });
|
||||
setVisibilityCatchUpError([agentId], error);
|
||||
ports.reportError(error);
|
||||
}
|
||||
} finally {
|
||||
startAcknowledgedCatchUps();
|
||||
}
|
||||
};
|
||||
|
||||
@@ -798,23 +813,29 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
|
||||
);
|
||||
};
|
||||
|
||||
const hiddenCatchUpSlotsAreFull = (agentId: string) => {
|
||||
const visible = new Set(visibleAgentIds());
|
||||
if (visible.has(agentId)) return false;
|
||||
let hidden = 0;
|
||||
for (const attempt of inFlightCatchUps) {
|
||||
if (!visible.has(attempt.agentId)) hidden += 1;
|
||||
}
|
||||
return hidden >= MAX_HIDDEN_CATCH_UPS;
|
||||
};
|
||||
|
||||
const startCatchUp = (
|
||||
agentId: string,
|
||||
options: {
|
||||
request?: ProjectedTimelineForwardFetchPlan;
|
||||
request?: CatchUpRequest;
|
||||
supersede?: boolean;
|
||||
} = {},
|
||||
) => {
|
||||
const { request, supersede = false } = options;
|
||||
if (freshnessChecks.has(agentId)) {
|
||||
if (request) pendingCatchUps.set(agentId, request);
|
||||
return;
|
||||
}
|
||||
if (!canCatchUp(agentId)) {
|
||||
if (request) pendingCatchUps.set(agentId, request);
|
||||
return;
|
||||
}
|
||||
if (shouldWaitForVisibleCatchUp(agentId)) {
|
||||
if (
|
||||
freshnessChecks.has(agentId) ||
|
||||
!canCatchUp(agentId) ||
|
||||
shouldWaitForVisibleCatchUp(agentId)
|
||||
) {
|
||||
if (request) pendingCatchUps.set(agentId, request);
|
||||
return;
|
||||
}
|
||||
@@ -824,11 +845,9 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
|
||||
return;
|
||||
}
|
||||
const applied = ports.readCursor(agentId);
|
||||
const nextRequest = request
|
||||
? planTimelineCatchUpPastApplied(request, applied)
|
||||
: planTimelineResumeFetch(applied);
|
||||
const nextRequest = planCatchUpRequest(request, applied);
|
||||
const current = catchUps.get(agentId);
|
||||
const decision = decideCatchUp({ current, request: nextRequest, supersede });
|
||||
const decision = decideCatchUp({ current, request: nextRequest.page, supersede });
|
||||
if (decision === "keep-and-park") {
|
||||
pendingCatchUps.set(agentId, nextRequest);
|
||||
return;
|
||||
@@ -836,18 +855,31 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
|
||||
if (decision === "keep") {
|
||||
return;
|
||||
}
|
||||
if (hiddenCatchUpSlotsAreFull(agentId)) {
|
||||
if (request) pendingCatchUps.set(agentId, request);
|
||||
return;
|
||||
}
|
||||
const generation = (catchUpGenerations.get(agentId) ?? 0) + 1;
|
||||
catchUpGenerations.set(agentId, generation);
|
||||
catchUps.set(agentId, { generation, status: "running", request: nextRequest });
|
||||
pendingCatchUps.delete(agentId);
|
||||
// A gap recovery pages forward to keep the coverage it extends. Without coverage there is
|
||||
// nothing to keep, so an overflowing page falls back to the latest tail, as a resume does.
|
||||
const attempt = { agentId };
|
||||
inFlightCatchUps.add(attempt);
|
||||
if (current?.status === "error" && !manualRetries.has(agentId)) {
|
||||
visibilityCatchUpErrors.delete(agentId);
|
||||
markCatchUpOwed(agentId);
|
||||
notifyListeners();
|
||||
}
|
||||
// A queued gap uses the coverage available when its fetch starts.
|
||||
void fetchUntilCurrent(
|
||||
agentId,
|
||||
generation,
|
||||
nextRequest,
|
||||
nextRequest.direction === "after" && (request === undefined || applied === undefined),
|
||||
);
|
||||
nextRequest.kind === "resume" || !applied,
|
||||
).finally(() => {
|
||||
inFlightCatchUps.delete(attempt);
|
||||
startAcknowledgedCatchUps();
|
||||
});
|
||||
};
|
||||
|
||||
const startAcknowledgedCatchUps = () => {
|
||||
@@ -859,9 +891,8 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
|
||||
for (const agentId of ordered) {
|
||||
const pendingCatchUp = pendingCatchUps.get(agentId);
|
||||
const current = catchUps.get(agentId);
|
||||
// Completion of a different chat must not bypass a failed chat's error or
|
||||
// supersede an in-flight tail that owns its parked gap recovery.
|
||||
if (current && !(current.status === "complete" && pendingCatchUp)) continue;
|
||||
// A running tail owns its parked gap. A failed catch-up can only have a queued retry.
|
||||
if (current?.status === "running" || (current && !pendingCatchUp)) continue;
|
||||
startCatchUp(agentId, {
|
||||
request: pendingCatchUp,
|
||||
supersede: Boolean(pendingCatchUp),
|
||||
@@ -869,6 +900,13 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
|
||||
}
|
||||
};
|
||||
|
||||
const retryFailedCatchUp = (agentId: string) => {
|
||||
const catchUp = catchUps.get(agentId);
|
||||
if (catchUp?.status === "error") {
|
||||
startCatchUp(agentId, { request: catchUp.request, supersede: true });
|
||||
}
|
||||
};
|
||||
|
||||
const membershipIsSettled = (requested: string[]) =>
|
||||
!membershipNeedsRetry &&
|
||||
!freshnessCheckOwed &&
|
||||
@@ -975,9 +1013,7 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
|
||||
void reconcileMembership();
|
||||
return;
|
||||
}
|
||||
if (catchUp?.status === "error") {
|
||||
startCatchUp(agentId, { request: catchUp.request, supersede: true });
|
||||
}
|
||||
retryFailedCatchUp(agentId);
|
||||
};
|
||||
|
||||
const commitDesiredMembership = (
|
||||
@@ -1068,11 +1104,17 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
|
||||
publishVisibleMembership();
|
||||
},
|
||||
replaceVisibleAgentIds(sourceId, agentIds) {
|
||||
const previouslyVisible = new Set(visibleAgentIds());
|
||||
const normalized = normalizeAgentIds(agentIds);
|
||||
if (normalized.length === 0) sources.delete(sourceId);
|
||||
else sources.set(sourceId, normalized);
|
||||
rememberOpenedAgentIds(normalized);
|
||||
publishVisibleMembership();
|
||||
if (active) {
|
||||
for (const agentId of normalized) {
|
||||
if (!previouslyVisible.has(agentId)) retryFailedCatchUp(agentId);
|
||||
}
|
||||
}
|
||||
startAcknowledgedCatchUps();
|
||||
},
|
||||
setActive(nextActive) {
|
||||
@@ -1085,7 +1127,10 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
|
||||
}
|
||||
const canCheck = connected && ports.canCheckFreshness();
|
||||
for (const agentId of visibleAgentIds()) {
|
||||
if (visibilityCatchUpErrors.has(agentId)) continue;
|
||||
if (visibilityCatchUpErrors.has(agentId)) {
|
||||
retryFailedCatchUp(agentId);
|
||||
continue;
|
||||
}
|
||||
markCatchUpOwed(agentId);
|
||||
if (
|
||||
canCheck &&
|
||||
@@ -1132,7 +1177,10 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
|
||||
recoverGap(agentId, cursor) {
|
||||
if (!isDesired(agentId) || catchUps.get(agentId)?.status === "error") return;
|
||||
startCatchUp(agentId, {
|
||||
request: planTimelineCatchUpAfter({ epoch: cursor.epoch, seq: cursor.endSeq }),
|
||||
request: {
|
||||
page: planTimelineCatchUpAfter({ epoch: cursor.epoch, seq: cursor.endSeq }),
|
||||
kind: "gap",
|
||||
},
|
||||
supersede: true,
|
||||
});
|
||||
},
|
||||
|
||||
@@ -32,6 +32,7 @@ it("translates mounted usage rows when the language changes", async () => {
|
||||
<>
|
||||
<UsageWindowBar
|
||||
window={window}
|
||||
forecastAt={null}
|
||||
displayAs="used"
|
||||
pinnable={false}
|
||||
pinned={false}
|
||||
@@ -51,3 +52,44 @@ it("translates mounted usage rows when the language changes", async () => {
|
||||
expect(container.textContent).toContain("セッション70% 使用済み");
|
||||
expect(container.textContent).toContain("クレジット");
|
||||
});
|
||||
|
||||
const narrowReadingMs = Date.now();
|
||||
const narrowForecastAt = new Date(narrowReadingMs).toISOString();
|
||||
const narrowWindow: UsageWindow = {
|
||||
id: "weekly",
|
||||
label: "Weekly",
|
||||
usedPct: 0.2,
|
||||
durationSeconds: 604_800,
|
||||
resetsAt: new Date(narrowReadingMs + 165.5 * 3_600_000).toISOString(),
|
||||
};
|
||||
|
||||
it("keeps the French reset countdown and forecast apart in a narrow card", async () => {
|
||||
await i18n.changeLanguage("fr");
|
||||
container.style.width = "272px";
|
||||
act(() =>
|
||||
root.render(
|
||||
<UsageWindowBar
|
||||
window={narrowWindow}
|
||||
forecastAt={narrowForecastAt}
|
||||
displayAs="used"
|
||||
pinnable={false}
|
||||
pinned={false}
|
||||
onTogglePin={ignorePin}
|
||||
pinLabel=""
|
||||
pinTestID=""
|
||||
/>,
|
||||
),
|
||||
);
|
||||
|
||||
function textBounds(prefix: string) {
|
||||
const element = Array.from(container.querySelectorAll("*")).find(
|
||||
(node) => node.childElementCount === 0 && node.textContent.startsWith(prefix),
|
||||
);
|
||||
expect(element).toBeDefined();
|
||||
const range = document.createRange();
|
||||
range.selectNodeContents(element!);
|
||||
return range.getBoundingClientRect();
|
||||
}
|
||||
|
||||
expect(textBounds("se réinitialise").right).toBeLessThan(textBounds("~").left);
|
||||
});
|
||||
|
||||
@@ -70,7 +70,7 @@ export function UsageCard({
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const isCompact = useIsCompactFormFactor();
|
||||
const { refresh, refreshState } = useReportRefresh(serverId, entry.id, agentId);
|
||||
const { refresh, refreshState } = useReportRefresh(serverId, entry, agentId);
|
||||
// Where there is no hover the freshness is printed on the card; elsewhere the Refresh tooltip.
|
||||
const showsFreshnessInline = isNative || isCompact || !refreshable;
|
||||
const usage = entry.report;
|
||||
@@ -176,7 +176,7 @@ function UsageCardBody({
|
||||
refreshState: UsageRefresh;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const { windows, balances, details, retained, successfulAt, messages } = report;
|
||||
const { windows, balances, details, retained, successfulAt, forecastAt, messages } = report;
|
||||
const footer = entry.account.label ?? null;
|
||||
return (
|
||||
<>
|
||||
@@ -194,6 +194,7 @@ function UsageCardBody({
|
||||
entry={entry}
|
||||
window={window}
|
||||
retained={retained}
|
||||
forecastAt={forecastAt}
|
||||
display={display}
|
||||
pinnable={pinnable}
|
||||
/>
|
||||
@@ -267,8 +268,10 @@ function CardWindowBar({
|
||||
display,
|
||||
pinnable,
|
||||
retained,
|
||||
forecastAt,
|
||||
}: {
|
||||
retained: boolean;
|
||||
forecastAt: string | null;
|
||||
entry: UsageReportEntry;
|
||||
window: UsageWindow;
|
||||
display: UsageDisplay;
|
||||
@@ -285,6 +288,7 @@ function CardWindowBar({
|
||||
<UsageWindowBar
|
||||
window={window}
|
||||
retained={retained}
|
||||
forecastAt={forecastAt}
|
||||
displayAs={display.displayAs}
|
||||
pinnable={pinnable}
|
||||
pinned={display.isPinned(pin)}
|
||||
|
||||
@@ -2,6 +2,7 @@ import { afterEach, describe, expect, it } from "vitest";
|
||||
import { i18n } from "@/i18n/i18next";
|
||||
import {
|
||||
resolveUsageReport,
|
||||
markUsageRefreshFailure,
|
||||
displayPercent,
|
||||
resolveAgentUsageView,
|
||||
replaceReport,
|
||||
@@ -82,7 +83,7 @@ describe("resolveUsageView", () => {
|
||||
expect(resolveUsageView({ ...base, query: undefined })).toEqual({ kind: "loading" });
|
||||
expect(
|
||||
resolveUsageView({ ...base, query: { data: [], error: null, isFetching: true } }),
|
||||
).toEqual({ kind: "ready", reports: [], isRefreshing: true });
|
||||
).toEqual({ kind: "ready", reports: [], isRefreshing: true, refreshFailed: false });
|
||||
expect(
|
||||
resolveUsageView({
|
||||
...base,
|
||||
@@ -90,6 +91,19 @@ describe("resolveUsageView", () => {
|
||||
}),
|
||||
).toEqual({ kind: "error", message: "boom" });
|
||||
});
|
||||
|
||||
it("shows a failed Refresh all alongside the reports still on screen", () => {
|
||||
const reports = [entry({})];
|
||||
expect(
|
||||
resolveUsageView({
|
||||
hostLabel: "Laptop",
|
||||
isConnected: true,
|
||||
supportsUsage: true,
|
||||
query: ready(reports),
|
||||
refreshState: "failed",
|
||||
}),
|
||||
).toEqual({ kind: "ready", reports, isRefreshing: false, refreshFailed: true });
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
@@ -203,15 +217,12 @@ describe("displayPercent", () => {
|
||||
|
||||
describe("resolveUsageRefresh", () => {
|
||||
it("is pending while a refresh runs, even after an earlier failure", () => {
|
||||
expect(resolveUsageRefresh({ isPending: true, error: new Error("boom") })).toBe("pending");
|
||||
expect(resolveUsageRefresh({ isPending: true, isError: true })).toBe("pending");
|
||||
});
|
||||
|
||||
it("is failed after a refresh errors", () => {
|
||||
expect(resolveUsageRefresh({ isPending: false, error: new Error("boom") })).toBe("failed");
|
||||
});
|
||||
|
||||
it("is idle before and after a successful refresh", () => {
|
||||
expect(resolveUsageRefresh({ isPending: false, error: null })).toBe("idle");
|
||||
it("reports the request outcome independently of the reading", () => {
|
||||
expect(resolveUsageRefresh({ isPending: false, isError: true })).toBe("failed");
|
||||
expect(resolveUsageRefresh({ isPending: false, isError: false })).toBe("idle");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -352,6 +363,7 @@ it("resolves retained usage and successful time without inventing old-daemon his
|
||||
details: [],
|
||||
planLabel: null,
|
||||
successfulAt: success.fetchedAt,
|
||||
forecastAt: null,
|
||||
retained: true,
|
||||
messages: ["Rate limited"],
|
||||
});
|
||||
@@ -361,6 +373,7 @@ it("resolves retained usage and successful time without inventing old-daemon his
|
||||
details: [],
|
||||
planLabel: null,
|
||||
successfulAt: null,
|
||||
forecastAt: null,
|
||||
retained: false,
|
||||
messages: ["Rate limited"],
|
||||
});
|
||||
@@ -370,11 +383,48 @@ it("resolves retained usage and successful time without inventing old-daemon his
|
||||
details: [],
|
||||
planLabel: null,
|
||||
successfulAt: success.fetchedAt,
|
||||
forecastAt: success.fetchedAt,
|
||||
retained: false,
|
||||
messages: [],
|
||||
});
|
||||
});
|
||||
|
||||
it("uses the quota observation time for pace and keeps the reading after a failed request", () => {
|
||||
const success = entry({ windows: [{ id: "weekly", label: "Weekly", usedPct: 42 }] });
|
||||
if (success.report.status !== "available") throw new Error("fixture must be available");
|
||||
const observedAt = success.fetchedAt;
|
||||
const successfulAt = "2026-01-01T00:15:00.000Z";
|
||||
const report = { ...success, successfulAt, report: { ...success.report, observedAt } };
|
||||
expect(resolveUsageReport(report, i18n.t)).toMatchObject({
|
||||
successfulAt,
|
||||
forecastAt: observedAt,
|
||||
});
|
||||
expect(resolveUsageReport({ ...report, forecastStale: true }, i18n.t)).toMatchObject({
|
||||
windows: success.report.windows,
|
||||
successfulAt,
|
||||
forecastAt: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps cached quota and hides its forecast when Refresh all fails before a new report arrives", () => {
|
||||
const before = entry({ windows: [{ id: "weekly", label: "Weekly", usedPct: 42 }] });
|
||||
const other = entry({ sourceId: "other" });
|
||||
const refreshedAt = "2026-01-01T00:06:00.000Z";
|
||||
const streamed = { ...other, fetchedAt: refreshedAt };
|
||||
const attempted = [before, other];
|
||||
const failed = markUsageRefreshFailure([before, streamed], attempted)!;
|
||||
|
||||
expect(resolveUsageReport(failed[0]!, i18n.t)).toMatchObject({
|
||||
forecastAt: null,
|
||||
windows: before.report.status === "available" ? before.report.windows : [],
|
||||
});
|
||||
expect(resolveUsageReport(failed[1]!, i18n.t).forecastAt).toBe(refreshedAt);
|
||||
expect(resolveUsageReport(upsertReport(failed, before)[0]!, i18n.t).forecastAt).toBeNull();
|
||||
|
||||
const retried = settleReports(failed, [{ ...before, fetchedAt: refreshedAt }, streamed]);
|
||||
expect(resolveUsageReport(retried[0]!, i18n.t).forecastAt).toBe(refreshedAt);
|
||||
});
|
||||
|
||||
it("orders failed polls by attempt time even when successful data is older", () => {
|
||||
const success = entry({});
|
||||
if (success.report.status !== "available") throw new Error("fixture must be available");
|
||||
|
||||
@@ -38,18 +38,31 @@ export function usageWindowRowLabel(input: {
|
||||
return `${input.pinLabel}, ${summary}`;
|
||||
}
|
||||
|
||||
/** A user-requested refresh of one report. The previous report stays on screen throughout. */
|
||||
/** The outcome of a user-requested usage refresh. */
|
||||
export type UsageRefresh = "idle" | "pending" | "failed";
|
||||
|
||||
export function resolveUsageRefresh(mutation: {
|
||||
isPending: boolean;
|
||||
error: unknown;
|
||||
isError: boolean;
|
||||
}): UsageRefresh {
|
||||
if (mutation.isPending) return "pending";
|
||||
if (mutation.error) return "failed";
|
||||
if (mutation.isError) return "failed";
|
||||
return "idle";
|
||||
}
|
||||
|
||||
/** Keep quota readings after a failed refresh and attach the outcome to the readings it targeted. */
|
||||
export function markUsageRefreshFailure(
|
||||
current: UsageReportEntry[] | undefined,
|
||||
attempted: readonly UsageReportEntry[],
|
||||
): UsageReportEntry[] | undefined {
|
||||
const attemptedAt = new Map(attempted.map((entry) => [entry.id, entry.fetchedAt]));
|
||||
return current?.map((entry) =>
|
||||
attemptedAt.get(entry.id) === entry.fetchedAt && !entry.forecastStale
|
||||
? { ...entry, forecastStale: true }
|
||||
: entry,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* A host's report list with one report swapped for its refreshed copy, in place.
|
||||
* `null` means the daemon no longer knows the ID, so the report leaves the list.
|
||||
@@ -60,7 +73,9 @@ export function replaceReport(
|
||||
refreshed: UsageReportEntry | null,
|
||||
): UsageReportEntry[] {
|
||||
if (!refreshed) return reports.filter((report) => report.id !== reportId);
|
||||
return reports.map((report) => (report.id === reportId ? refreshed : report));
|
||||
return reports.map((report) =>
|
||||
report.id === reportId ? laterFetched(report, refreshed) : report,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -68,7 +83,9 @@ export function replaceReport(
|
||||
* started, so a Refresh that lands while it streams is newer than what the request still delivers.
|
||||
*/
|
||||
function laterFetched(shown: UsageReportEntry, arriving: UsageReportEntry): UsageReportEntry {
|
||||
return Date.parse(shown.fetchedAt) > Date.parse(arriving.fetchedAt) ? shown : arriving;
|
||||
const shownAt = Date.parse(shown.fetchedAt);
|
||||
const arrivingAt = Date.parse(arriving.fetchedAt);
|
||||
return shownAt > arrivingAt || (shownAt === arrivingAt && shown.forecastStale) ? shown : arriving;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -117,10 +134,11 @@ export function resolveUsageView(
|
||||
isConnected: boolean;
|
||||
supportsUsage: boolean;
|
||||
query: UsageQueryState | undefined;
|
||||
refreshState?: UsageRefresh;
|
||||
},
|
||||
t: TFunction = i18n.t,
|
||||
): UsageView {
|
||||
const { hostLabel, isConnected, supportsUsage, query } = input;
|
||||
const { hostLabel, isConnected, supportsUsage, query, refreshState } = input;
|
||||
if (!isConnected)
|
||||
return {
|
||||
kind: "unavailable",
|
||||
@@ -135,7 +153,12 @@ export function resolveUsageView(
|
||||
if (input.enabled === false)
|
||||
return { kind: "off", message: t("providerUsage.off", { host: hostLabel }) };
|
||||
if (query?.data) {
|
||||
return { kind: "ready", reports: query.data, isRefreshing: query.isFetching };
|
||||
return {
|
||||
kind: "ready",
|
||||
reports: query.data,
|
||||
isRefreshing: query.isFetching || refreshState === "pending",
|
||||
refreshFailed: refreshState === "failed",
|
||||
};
|
||||
}
|
||||
if (query?.error) {
|
||||
return {
|
||||
@@ -250,7 +273,12 @@ export function resolveUsageReport(entry: UsageReportEntry, t: TFunction) {
|
||||
// COMPAT(usageLoginErrors): added in v0.11.0, remove after 2027-04-05 once daemon floor >= v0.11.0.
|
||||
else messages.push(usageProblemText(entry.report, t));
|
||||
}
|
||||
const forecastAt =
|
||||
snapshot && !snapshot.retained && !entry.forecastStale
|
||||
? (snapshot.report.observedAt ?? snapshot.successfulAt)
|
||||
: null;
|
||||
return {
|
||||
forecastAt,
|
||||
windows: snapshot?.report.windows ?? [],
|
||||
balances: snapshot?.report.balances ?? [],
|
||||
details: snapshot?.report.details ?? [],
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { usagePace } from "./pace";
|
||||
import type { UsageWindow } from "./types";
|
||||
|
||||
const day = "2026-11-20T";
|
||||
const reading = (time: string) => `${day}${time}:00.000Z`;
|
||||
const window: UsageWindow = {
|
||||
id: "five_hour",
|
||||
label: "Session",
|
||||
durationSeconds: 18_000,
|
||||
usedPct: 65,
|
||||
resetsAt: reading("15:00"),
|
||||
};
|
||||
|
||||
describe("usage pace", () => {
|
||||
it("projects the limit from the sample time and keeps it fixed between readings", () => {
|
||||
const sampledAt = reading("12:00");
|
||||
const estimate = { kind: "runsOut", at: `${day}13:04:36.923Z` };
|
||||
expect(usagePace(window, sampledAt, Date.parse(sampledAt))).toEqual(estimate);
|
||||
expect(usagePace(window, sampledAt, Date.parse(reading("12:30")))).toEqual(estimate);
|
||||
});
|
||||
|
||||
it("updates after a later reading and works with a remaining percentage", () => {
|
||||
const close = reading("13:30");
|
||||
const safe = reading("14:00");
|
||||
const forecast = usagePace(window, close, Date.parse(close));
|
||||
expect(forecast.kind).toBe("remaining");
|
||||
if (forecast.kind === "remaining") expect(forecast.remainingAtResetPct).toBeCloseTo(7.14);
|
||||
expect(
|
||||
usagePace({ ...window, usedPct: undefined, remainingPct: 35 }, safe, Date.parse(safe)),
|
||||
).toEqual({ kind: "remaining", remainingAtResetPct: 18.75 });
|
||||
});
|
||||
|
||||
it("only forecasts with timing and an active, usable reading", () => {
|
||||
const sampledAt = reading("12:00");
|
||||
const now = Date.parse(sampledAt);
|
||||
expect(usagePace({ ...window, durationSeconds: undefined }, sampledAt, now)).toEqual({
|
||||
kind: "unknown",
|
||||
});
|
||||
expect(usagePace(window, null, now)).toEqual({ kind: "unknown" });
|
||||
expect(usagePace(window, reading("10:01"), now)).toEqual({ kind: "unknown" });
|
||||
expect(usagePace(window, sampledAt, Date.parse(window.resetsAt!))).toEqual({ kind: "unknown" });
|
||||
expect(usagePace({ ...window, usedPct: 100 }, sampledAt, now)).toEqual({ kind: "reached" });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,45 @@
|
||||
import { usedPercent } from "./model";
|
||||
import type { UsageWindow } from "./types";
|
||||
|
||||
type UsagePace =
|
||||
| { kind: "unknown" }
|
||||
| { kind: "reached" }
|
||||
| { kind: "runsOut"; at: string }
|
||||
| { kind: "remaining"; remainingAtResetPct: number };
|
||||
|
||||
/** Estimate from the window's average pace as of the reading. The clock only expires the estimate. */
|
||||
export function usagePace(window: UsageWindow, observedAt: string | null, now: number): UsagePace {
|
||||
if (observedAt === null) return { kind: "unknown" };
|
||||
const reset = Date.parse(window.resetsAt ?? "");
|
||||
if (reset <= now) return { kind: "unknown" };
|
||||
|
||||
const used = usedPercent(window);
|
||||
if (used != null && used >= 100) return { kind: "reached" };
|
||||
|
||||
const supplied = window.runsOutAt;
|
||||
const suppliedAt = Date.parse(supplied ?? "");
|
||||
if (supplied && Number.isFinite(suppliedAt) && (!Number.isFinite(reset) || suppliedAt < reset)) {
|
||||
return { kind: "runsOut", at: supplied };
|
||||
}
|
||||
|
||||
const duration = (window.durationSeconds ?? 0) * 1_000;
|
||||
const sampled = Date.parse(observedAt);
|
||||
const elapsed = sampled - (reset - duration);
|
||||
if (
|
||||
used == null ||
|
||||
!Number.isFinite(used) ||
|
||||
used < 0 ||
|
||||
!Number.isFinite(elapsed) ||
|
||||
sampled >= reset ||
|
||||
elapsed < Math.max(60_000, duration * 0.01)
|
||||
) {
|
||||
return { kind: "unknown" };
|
||||
}
|
||||
|
||||
const projectedAtReset = (used / elapsed) * duration;
|
||||
if (projectedAtReset > 100) {
|
||||
const runsOut = sampled + ((100 - used) / used) * elapsed;
|
||||
return { kind: "runsOut", at: new Date(runsOut).toISOString() };
|
||||
}
|
||||
return { kind: "remaining", remainingAtResetPct: 100 - projectedAtReset };
|
||||
}
|
||||
@@ -20,6 +20,7 @@ import { useSessionStore, type SessionState } from "@/stores/session-store";
|
||||
import { useUsageSetting } from "./setting";
|
||||
import { usageCopy } from "./copy";
|
||||
import {
|
||||
markUsageRefreshFailure,
|
||||
replaceReport,
|
||||
resolveAgentUsageView,
|
||||
resolveUsageRefresh,
|
||||
@@ -97,17 +98,32 @@ async function streamReports(input: {
|
||||
return settleReports(queryClient.getQueryData<UsageReportEntry[]>(queryKey), reports);
|
||||
}
|
||||
|
||||
function listReports(
|
||||
async function listReports(
|
||||
queryClient: QueryClient,
|
||||
serverId: string,
|
||||
forceRefresh = false,
|
||||
): Promise<UsageReportEntry[]> {
|
||||
return streamReports({
|
||||
queryClient,
|
||||
queryKey: usageReportsQueryKey(serverId),
|
||||
serverId,
|
||||
forceRefresh,
|
||||
});
|
||||
const queryKey = usageReportsQueryKey(serverId);
|
||||
const attempted = queryClient.getQueryData<UsageReportEntry[]>(queryKey) ?? [];
|
||||
try {
|
||||
return await streamReports({ queryClient, queryKey, serverId, forceRefresh });
|
||||
} catch (error) {
|
||||
recordUsageRefreshFailure(queryClient, queryKey, attempted);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
function recordUsageRefreshFailure(
|
||||
queryClient: QueryClient,
|
||||
queryKey: QueryKey,
|
||||
attempted: readonly UsageReportEntry[],
|
||||
): void {
|
||||
const { dataUpdatedAt } = queryClient.getQueryState(queryKey) ?? {};
|
||||
queryClient.setQueryData<UsageReportEntry[]>(
|
||||
queryKey,
|
||||
(current) => markUsageRefreshFailure(current, attempted),
|
||||
{ updatedAt: dataUpdatedAt },
|
||||
);
|
||||
}
|
||||
|
||||
async function getReport(
|
||||
@@ -158,9 +174,12 @@ export function useHostUsage(serverId: string): { view: UsageView; refresh: () =
|
||||
dataShape: "value",
|
||||
staleTimeMs: REPORTS_STALE_TIME_MS,
|
||||
});
|
||||
const refresh = useCallback(() => {
|
||||
void refreshReports(queryClient, serverId).catch(() => undefined);
|
||||
}, [queryClient, serverId]);
|
||||
const mutation = useMutation({
|
||||
mutationKey: [...usageReportsQueryKey(serverId), "refresh"],
|
||||
mutationFn: (hostId: string) => refreshReports(queryClient, hostId),
|
||||
});
|
||||
const { mutate, variables } = mutation;
|
||||
const refresh = useCallback(() => mutate(serverId), [mutate, serverId]);
|
||||
const { t } = useTranslation();
|
||||
const hostLabel = useHosts().find((host) => host.serverId === serverId)?.label ?? serverId;
|
||||
const view = resolveUsageView(
|
||||
@@ -170,6 +189,7 @@ export function useHostUsage(serverId: string): { view: UsageView; refresh: () =
|
||||
isConnected,
|
||||
supportsUsage: isSupported,
|
||||
query: toQueryState(query),
|
||||
refreshState: variables === serverId ? resolveUsageRefresh(mutation) : "idle",
|
||||
},
|
||||
t,
|
||||
);
|
||||
@@ -265,23 +285,26 @@ export function useUsageHosts(): UsageHost[] {
|
||||
*/
|
||||
export function useReportRefresh(
|
||||
serverId: string,
|
||||
reportId: string,
|
||||
entry: UsageReportEntry,
|
||||
agentId?: string,
|
||||
): { refresh: () => void; refreshState: UsageRefresh } {
|
||||
const queryClient = useQueryClient();
|
||||
const usageScopeKey = useAgentUsageScopeKey(serverId, agentId);
|
||||
const queryKey =
|
||||
agentId === undefined
|
||||
? usageReportsQueryKey(serverId)
|
||||
: agentUsageQueryKey(serverId, agentId, usageScopeKey);
|
||||
const mutation = useMutation({
|
||||
mutationFn: () => getReport(serverId, reportId, true, agentId),
|
||||
onSuccess: (report) => {
|
||||
queryClient.setQueryData<UsageReportEntry[]>(
|
||||
agentId === undefined
|
||||
? usageReportsQueryKey(serverId)
|
||||
: agentUsageQueryKey(serverId, agentId, usageScopeKey),
|
||||
(reports) => (reports ? replaceReport(reports, reportId, report) : reports),
|
||||
mutationKey: [...queryKey, "refresh", entry.id],
|
||||
mutationFn: (attempted: UsageReportEntry) => getReport(serverId, attempted.id, true, agentId),
|
||||
onSuccess: (report, attempted) => {
|
||||
queryClient.setQueryData<UsageReportEntry[]>(queryKey, (reports) =>
|
||||
reports ? replaceReport(reports, attempted.id, report) : reports,
|
||||
);
|
||||
},
|
||||
onError: (_error, attempted) => recordUsageRefreshFailure(queryClient, queryKey, [attempted]),
|
||||
});
|
||||
const { mutate } = mutation;
|
||||
const refresh = useCallback(() => mutate(), [mutate]);
|
||||
const refresh = useCallback(() => mutate(entry), [mutate, entry]);
|
||||
return { refresh, refreshState: resolveUsageRefresh(mutation) };
|
||||
}
|
||||
|
||||
@@ -3,24 +3,21 @@ import { StyleSheet } from "react-native-unistyles";
|
||||
|
||||
/**
|
||||
* The reset data of a window or balance: the countdown first, then the exact time. When the line
|
||||
* is too narrow the exact time gives way (truncates) and the countdown stays whole.
|
||||
* is too narrow the exact time truncates and the countdown wraps within its column.
|
||||
*/
|
||||
export function UsageResetLine({
|
||||
countdown,
|
||||
exactTime,
|
||||
atRisk = false,
|
||||
testID,
|
||||
}: {
|
||||
countdown: string | null;
|
||||
exactTime: string | null;
|
||||
/** The countdown is a runs-out warning rather than a reset. */
|
||||
atRisk?: boolean;
|
||||
testID?: string;
|
||||
}) {
|
||||
if (!countdown) return null;
|
||||
return (
|
||||
<View style={styles.line} testID={testID}>
|
||||
<Text style={atRisk ? styles.atRisk : styles.text}>{countdown}</Text>
|
||||
<Text style={[styles.text, styles.countdown]}>{countdown}</Text>
|
||||
{exactTime ? (
|
||||
<Text style={[styles.text, styles.exactTime]} numberOfLines={1} ellipsizeMode="tail">
|
||||
{`\u00a0·\u00a0${exactTime}`}
|
||||
@@ -31,18 +28,13 @@ export function UsageResetLine({
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
line: { flexDirection: "row", alignItems: "center" },
|
||||
line: { flexDirection: "row", alignItems: "baseline" },
|
||||
text: {
|
||||
flexShrink: 0,
|
||||
color: theme.colors.foregroundMuted,
|
||||
fontSize: theme.fontSize.sm,
|
||||
fontWeight: theme.fontWeight.normal,
|
||||
},
|
||||
atRisk: {
|
||||
flexShrink: 0,
|
||||
color: theme.colors.statusDanger,
|
||||
fontSize: theme.fontSize.sm,
|
||||
fontWeight: theme.fontWeight.normal,
|
||||
},
|
||||
exactTime: { flexShrink: 1 },
|
||||
countdown: { maxWidth: "100%" },
|
||||
exactTime: { flexShrink: 1, minWidth: 0 },
|
||||
}));
|
||||
|
||||
@@ -1,6 +1,12 @@
|
||||
import type { ProviderUsageTone, UsageReportEntry } from "@getpaseo/protocol/messages";
|
||||
import type {
|
||||
ProviderUsageTone,
|
||||
UsageReportEntry as WireUsageReportEntry,
|
||||
} from "@getpaseo/protocol/messages";
|
||||
|
||||
export type { UsageReportEntry };
|
||||
export interface UsageReportEntry extends WireUsageReportEntry {
|
||||
/** A refresh failed while this reading was cached. */
|
||||
forecastStale?: true;
|
||||
}
|
||||
export type UsageReport = UsageReportEntry["report"];
|
||||
export type UsageTone = ProviderUsageTone;
|
||||
export type AvailableUsageReport = Extract<UsageReport, { status: "available" }>;
|
||||
@@ -14,4 +20,4 @@ export type UsageView =
|
||||
| { kind: "unavailable"; message: string }
|
||||
| { kind: "loading" }
|
||||
| { kind: "error"; message: string }
|
||||
| { kind: "ready"; reports: UsageReportEntry[]; isRefreshing: boolean };
|
||||
| { kind: "ready"; reports: UsageReportEntry[]; isRefreshing: boolean; refreshFailed: boolean };
|
||||
|
||||
@@ -84,11 +84,18 @@ export function UsageBody({
|
||||
);
|
||||
}
|
||||
|
||||
if (view.reports.length === 0) {
|
||||
return <UsageMessage text={t("providerUsage.empty")} />;
|
||||
}
|
||||
|
||||
return <UsageList serverId={serverId} reports={view.reports} display={display} />;
|
||||
return (
|
||||
<View style={styles.reports}>
|
||||
{view.refreshFailed ? (
|
||||
<Alert size="sm" variant="error" title={t("providerUsage.refreshFailed")} />
|
||||
) : null}
|
||||
{view.reports.length === 0 ? (
|
||||
<UsageMessage text={t("providerUsage.empty")} />
|
||||
) : (
|
||||
<UsageList serverId={serverId} reports={view.reports} display={display} />
|
||||
)}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
export function UsageMessage({ text }: { text: string }) {
|
||||
@@ -100,6 +107,7 @@ export function UsageMessage({ text }: { text: string }) {
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
reports: { gap: theme.spacing[3] },
|
||||
emptyCard: {
|
||||
padding: theme.spacing[4],
|
||||
alignItems: "center",
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import type { TFunction } from "i18next";
|
||||
import { Pin } from "lucide-react-native";
|
||||
import { useMemo } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
@@ -6,6 +7,7 @@ import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
|
||||
import {
|
||||
formatDisplayPct,
|
||||
formatPct,
|
||||
formatProviderUsageLabel,
|
||||
formatResetLabel,
|
||||
formatResetTime,
|
||||
@@ -13,9 +15,9 @@ import {
|
||||
} from "./format";
|
||||
import { UsageMeter } from "./meter";
|
||||
import { displayPercent, usageWindowRowLabel } from "./model";
|
||||
import { usagePace } from "./pace";
|
||||
import { UsageResetLine } from "./reset-line";
|
||||
import type { UsageDisplayAs } from "./preferences";
|
||||
import { windowTone } from "./tone";
|
||||
import type { UsageTone, UsageWindow } from "./types";
|
||||
import { useRelativeTimeTick } from "./use-relative-time-tick";
|
||||
|
||||
@@ -28,8 +30,10 @@ export function UsageWindowBar({
|
||||
pinLabel,
|
||||
pinTestID,
|
||||
retained = false,
|
||||
forecastAt,
|
||||
}: {
|
||||
retained?: boolean;
|
||||
forecastAt: string | null;
|
||||
window: UsageWindow;
|
||||
displayAs: UsageDisplayAs;
|
||||
/** Whether the row pins the window to the sidebar. When false the row is a plain bar. */
|
||||
@@ -42,19 +46,11 @@ export function UsageWindowBar({
|
||||
}) {
|
||||
const { t, i18n } = useTranslation();
|
||||
const shownPct = displayPercent(window, displayAs);
|
||||
const tone = windowTone(window);
|
||||
|
||||
const now = useRelativeTimeTick({ enabled: window.runsOutAt != null || window.resetsAt != null });
|
||||
const isAtRisk =
|
||||
window.runsOutAt != null &&
|
||||
window.shortfallPct != null &&
|
||||
(!retained || Date.parse(window.runsOutAt) > now);
|
||||
const countdown = isAtRisk
|
||||
? formatRunsOutLabel(window.runsOutAt, now, t)
|
||||
: formatResetLabel(window.resetsAt, retained, now, t);
|
||||
// The exact time belongs to the reset; beside a runs-out warning it would read as the moment
|
||||
// the quota runs out.
|
||||
const exactTime = isAtRisk ? null : formatResetTime(window.resetsAt, now, t);
|
||||
const pace = usagePace(window, forecastAt, now);
|
||||
const forecast = formatPace(pace, now, t);
|
||||
const countdown = formatResetLabel(window.resetsAt, retained, now, t);
|
||||
const exactTime = formatResetTime(window.resetsAt, now, t);
|
||||
|
||||
const value =
|
||||
shownPct != null ? formatDisplayPct(shownPct, displayAs, i18n.resolvedLanguage, t) : "—";
|
||||
@@ -64,9 +60,8 @@ export function UsageWindowBar({
|
||||
value,
|
||||
countdown,
|
||||
exactTime,
|
||||
isAtRisk,
|
||||
forecast,
|
||||
percent: shownPct ?? 0,
|
||||
tone,
|
||||
pinned,
|
||||
};
|
||||
|
||||
@@ -86,7 +81,7 @@ export function UsageWindowBar({
|
||||
accessibilityLabel={usageWindowRowLabel({
|
||||
pinLabel,
|
||||
value,
|
||||
trailing: [countdown, exactTime].filter(Boolean).join(" · "),
|
||||
trailing: [countdown, exactTime, forecast?.label].filter(Boolean).join(" · "),
|
||||
})}
|
||||
accessibilityState={accessibilityState}
|
||||
aria-checked={pinned}
|
||||
@@ -103,9 +98,8 @@ function WindowRowContent({
|
||||
value,
|
||||
countdown,
|
||||
exactTime,
|
||||
isAtRisk,
|
||||
forecast,
|
||||
percent,
|
||||
tone,
|
||||
pinnable,
|
||||
pinned,
|
||||
}: {
|
||||
@@ -113,9 +107,8 @@ function WindowRowContent({
|
||||
value: string;
|
||||
countdown: string | null;
|
||||
exactTime: string | null;
|
||||
isAtRisk: boolean;
|
||||
forecast: PaceLabel | null;
|
||||
percent: number;
|
||||
tone: UsageTone;
|
||||
pinnable: boolean;
|
||||
pinned: boolean;
|
||||
}) {
|
||||
@@ -130,12 +123,51 @@ function WindowRowContent({
|
||||
</Text>
|
||||
{pinnable ? <UsagePinGlyph pinned={pinned} /> : null}
|
||||
</View>
|
||||
<UsageMeter percent={percent} tone={tone} />
|
||||
<UsageResetLine countdown={countdown} exactTime={exactTime} atRisk={isAtRisk} />
|
||||
<UsageMeter percent={percent} tone={forecast?.tone ?? "default"} />
|
||||
{countdown || forecast ? (
|
||||
<View style={styles.timingRow}>
|
||||
<View style={styles.resetTiming}>
|
||||
<UsageResetLine countdown={countdown} exactTime={exactTime} />
|
||||
</View>
|
||||
{forecast ? <Text style={styles.forecast(forecast.tone)}>{forecast.label}</Text> : null}
|
||||
</View>
|
||||
) : null}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
interface PaceLabel {
|
||||
label: string;
|
||||
tone: UsageTone;
|
||||
}
|
||||
|
||||
function formatPace(
|
||||
pace: ReturnType<typeof usagePace>,
|
||||
now: number,
|
||||
t: TFunction,
|
||||
): PaceLabel | null {
|
||||
switch (pace.kind) {
|
||||
case "reached":
|
||||
return { label: t("providerUsage.timing.limitReached"), tone: "danger" };
|
||||
case "runsOut": {
|
||||
const label =
|
||||
Date.parse(pace.at) <= now
|
||||
? t("providerUsage.timing.mayHaveRunOut")
|
||||
: formatRunsOutLabel(pace.at, now, t);
|
||||
return label ? { label, tone: "danger" } : null;
|
||||
}
|
||||
case "remaining":
|
||||
return {
|
||||
label: t("providerUsage.timing.projectedLeftAtReset", {
|
||||
percentage: formatPct(pace.remainingAtResetPct),
|
||||
}),
|
||||
tone: pace.remainingAtResetPct <= 10 ? "warning" : "default",
|
||||
};
|
||||
case "unknown":
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
const ThemedPin = withUnistyles(Pin);
|
||||
|
||||
function UsagePinGlyph({ pinned }: { pinned: boolean }) {
|
||||
@@ -167,6 +199,23 @@ function UsagePinGlyph({ pinned }: { pinned: boolean }) {
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
timingRow: {
|
||||
flexDirection: "row",
|
||||
alignItems: "flex-start",
|
||||
gap: theme.spacing[2],
|
||||
},
|
||||
resetTiming: { flex: 1, minWidth: 0 },
|
||||
forecast: (tone: UsageTone) => ({
|
||||
color: {
|
||||
danger: theme.colors.statusDanger,
|
||||
warning: theme.colors.statusWarning,
|
||||
default: theme.colors.foregroundMuted,
|
||||
ok: theme.colors.statusSuccess,
|
||||
}[tone],
|
||||
fontSize: theme.fontSize.sm,
|
||||
maxWidth: "50%",
|
||||
textAlign: "right",
|
||||
}),
|
||||
row: { gap: 3, paddingVertical: theme.spacing[1.5] },
|
||||
pin: { width: 12, alignItems: "center" },
|
||||
tooltipText: { color: theme.colors.popoverForeground, fontSize: theme.fontSize.sm },
|
||||
|
||||
@@ -14,6 +14,7 @@ import { buildWorkspaceTabPersistenceKey } from "@/workspace-tabs/model";
|
||||
import { archiveWorkspaceWithUndo, supportsWorkspaceArchiveUndo } from "@/workspace/archive-undo";
|
||||
import {
|
||||
archiveWorkspaceOptimistically,
|
||||
runWorkspaceArchiveAttempt,
|
||||
type WorkspaceArchiveTarget,
|
||||
} from "@/workspace/workspace-archive";
|
||||
|
||||
@@ -56,7 +57,6 @@ export function useWorkspaceArchive(input: ArchiveWorkspaceInput): WorkspaceArch
|
||||
} = input;
|
||||
const { t } = useTranslation();
|
||||
const toast = useToast();
|
||||
const confirmingRef = useRef(false);
|
||||
// The archive starts after the host answers and you confirm. By then you may have opened another
|
||||
// workspace, so the redirect reads the selection from the latest render.
|
||||
const onArchiveStartedRef = useRef(onArchiveStarted);
|
||||
@@ -119,26 +119,12 @@ export function useWorkspaceArchive(input: ArchiveWorkspaceInput): WorkspaceArch
|
||||
}, [diffStat, name, serverId, t, toast, warningLabels, workspaceDirectory]);
|
||||
|
||||
const archive = useCallback(() => {
|
||||
// A second press while the host answers or the warning is open would ask twice.
|
||||
if (confirmingRef.current) {
|
||||
return;
|
||||
}
|
||||
void (async () => {
|
||||
if (workspaceKind === "worktree") {
|
||||
confirmingRef.current = true;
|
||||
let confirmed: boolean;
|
||||
try {
|
||||
confirmed = await confirmWorktreeArchive();
|
||||
} finally {
|
||||
confirmingRef.current = false;
|
||||
}
|
||||
if (!confirmed) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
await archiveWorkspaceRecord();
|
||||
})();
|
||||
}, [archiveWorkspaceRecord, confirmWorktreeArchive, workspaceKind]);
|
||||
void runWorkspaceArchiveAttempt({
|
||||
workspace: { serverId, workspaceId },
|
||||
confirm: workspaceKind === "worktree" ? confirmWorktreeArchive : undefined,
|
||||
archive: archiveWorkspaceRecord,
|
||||
});
|
||||
}, [archiveWorkspaceRecord, confirmWorktreeArchive, serverId, workspaceId, workspaceKind]);
|
||||
|
||||
return {
|
||||
archive,
|
||||
|
||||
@@ -17,6 +17,30 @@ export interface WorkspaceArchiveTarget {
|
||||
workspaceId: string;
|
||||
}
|
||||
|
||||
const pendingArchiveAttempts = new Set<string>();
|
||||
|
||||
/** Checks and starts one archive at a time for a workspace. */
|
||||
export async function runWorkspaceArchiveAttempt(input: {
|
||||
workspace: WorkspaceArchiveTarget;
|
||||
confirm?: () => Promise<boolean>;
|
||||
archive: () => Promise<void>;
|
||||
}): Promise<void> {
|
||||
const { serverId, workspaceId } = input.workspace;
|
||||
const key = JSON.stringify([serverId, workspaceId]);
|
||||
if (pendingArchiveAttempts.has(key)) return;
|
||||
|
||||
pendingArchiveAttempts.add(key);
|
||||
try {
|
||||
if (input.confirm && !(await input.confirm())) return;
|
||||
if (!isWorkspaceListed(input.workspace)) return;
|
||||
// Archive hides the row synchronously. Undo can restore it and start a new
|
||||
// archive while the previous daemon request is still settling.
|
||||
return input.archive();
|
||||
} finally {
|
||||
pendingArchiveAttempts.delete(key);
|
||||
}
|
||||
}
|
||||
|
||||
interface WorkspaceArchiveClient {
|
||||
archiveWorkspace: (workspaceId: string) => Promise<{ error: string | null; canceled?: boolean }>;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,164 @@
|
||||
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();
|
||||
});
|
||||
@@ -89,6 +89,9 @@ export async function createAcpProviderConnection(
|
||||
if (probe.agentCapabilities.loadSession) {
|
||||
supportedCapabilities.push("session.persistence");
|
||||
}
|
||||
if (options.acpOptions?.deferTurnOnRunningTools) {
|
||||
supportedCapabilities.push("prompt.steer");
|
||||
}
|
||||
await probe.close();
|
||||
const capabilities = negotiateProviderCapabilities(request.capabilities, supportedCapabilities);
|
||||
const listeners = new Set<(event: ProviderEvent) => void>();
|
||||
@@ -214,10 +217,13 @@ async function dispatch(input: ProviderInput, state: AcpConnectionState): Promis
|
||||
await mutateSession(session, () => session.runtime.prompt(input));
|
||||
return;
|
||||
}
|
||||
case "session.interrupt":
|
||||
await requireSession(state, input.sessionId).runtime.interrupt();
|
||||
case "session.interrupt": {
|
||||
const session = requireSession(state, input.sessionId);
|
||||
const retired = await session.runtime.interrupt();
|
||||
state.emit({ type: "request.completed", requestId: input.requestId });
|
||||
if (retired) retireSession(state, input.sessionId);
|
||||
return;
|
||||
}
|
||||
case "session.permission":
|
||||
requireSession(state, input.sessionId).runtime.respondToPermission(
|
||||
input.permissionId,
|
||||
@@ -304,6 +310,12 @@ async function listSessions(
|
||||
}
|
||||
}
|
||||
|
||||
function retireSession(state: AcpConnectionState, sessionId: string): void {
|
||||
if (state.sessions.delete(sessionId)) {
|
||||
state.emit({ type: "session.closed", sessionId });
|
||||
}
|
||||
}
|
||||
|
||||
async function openSession(
|
||||
input: Extract<ProviderInput, { type: "session.open" }>,
|
||||
state: AcpConnectionState,
|
||||
@@ -317,6 +329,7 @@ async function openSession(
|
||||
cwd: input.config.cwd,
|
||||
env: input.config.env,
|
||||
emit: state.emit,
|
||||
onRetired: () => retireSession(state, input.sessionId),
|
||||
});
|
||||
try {
|
||||
const capabilities = await runtime.open(input, state.capabilities);
|
||||
@@ -358,6 +371,7 @@ interface StartRuntimeOptions {
|
||||
cwd?: string;
|
||||
env: Readonly<Record<string, string>>;
|
||||
emit(event: ProviderEvent): void;
|
||||
onRetired?: () => void;
|
||||
}
|
||||
|
||||
interface PendingPermission {
|
||||
@@ -366,6 +380,33 @@ interface PendingPermission {
|
||||
resolve(response: RequestPermissionResponse): void;
|
||||
}
|
||||
|
||||
type DeferredTurnOutcome =
|
||||
| { type: "complete"; terminalizeTools: boolean }
|
||||
| { type: "cancel" }
|
||||
| { type: "fail"; error: { message: string } };
|
||||
|
||||
interface DeferredTurnState {
|
||||
timer: ReturnType<typeof setTimeout> | null;
|
||||
resolve(outcome: DeferredTurnOutcome): void;
|
||||
}
|
||||
|
||||
type DeferredReplyState = "idle" | "open" | "settled_with_open_tools" | "settled";
|
||||
|
||||
interface ActivePrompt {
|
||||
turnId: string;
|
||||
settled: Promise<void>;
|
||||
cancelling: boolean;
|
||||
wirePromptsInFlight: number;
|
||||
wirePromptLane: Promise<void>;
|
||||
lastPromptResponseWireSeq: number | null;
|
||||
crossedEndTurn: boolean;
|
||||
replyState: DeferredReplyState;
|
||||
deferred: DeferredTurnState | null;
|
||||
}
|
||||
|
||||
const DEFAULT_DEFERRED_SETTLE_DELAY_MS = 500;
|
||||
const DEFAULT_DEFERRED_QUIET_LIMIT_MS = 120_000;
|
||||
|
||||
class AcpRuntime {
|
||||
readonly connection: ClientSideConnection;
|
||||
agentCapabilities: AgentCapabilities = {};
|
||||
@@ -374,6 +415,8 @@ class AcpRuntime {
|
||||
private emit: (event: ProviderEvent) => void;
|
||||
private readonly messages = new Map<string, string>();
|
||||
private readonly toolCalls = new Map<string, AcpToolCallSnapshot>();
|
||||
private readonly liveOpenToolIds = new Set<string>();
|
||||
private readonly canceledToolCallIds = new Set<string>();
|
||||
// Running tool rows published by transformers; the turn's terminal closes any left open.
|
||||
private readonly vendorToolCalls = new Map<string, ToolCallTimelineItem>();
|
||||
private readonly pendingCompactions = new Set<string>();
|
||||
@@ -401,21 +444,33 @@ class AcpRuntime {
|
||||
private replayWindow: "replay" | "skip" | null = null;
|
||||
private lastLoadUpdateAt = 0;
|
||||
private closing = false;
|
||||
private closePromise: Promise<void> | null = null;
|
||||
private deferredRetirement: Promise<boolean> | null = null;
|
||||
private deferredFinalized = false;
|
||||
private processFailed = false;
|
||||
private configTransaction = false;
|
||||
private stagedTransformerConfig: ProviderConfigState | null = null;
|
||||
private readonly closeConnector: () => Promise<void>;
|
||||
private readonly closeConnector: (options?: {
|
||||
force?: boolean;
|
||||
timeoutMs?: number;
|
||||
}) => Promise<void>;
|
||||
private readonly whenConnectorClosed: () => Promise<void> | null;
|
||||
private notificationLane: Promise<void> = Promise.resolve();
|
||||
private incomingWireSeq = 0;
|
||||
private readonly sessionUpdateWireSeqs: number[] = [];
|
||||
private autoAccept = false;
|
||||
private activePrompt: { turnId: string; settled: Promise<void>; cancelling: boolean } | null =
|
||||
null;
|
||||
private activePrompt: ActivePrompt | null = null;
|
||||
private lastUsage: ProviderUsage = {};
|
||||
|
||||
static async start(options: StartRuntimeOptions): Promise<AcpRuntime> {
|
||||
let child: ChildProcessWithoutNullStreams | null = null;
|
||||
let spawnFailure: Promise<never> | null = null;
|
||||
let stream: Stream;
|
||||
let closeConnector = async () => {};
|
||||
let closeConnector: (options?: {
|
||||
force?: boolean;
|
||||
timeoutMs?: number;
|
||||
}) => Promise<void> = async () => {};
|
||||
let whenConnectorClosed: () => Promise<void> | null = () => null;
|
||||
if (options.options.command) {
|
||||
// COMPAT(pluginProviderLaunch): added in v0.10.0, remove after 2027-03-29 once plugin host floor >= v0.10.0.
|
||||
// Standalone callers and older hosts do not send a daemon-resolved launch.
|
||||
@@ -438,8 +493,9 @@ class AcpRuntime {
|
||||
const owned = ownConnectorStream(await options.options.connector());
|
||||
stream = owned.stream;
|
||||
closeConnector = owned.close;
|
||||
whenConnectorClosed = owned.whenClosed;
|
||||
}
|
||||
const runtime = new AcpRuntime(stream, child, closeConnector, options);
|
||||
const runtime = new AcpRuntime(stream, child, closeConnector, whenConnectorClosed, options);
|
||||
try {
|
||||
const initialize = withTimeout(
|
||||
runtime.call(
|
||||
@@ -466,41 +522,51 @@ class AcpRuntime {
|
||||
private constructor(
|
||||
stream: Stream,
|
||||
child: ChildProcessWithoutNullStreams | null,
|
||||
closeConnector: () => Promise<void>,
|
||||
closeConnector: (options?: { force?: boolean; timeoutMs?: number }) => Promise<void>,
|
||||
whenConnectorClosed: () => Promise<void> | null,
|
||||
private readonly options: StartRuntimeOptions,
|
||||
) {
|
||||
this.child = child;
|
||||
this.closeConnector = closeConnector;
|
||||
this.whenConnectorClosed = whenConnectorClosed;
|
||||
this.emit = options.emit;
|
||||
this.transformers = options.options.transformers ?? [];
|
||||
const client: Client = {
|
||||
requestPermission: (request) => this.requestPermission(request),
|
||||
sessionUpdate: (notification) =>
|
||||
this.enqueueNotification(() => this.sessionUpdate(notification)),
|
||||
sessionUpdate: (notification) => {
|
||||
const wireSeq = this.sessionUpdateWireSeqs.shift() ?? ++this.incomingWireSeq;
|
||||
return this.enqueueNotification(() => this.sessionUpdate(notification, wireSeq));
|
||||
},
|
||||
};
|
||||
this.connection = new ClientSideConnection(
|
||||
() => client,
|
||||
routeVendorNotifications(stream, (method, params) => this.vendorNotification(method, params)),
|
||||
routeIncomingMessages(
|
||||
stream,
|
||||
(method, params) => this.vendorNotification(method, params),
|
||||
(message) => this.observeWireMessage(message),
|
||||
),
|
||||
);
|
||||
if (!child) void this.connection.closed.then(() => this.handleUnexpectedTransportClose());
|
||||
child?.on("error", (error) => {
|
||||
const message = describeError(error);
|
||||
this.processFailed = true;
|
||||
this.settlePendingWork();
|
||||
this.settlePendingWork(message);
|
||||
if (this.closing || !this.nativeSessionId) return;
|
||||
this.emit({
|
||||
type: "session.runtime_failed",
|
||||
sessionId: this.options.boundarySessionId,
|
||||
error: { message: describeError(error) },
|
||||
error: { message },
|
||||
});
|
||||
});
|
||||
child?.once("close", (code, signal) => {
|
||||
if (this.closing || this.processFailed || !this.nativeSessionId) return;
|
||||
const message = `ACP process exited (${signal ?? code ?? "unknown"})`;
|
||||
this.processFailed = true;
|
||||
this.settlePendingWork();
|
||||
this.settlePendingWork(message);
|
||||
this.emit({
|
||||
type: "session.runtime_failed",
|
||||
sessionId: this.options.boundarySessionId,
|
||||
error: { message: `ACP process exited (${signal ?? code ?? "unknown"})` },
|
||||
error: { message },
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -609,10 +675,31 @@ class AcpRuntime {
|
||||
}
|
||||
|
||||
async prompt(input: Extract<ProviderInput, { type: "session.prompt" }>): Promise<void> {
|
||||
if (this.closing || this.processFailed || this.deferredRetirement) {
|
||||
throw new Error("ACP session is closed");
|
||||
}
|
||||
if (input.prompt.delivery === "steer") {
|
||||
this.steerDeferredPrompt(input);
|
||||
return;
|
||||
}
|
||||
const active = this.activePrompt;
|
||||
if (active) {
|
||||
await this.interrupt();
|
||||
if (active.deferred && active.wirePromptsInFlight === 0) {
|
||||
// Wire session/prompt already resolved; finish the deferred turn without sending
|
||||
// session/cancel so running background tools stay alive into the follow-up turn.
|
||||
this.finishDeferredTurn(active, { type: "complete", terminalizeTools: false });
|
||||
} else {
|
||||
const retired = await this.interrupt();
|
||||
if (retired) {
|
||||
// Notify caller that the session closed before failing the replacement prompt.
|
||||
this.options.onRetired?.();
|
||||
throw new Error("ACP session retired after stopping deferred background work");
|
||||
}
|
||||
}
|
||||
await active.settled;
|
||||
if (this.closing || this.processFailed || this.deferredRetirement) {
|
||||
throw new Error("ACP session is closed");
|
||||
}
|
||||
}
|
||||
const prompt = toAcpPrompt(input.prompt);
|
||||
this.replayWindow = null;
|
||||
@@ -643,6 +730,17 @@ class AcpRuntime {
|
||||
turnId,
|
||||
state: "started",
|
||||
});
|
||||
const activePrompt: ActivePrompt = {
|
||||
turnId,
|
||||
settled: Promise.resolve(),
|
||||
cancelling: false,
|
||||
wirePromptsInFlight: 1,
|
||||
wirePromptLane: Promise.resolve(),
|
||||
lastPromptResponseWireSeq: null,
|
||||
crossedEndTurn: false,
|
||||
replyState: "idle",
|
||||
deferred: null,
|
||||
};
|
||||
// The SDK dispatches notifications without awaiting them, so the prompt response can resolve
|
||||
// while earlier session updates are still queued. Apply them before the turn ends.
|
||||
const settled = this.call(
|
||||
@@ -650,6 +748,7 @@ class AcpRuntime {
|
||||
).then(
|
||||
async (response): Promise<void> => {
|
||||
await this.drainNotifications();
|
||||
activePrompt.wirePromptsInFlight -= 1;
|
||||
if (response.usage) {
|
||||
this.lastUsage = {
|
||||
...this.lastUsage,
|
||||
@@ -665,47 +764,95 @@ class AcpRuntime {
|
||||
});
|
||||
}
|
||||
const state = response.stopReason === "cancelled" ? "canceled" : "completed";
|
||||
this.fallbackChunkIds.clear();
|
||||
this.terminalizeTransientItems(state);
|
||||
this.finishTurnPermissions(turnId);
|
||||
this.emit({
|
||||
type: "session.turn",
|
||||
sessionId: this.options.boundarySessionId,
|
||||
turnId,
|
||||
state,
|
||||
});
|
||||
if (response.stopReason === "end_turn" && this.shouldDeferTurn(activePrompt)) {
|
||||
await this.settleDeferredPrompt(activePrompt);
|
||||
return undefined;
|
||||
}
|
||||
this.finishPromptTurn(turnId, state);
|
||||
return undefined;
|
||||
},
|
||||
async (error): Promise<void> => {
|
||||
await this.drainNotifications();
|
||||
this.fallbackChunkIds.clear();
|
||||
this.terminalizeTransientItems("failed");
|
||||
this.finishTurnPermissions(turnId);
|
||||
this.emit({
|
||||
type: "session.turn",
|
||||
sessionId: this.options.boundarySessionId,
|
||||
turnId,
|
||||
state: "failed",
|
||||
error: { message: describeError(error) },
|
||||
});
|
||||
activePrompt.wirePromptsInFlight -= 1;
|
||||
this.finishPromptTurn(turnId, "failed", { message: describeError(error) });
|
||||
return undefined;
|
||||
},
|
||||
);
|
||||
this.activePrompt = { turnId, settled, cancelling: false };
|
||||
activePrompt.settled = settled;
|
||||
this.activePrompt = activePrompt;
|
||||
void settled.finally(() => {
|
||||
if (this.activePrompt?.turnId === turnId) this.activePrompt = null;
|
||||
});
|
||||
}
|
||||
|
||||
async interrupt(): Promise<void> {
|
||||
async interrupt(): Promise<boolean> {
|
||||
if (this.deferredRetirement) return this.deferredRetirement;
|
||||
const active = this.activePrompt;
|
||||
const deferredTurnId = active?.deferred ? active.turnId : null;
|
||||
if (active && deferredTurnId) {
|
||||
const retirement = this.retireDeferredTurn(active, deferredTurnId).catch((error) => {
|
||||
if (this.deferredRetirement === retirement) this.deferredRetirement = null;
|
||||
throw error;
|
||||
});
|
||||
this.deferredRetirement = retirement;
|
||||
return retirement;
|
||||
}
|
||||
if (active) active.cancelling = true;
|
||||
try {
|
||||
await this.call(this.connection.cancel({ sessionId: this.nativeSessionId }));
|
||||
} finally {
|
||||
// An agent may wait for its outstanding permission replies before ending the prompt.
|
||||
if (active) this.finishTurnPermissions(active.turnId);
|
||||
if (active) {
|
||||
this.finishTurnPermissions(active.turnId);
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private finalizeDeferredTurn(deferredTurnId: string, emitRetired: boolean): void {
|
||||
if (this.deferredFinalized) return;
|
||||
this.deferredFinalized = true;
|
||||
this.finishPromptTurn(deferredTurnId, "canceled", undefined, {
|
||||
suppressTrailingToolEcho: true,
|
||||
});
|
||||
if (emitRetired) this.options.onRetired?.();
|
||||
}
|
||||
|
||||
private async retireDeferredTurn(active: ActivePrompt, deferredTurnId: string): Promise<boolean> {
|
||||
active.cancelling = true;
|
||||
// Record open tools owned by Stop before writing session/cancel so any failure
|
||||
// update arriving during cancel preserves their canceled state.
|
||||
for (const id of this.liveOpenToolIds) this.canceledToolCallIds.add(id);
|
||||
let cancelTimedOut = false;
|
||||
if (!this.closing) {
|
||||
try {
|
||||
await withTimeout(
|
||||
this.call(this.connection.cancel({ sessionId: this.nativeSessionId })),
|
||||
1_000,
|
||||
`ACP session ${this.nativeSessionId} did not accept cancel`,
|
||||
);
|
||||
} catch {
|
||||
cancelTimedOut = true;
|
||||
} finally {
|
||||
// An agent may wait for its outstanding permission replies before ending the prompt.
|
||||
this.finishTurnPermissions(active.turnId);
|
||||
}
|
||||
}
|
||||
// ACP v1 has no response or end boundary for session/cancel once session/prompt
|
||||
// already returned. Close the process first while the turn still appears running,
|
||||
// then emit the canceled turn synchronously before request.completed and session.closed
|
||||
// so queued work and config changes immediately observe the retired session.
|
||||
try {
|
||||
await this.close({ force: cancelTimedOut, timeoutMs: 1_000 });
|
||||
} catch (error) {
|
||||
void this.whenConnectorClosed()?.then(
|
||||
() => this.finalizeDeferredTurn(deferredTurnId, true),
|
||||
() => undefined,
|
||||
);
|
||||
throw error;
|
||||
}
|
||||
this.finalizeDeferredTurn(deferredTurnId, false);
|
||||
return true;
|
||||
}
|
||||
|
||||
listSessions(cwd?: string) {
|
||||
@@ -758,6 +905,7 @@ class AcpRuntime {
|
||||
sessionId: this.options.boundarySessionId,
|
||||
permissionId,
|
||||
});
|
||||
if (this.activePrompt?.deferred) this.scheduleDeferredSettle();
|
||||
}
|
||||
|
||||
async configure(
|
||||
@@ -833,11 +981,20 @@ class AcpRuntime {
|
||||
await this.close();
|
||||
}
|
||||
|
||||
async close(): Promise<void> {
|
||||
if (this.closing) return;
|
||||
close(options?: { force?: boolean; timeoutMs?: number }): Promise<void> {
|
||||
if (this.closePromise) return this.closePromise;
|
||||
this.closing = true;
|
||||
const promise = this.closeInternal(options).catch((error) => {
|
||||
if (this.closePromise === promise) this.closePromise = null;
|
||||
throw error;
|
||||
});
|
||||
this.closePromise = promise;
|
||||
return promise;
|
||||
}
|
||||
|
||||
private async closeInternal(options?: { force?: boolean; timeoutMs?: number }): Promise<void> {
|
||||
this.settlePendingWork();
|
||||
await this.closeConnector();
|
||||
await this.closeConnector(options);
|
||||
const child = this.child;
|
||||
if (!child || this.processFailed) return;
|
||||
if (child.exitCode !== null || child.signalCode !== null) return;
|
||||
@@ -1066,6 +1223,7 @@ class AcpRuntime {
|
||||
const permissionId = `permission:${request.toolCall.toolCallId}`;
|
||||
return new Promise((resolve) => {
|
||||
this.permissions.set(permissionId, { request, resolve, turnId: this.activePrompt?.turnId });
|
||||
if (this.activePrompt?.deferred) this.scheduleDeferredSettle();
|
||||
this.emit({
|
||||
type: "session.permission",
|
||||
sessionId: this.options.boundarySessionId,
|
||||
@@ -1085,7 +1243,31 @@ class AcpRuntime {
|
||||
});
|
||||
}
|
||||
|
||||
private sessionUpdate(notification: SessionNotification): void {
|
||||
private observeWireMessage(message: unknown): void {
|
||||
if (typeof message !== "object" || message === null) return;
|
||||
const record = message as Record<string, unknown>;
|
||||
if (record.method === "session/update") {
|
||||
this.sessionUpdateWireSeqs.push(++this.incomingWireSeq);
|
||||
return;
|
||||
}
|
||||
if (
|
||||
!("method" in record) &&
|
||||
"id" in record &&
|
||||
typeof record.result === "object" &&
|
||||
record.result !== null &&
|
||||
typeof (record.result as Record<string, unknown>).stopReason === "string" &&
|
||||
this.activePrompt &&
|
||||
this.activePrompt.lastPromptResponseWireSeq === null
|
||||
) {
|
||||
this.activePrompt.lastPromptResponseWireSeq = ++this.incomingWireSeq;
|
||||
}
|
||||
}
|
||||
|
||||
private isPostWirePrompt(active: ActivePrompt, wireSeq: number): boolean {
|
||||
return active.lastPromptResponseWireSeq !== null && wireSeq > active.lastPromptResponseWireSeq;
|
||||
}
|
||||
|
||||
private sessionUpdate(notification: SessionNotification, wireSeq: number): void {
|
||||
if (notification.sessionId !== this.nativeSessionId) return;
|
||||
if (this.replayWindow) this.lastLoadUpdateAt = performance.now();
|
||||
if (this.replayWindow === "skip") {
|
||||
@@ -1096,7 +1278,7 @@ class AcpRuntime {
|
||||
update.sessionUpdate === "current_mode_update" ||
|
||||
update.sessionUpdate === "usage_update"
|
||||
) {
|
||||
this.reduceStateUpdate(update);
|
||||
this.reduceStateUpdate(update, wireSeq);
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -1107,10 +1289,10 @@ class AcpRuntime {
|
||||
this.reduceUserMessageChunk(notification.update);
|
||||
return;
|
||||
}
|
||||
this.reduceUpdate(notification.update);
|
||||
this.reduceUpdate(notification.update, wireSeq);
|
||||
}
|
||||
|
||||
private reduceUpdate(update: SessionUpdate): void {
|
||||
private reduceUpdate(update: SessionUpdate, wireSeq: number): void {
|
||||
if (
|
||||
update.sessionUpdate === "agent_message_chunk" ||
|
||||
update.sessionUpdate === "agent_thought_chunk" ||
|
||||
@@ -1144,15 +1326,16 @@ class AcpRuntime {
|
||||
: {}),
|
||||
},
|
||||
});
|
||||
this.noteDeferredChunk(update.sessionUpdate, wireSeq);
|
||||
return;
|
||||
}
|
||||
if (update.sessionUpdate === "tool_call" || update.sessionUpdate === "tool_call_update") {
|
||||
if (update.sessionUpdate === "tool_call") this.fallbackChunkIds.clear();
|
||||
this.reduceToolCall(update);
|
||||
this.reduceToolCall(update, wireSeq);
|
||||
return;
|
||||
}
|
||||
if (update.sessionUpdate === "plan") this.fallbackChunkIds.clear();
|
||||
this.reduceStateUpdate(update);
|
||||
this.reduceStateUpdate(update, wireSeq);
|
||||
}
|
||||
|
||||
// Historical user messages arrive only as replayed chunks; a live prompt
|
||||
@@ -1196,7 +1379,7 @@ class AcpRuntime {
|
||||
return id;
|
||||
}
|
||||
|
||||
private reduceStateUpdate(update: SessionUpdate): void {
|
||||
private reduceStateUpdate(update: SessionUpdate, wireSeq: number): void {
|
||||
if (update.sessionUpdate === "plan") {
|
||||
this.emit({
|
||||
type: "timeline.item",
|
||||
@@ -1253,6 +1436,7 @@ class AcpRuntime {
|
||||
sessionId: this.options.boundarySessionId,
|
||||
usage: this.lastUsage,
|
||||
});
|
||||
this.noteDeferredUsageUpdate(wireSeq);
|
||||
return;
|
||||
}
|
||||
if (update.sessionUpdate === "compaction_update") {
|
||||
@@ -1267,12 +1451,20 @@ class AcpRuntime {
|
||||
status: update.status === "completed" ? "completed" : "loading",
|
||||
},
|
||||
});
|
||||
if (this.activePrompt?.deferred) this.scheduleDeferredSettle();
|
||||
}
|
||||
}
|
||||
|
||||
private terminalizeTransientItems(state: "completed" | "failed" | "canceled"): void {
|
||||
private terminalizeTransientItems(
|
||||
state: "completed" | "failed" | "canceled",
|
||||
options?: { preserveQualifyingOpenTools?: boolean; suppressTrailingToolEcho?: boolean },
|
||||
): void {
|
||||
const preserve = options?.preserveQualifyingOpenTools === true;
|
||||
for (const [id, snapshot] of this.toolCalls) {
|
||||
if (snapshot.status !== "pending" && snapshot.status !== "in_progress") continue;
|
||||
if (preserve && this.liveOpenToolIds.has(id) && this.toolKeepsTurnOpen(snapshot)) continue;
|
||||
this.liveOpenToolIds.delete(id);
|
||||
if (options?.suppressTrailingToolEcho) this.canceledToolCallIds.add(id);
|
||||
const completed: AcpToolCallSnapshot = {
|
||||
...snapshot,
|
||||
status: state === "completed" ? "completed" : "failed",
|
||||
@@ -1302,18 +1494,42 @@ class AcpRuntime {
|
||||
this.pendingCompactions.clear();
|
||||
}
|
||||
|
||||
private reduceToolCall(update: ToolCall | ToolCallUpdate): void {
|
||||
private reduceToolCall(
|
||||
update: Extract<SessionUpdate, { sessionUpdate: "tool_call" | "tool_call_update" }>,
|
||||
wireSeq: number,
|
||||
): void {
|
||||
if (
|
||||
update.sessionUpdate === "tool_call_update" &&
|
||||
this.canceledToolCallIds.has(update.toolCallId)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
if (update.sessionUpdate === "tool_call") {
|
||||
this.canceledToolCallIds.delete(update.toolCallId);
|
||||
}
|
||||
const current = this.toolCalls.get(update.toolCallId);
|
||||
const wasOpenQualifying =
|
||||
current !== undefined &&
|
||||
this.liveOpenToolIds.has(current.id) &&
|
||||
this.toolKeepsTurnOpen(current);
|
||||
let snapshot = mergeToolCallSnapshot(update, current);
|
||||
const context = { sessionId: this.options.boundarySessionId };
|
||||
for (const transformer of this.transformers)
|
||||
snapshot = transformer.toolCall?.(snapshot, context) ?? snapshot;
|
||||
this.toolCalls.set(snapshot.id, snapshot);
|
||||
const isOpen = snapshot.status === "pending" || snapshot.status === "in_progress";
|
||||
if (this.replayWindow === null) {
|
||||
if (isOpen) this.liveOpenToolIds.add(snapshot.id);
|
||||
else this.liveOpenToolIds.delete(snapshot.id);
|
||||
}
|
||||
this.emit({
|
||||
type: "timeline.item",
|
||||
sessionId: this.options.boundarySessionId,
|
||||
item: toolTimelineItem(snapshot),
|
||||
});
|
||||
const isOpenQualifying =
|
||||
this.liveOpenToolIds.has(snapshot.id) && this.toolKeepsTurnOpen(snapshot);
|
||||
this.noteDeferredToolTransition(wasOpenQualifying, isOpenQualifying, isOpen, snapshot, wireSeq);
|
||||
}
|
||||
|
||||
private vendorNotification(method: string, params: unknown): void {
|
||||
@@ -1376,25 +1592,306 @@ class AcpRuntime {
|
||||
|
||||
private handleUnexpectedTransportClose(): void {
|
||||
if (this.closing || this.processFailed) return;
|
||||
const message = "ACP transport closed unexpectedly";
|
||||
this.processFailed = true;
|
||||
this.settlePendingWork();
|
||||
this.settlePendingWork(message);
|
||||
if (!this.nativeSessionId) return;
|
||||
this.emit({
|
||||
type: "session.runtime_failed",
|
||||
sessionId: this.options.boundarySessionId,
|
||||
error: { message: "ACP transport closed unexpectedly" },
|
||||
error: { message },
|
||||
});
|
||||
}
|
||||
|
||||
private settlePendingWork(): void {
|
||||
private settlePendingWork(failureMessage?: string): void {
|
||||
for (const permission of this.permissions.values()) {
|
||||
permission.resolve({ outcome: { outcome: "cancelled" } });
|
||||
}
|
||||
this.permissions.clear();
|
||||
if (this.activePrompt?.deferred) {
|
||||
this.finishDeferredTurn(
|
||||
this.activePrompt,
|
||||
failureMessage ? { type: "fail", error: { message: failureMessage } } : { type: "cancel" },
|
||||
);
|
||||
}
|
||||
this.commandWaiter?.();
|
||||
this.commandWaiter = null;
|
||||
}
|
||||
|
||||
private finishPromptTurn(
|
||||
turnId: string,
|
||||
state: "completed" | "failed" | "canceled",
|
||||
error?: { message: string },
|
||||
options?: { preserveQualifyingOpenTools?: boolean; suppressTrailingToolEcho?: boolean },
|
||||
): void {
|
||||
this.fallbackChunkIds.clear();
|
||||
this.terminalizeTransientItems(state, options);
|
||||
this.finishTurnPermissions(turnId);
|
||||
if (state === "failed") {
|
||||
this.emit({
|
||||
type: "session.turn",
|
||||
sessionId: this.options.boundarySessionId,
|
||||
turnId,
|
||||
state,
|
||||
error: error ?? { message: "ACP turn failed" },
|
||||
});
|
||||
return;
|
||||
}
|
||||
this.emit({
|
||||
type: "session.turn",
|
||||
sessionId: this.options.boundarySessionId,
|
||||
turnId,
|
||||
state,
|
||||
});
|
||||
}
|
||||
|
||||
private steerDeferredPrompt(input: Extract<ProviderInput, { type: "session.prompt" }>): void {
|
||||
const active = this.activePrompt;
|
||||
const deferred = active?.deferred;
|
||||
if (!active || !deferred || active.cancelling || this.closing || this.processFailed) {
|
||||
this.emit({
|
||||
type: "session.prompt_result",
|
||||
sessionId: this.options.boundarySessionId,
|
||||
clientMessageId: input.prompt.clientMessageId,
|
||||
result: {
|
||||
type: "failed",
|
||||
error: {
|
||||
message: "ACP session can only steer while waiting on deferred background tools",
|
||||
},
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (input.prompt.clearPendingPermissions) {
|
||||
this.finishTurnPermissions(active.turnId);
|
||||
}
|
||||
const prompt = toAcpPrompt(input.prompt);
|
||||
active.wirePromptsInFlight += 1;
|
||||
this.scheduleDeferredSettle();
|
||||
this.replayWindow = null;
|
||||
this.fallbackChunkIds.clear();
|
||||
this.emit({
|
||||
type: "timeline.item",
|
||||
sessionId: this.options.boundarySessionId,
|
||||
item: {
|
||||
type: "user_message",
|
||||
id: input.prompt.clientMessageId,
|
||||
text: prompt
|
||||
.filter((part) => part.type === "text")
|
||||
.map((part) => part.text)
|
||||
.join("\n"),
|
||||
clientMessageId: input.prompt.clientMessageId,
|
||||
},
|
||||
});
|
||||
this.emit({
|
||||
type: "session.prompt_result",
|
||||
sessionId: this.options.boundarySessionId,
|
||||
clientMessageId: input.prompt.clientMessageId,
|
||||
result: { type: "steer", turnId: active.turnId },
|
||||
});
|
||||
const runSteer = async (): Promise<void> => {
|
||||
try {
|
||||
if (
|
||||
this.closing ||
|
||||
this.processFailed ||
|
||||
active.cancelling ||
|
||||
active.deferred !== deferred
|
||||
) {
|
||||
return;
|
||||
}
|
||||
this.fallbackChunkIds.clear();
|
||||
active.lastPromptResponseWireSeq = null;
|
||||
if (active.replyState === "settled_with_open_tools") active.replyState = "idle";
|
||||
const response = await this.call(
|
||||
this.connection.prompt({ sessionId: this.nativeSessionId, prompt }),
|
||||
);
|
||||
await this.drainNotifications();
|
||||
if (this.closing || this.deferredRetirement || active.deferred !== deferred) return;
|
||||
if (response.usage) {
|
||||
this.lastUsage = {
|
||||
...this.lastUsage,
|
||||
inputTokens: response.usage.inputTokens,
|
||||
outputTokens: response.usage.outputTokens,
|
||||
cachedInputTokens: response.usage.cachedReadTokens ?? undefined,
|
||||
};
|
||||
this.emit({
|
||||
type: "session.usage",
|
||||
sessionId: this.options.boundarySessionId,
|
||||
turnId: active.turnId,
|
||||
usage: this.lastUsage,
|
||||
});
|
||||
}
|
||||
if (response.stopReason === "cancelled") {
|
||||
this.finishDeferredTurn(active, { type: "cancel" });
|
||||
return;
|
||||
}
|
||||
if (response.stopReason !== "end_turn" && active.wirePromptsInFlight === 1) {
|
||||
this.finishDeferredTurn(active, { type: "complete", terminalizeTools: true });
|
||||
}
|
||||
} catch (error) {
|
||||
await this.drainNotifications();
|
||||
if (this.closing || this.deferredRetirement || active.deferred !== deferred) return;
|
||||
if (this.processFailed) {
|
||||
this.finishDeferredTurn(active, {
|
||||
type: "fail",
|
||||
error: { message: describeError(error) },
|
||||
});
|
||||
} else {
|
||||
this.emit({
|
||||
type: "session.notice",
|
||||
sessionId: this.options.boundarySessionId,
|
||||
notice: {
|
||||
id: `acp:steer-error:${input.prompt.clientMessageId}`,
|
||||
severity: "error",
|
||||
title: "Follow-up prompt failed",
|
||||
description: describeError(error),
|
||||
},
|
||||
});
|
||||
}
|
||||
} finally {
|
||||
if (active.lastPromptResponseWireSeq === null) {
|
||||
active.lastPromptResponseWireSeq = this.incomingWireSeq;
|
||||
}
|
||||
active.wirePromptsInFlight -= 1;
|
||||
this.scheduleDeferredSettle();
|
||||
}
|
||||
};
|
||||
active.wirePromptLane = active.wirePromptLane.then(runSteer);
|
||||
}
|
||||
|
||||
private async settleDeferredPrompt(active: ActivePrompt): Promise<void> {
|
||||
this.fallbackChunkIds.clear();
|
||||
const outcome = await new Promise<DeferredTurnOutcome>((resolve) => {
|
||||
active.deferred = { timer: null, resolve };
|
||||
this.scheduleDeferredSettle();
|
||||
});
|
||||
if (this.closing || this.deferredRetirement) return;
|
||||
if (outcome.type === "fail") {
|
||||
this.finishPromptTurn(active.turnId, "failed", outcome.error);
|
||||
return;
|
||||
}
|
||||
this.finishPromptTurn(
|
||||
active.turnId,
|
||||
outcome.type === "cancel" ? "canceled" : "completed",
|
||||
undefined,
|
||||
{
|
||||
preserveQualifyingOpenTools: outcome.type === "complete" && !outcome.terminalizeTools,
|
||||
suppressTrailingToolEcho: outcome.type === "cancel",
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
private toolKeepsTurnOpen(snapshot: AcpToolCallSnapshot): boolean {
|
||||
const defer = this.options.options.acpOptions?.deferTurnOnRunningTools;
|
||||
if (!defer) return false;
|
||||
return defer.keepsTurnOpen ? defer.keepsTurnOpen(snapshot) : true;
|
||||
}
|
||||
|
||||
private hasQualifyingOpenTools(): boolean {
|
||||
for (const id of this.liveOpenToolIds) {
|
||||
const snapshot = this.toolCalls.get(id);
|
||||
if (snapshot && this.toolKeepsTurnOpen(snapshot)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private hasDeferredBlockers(): boolean {
|
||||
return (
|
||||
(this.activePrompt?.wirePromptsInFlight ?? 0) > 0 ||
|
||||
this.hasQualifyingOpenTools() ||
|
||||
this.permissions.size > 0 ||
|
||||
this.pendingCompactions.size > 0
|
||||
);
|
||||
}
|
||||
|
||||
private shouldDeferTurn(active: ActivePrompt): boolean {
|
||||
if (!this.options.options.acpOptions?.deferTurnOnRunningTools) return false;
|
||||
if (active.cancelling || this.closing || this.processFailed) return false;
|
||||
return this.hasQualifyingOpenTools() || active.crossedEndTurn;
|
||||
}
|
||||
|
||||
private finishDeferredTurn(active: ActivePrompt, outcome: DeferredTurnOutcome): void {
|
||||
const deferred = active.deferred;
|
||||
if (!deferred) return;
|
||||
if (deferred.timer) clearTimeout(deferred.timer);
|
||||
active.deferred = null;
|
||||
deferred.resolve(outcome);
|
||||
}
|
||||
|
||||
private noteDeferredToolTransition(
|
||||
wasOpenQualifying: boolean,
|
||||
isOpenQualifying: boolean,
|
||||
isOpen: boolean,
|
||||
snapshot: AcpToolCallSnapshot,
|
||||
wireSeq: number,
|
||||
): void {
|
||||
const active = this.activePrompt;
|
||||
if (!active || wasOpenQualifying === isOpenQualifying) return;
|
||||
if (!active.deferred && !this.isPostWirePrompt(active, wireSeq)) return;
|
||||
if (!active.deferred && wasOpenQualifying && !isOpen && this.toolKeepsTurnOpen(snapshot)) {
|
||||
active.crossedEndTurn = true;
|
||||
}
|
||||
if (isOpenQualifying) active.replyState = "idle";
|
||||
if (active.deferred) this.scheduleDeferredSettle();
|
||||
}
|
||||
|
||||
private noteDeferredChunk(
|
||||
kind: "agent_message_chunk" | "agent_thought_chunk",
|
||||
wireSeq: number,
|
||||
): void {
|
||||
const active = this.activePrompt;
|
||||
if (!active || !this.isPostWirePrompt(active, wireSeq)) return;
|
||||
if (kind === "agent_message_chunk") active.replyState = "open";
|
||||
else if (active.replyState !== "open") active.replyState = "idle";
|
||||
if (active.deferred) this.scheduleDeferredSettle();
|
||||
}
|
||||
|
||||
private noteDeferredUsageUpdate(wireSeq: number): void {
|
||||
const active = this.activePrompt;
|
||||
if (!active || !this.isPostWirePrompt(active, wireSeq) || active.replyState !== "open") return;
|
||||
active.replyState = this.hasQualifyingOpenTools() ? "settled_with_open_tools" : "settled";
|
||||
if (active.deferred) this.scheduleDeferredSettle();
|
||||
}
|
||||
|
||||
private scheduleDeferredSettle(): void {
|
||||
const active = this.activePrompt;
|
||||
const deferred = active?.deferred;
|
||||
const config = this.options.options.acpOptions?.deferTurnOnRunningTools;
|
||||
if (!active || !deferred || !config || active.cancelling) return;
|
||||
if (deferred.timer) {
|
||||
clearTimeout(deferred.timer);
|
||||
deferred.timer = null;
|
||||
}
|
||||
if (this.hasDeferredBlockers()) return;
|
||||
const settled =
|
||||
active.replyState === "settled" || active.replyState === "settled_with_open_tools";
|
||||
const delayMs = settled
|
||||
? (config.settleDelayMs ?? DEFAULT_DEFERRED_SETTLE_DELAY_MS)
|
||||
: (config.quietLimitMs ?? DEFAULT_DEFERRED_QUIET_LIMIT_MS);
|
||||
deferred.timer = setTimeout(() => {
|
||||
deferred.timer = null;
|
||||
void this.trySettleDeferredTurn(active, deferred);
|
||||
}, delayMs);
|
||||
}
|
||||
|
||||
private async trySettleDeferredTurn(
|
||||
active: ActivePrompt,
|
||||
deferred: DeferredTurnState,
|
||||
): Promise<void> {
|
||||
await this.drainNotifications();
|
||||
if (
|
||||
this.closing ||
|
||||
this.processFailed ||
|
||||
active.cancelling ||
|
||||
active.deferred !== deferred ||
|
||||
deferred.timer !== null ||
|
||||
this.hasDeferredBlockers()
|
||||
) {
|
||||
return;
|
||||
}
|
||||
this.finishDeferredTurn(active, { type: "complete", terminalizeTools: true });
|
||||
}
|
||||
|
||||
private waitForInitialCommands(): Promise<void> {
|
||||
if (this.receivedInitialCommands) return Promise.resolve();
|
||||
const timeoutMs = this.options.options.acpOptions?.initialCommandsTimeoutMs ?? 1_000;
|
||||
@@ -1421,9 +1918,10 @@ class AcpRuntime {
|
||||
}
|
||||
}
|
||||
|
||||
function routeVendorNotifications(
|
||||
function routeIncomingMessages(
|
||||
stream: Stream,
|
||||
receive: (method: string, params: unknown) => void,
|
||||
receiveVendor: (method: string, params: unknown) => void,
|
||||
observeWire: (message: unknown) => void,
|
||||
): Stream {
|
||||
const clientMethods = new Set<string>(Object.values(CLIENT_METHODS));
|
||||
return {
|
||||
@@ -1435,11 +1933,14 @@ function routeVendorNotifications(
|
||||
// The SDK dispatches extensions asynchronously and can resolve a later response first.
|
||||
// Run synchronous vendor transforms in wire order, inside the configuration transaction.
|
||||
try {
|
||||
receive(message.method, message.params);
|
||||
receiveVendor(message.method, message.params);
|
||||
} catch (error) {
|
||||
console.error("Error handling ACP vendor notification", error);
|
||||
}
|
||||
} else controller.enqueue(message);
|
||||
} else {
|
||||
observeWire(message);
|
||||
controller.enqueue(message);
|
||||
}
|
||||
},
|
||||
}),
|
||||
),
|
||||
@@ -1470,11 +1971,12 @@ function permissionOptionBehavior(
|
||||
|
||||
function ownConnectorStream(source: Stream): {
|
||||
stream: Stream;
|
||||
close(): Promise<void>;
|
||||
close(options?: { force?: boolean; timeoutMs?: number }): Promise<void>;
|
||||
whenClosed(): Promise<void> | null;
|
||||
} {
|
||||
const reader = source.readable.getReader();
|
||||
const writer = source.writable.getWriter();
|
||||
let closed = false;
|
||||
let closing: Promise<void> | null = null;
|
||||
const stream: Stream = {
|
||||
readable: new ReadableStream({
|
||||
async pull(controller) {
|
||||
@@ -1496,13 +1998,29 @@ function ownConnectorStream(source: Stream): {
|
||||
};
|
||||
return {
|
||||
stream,
|
||||
async close() {
|
||||
if (closed) return;
|
||||
closed = true;
|
||||
await Promise.allSettled([
|
||||
reader.cancel(new Error("Paseo closed the ACP connector")),
|
||||
writer.close(),
|
||||
]);
|
||||
whenClosed: () => closing,
|
||||
async close(options?: { force?: boolean; timeoutMs?: number }) {
|
||||
if (!closing) {
|
||||
const closeWrite = options?.force
|
||||
? writer.abort(new Error("Paseo aborted the ACP connector"))
|
||||
: writer.close();
|
||||
closing = Promise.allSettled([
|
||||
reader.cancel(new Error("Paseo closed the ACP connector")),
|
||||
closeWrite,
|
||||
]).then((results) => {
|
||||
if (options?.timeoutMs === undefined) return undefined;
|
||||
const rejected = results.find(
|
||||
(result): result is PromiseRejectedResult => result.status === "rejected",
|
||||
);
|
||||
if (rejected) throw rejected.reason;
|
||||
return undefined;
|
||||
});
|
||||
}
|
||||
if (options?.timeoutMs !== undefined) {
|
||||
await withTimeout(closing, options.timeoutMs, "ACP connector did not close");
|
||||
} else {
|
||||
await closing.catch(() => undefined);
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -53,6 +53,18 @@ export interface AcpOptions {
|
||||
initialCommandsTimeoutMs?: number;
|
||||
/** Allow delayed session/load updates before publishing the session as ready. */
|
||||
loadReplayQuietPeriodMs?: number;
|
||||
/**
|
||||
* Keep a turn open after `end_turn` while qualifying tool calls are still running,
|
||||
* settling once those tools finish and the agent finishes its follow-up reply.
|
||||
*/
|
||||
deferTurnOnRunningTools?: {
|
||||
/** Delay after `usage_update` closes a follow-up reply before settling. Defaults to 500ms. */
|
||||
settleDelayMs?: number;
|
||||
/** Quiet limit after qualifying tools finish if no reply settles via `usage_update`. Defaults to 120_000ms. */
|
||||
quietLimitMs?: number;
|
||||
/** Predicate deciding whether an open tool call keeps the turn open. Defaults to all running tools. */
|
||||
keepsTurnOpen?: (toolCall: AcpToolCallSnapshot) => boolean;
|
||||
};
|
||||
/** An unattended mode that approves ACP allow-once requests in the specified native mode. */
|
||||
autoAcceptMode?: {
|
||||
mode: Omit<ProviderMode, "isUnattended">;
|
||||
|
||||
@@ -96,12 +96,12 @@ test.each([
|
||||
])(
|
||||
"duration %s owns the window's identity and both names",
|
||||
(durationSeconds, id, label, shortLabel) => {
|
||||
expect(
|
||||
windowFromReportedDuration({
|
||||
durationSeconds: durationSeconds as number | null,
|
||||
unknown: { id: "primary", label: "Primary limit", shortLabel: "" },
|
||||
utilizationPct: 11,
|
||||
}),
|
||||
).toMatchObject({ id, label, shortLabel, usedPct: 11 });
|
||||
const window = windowFromReportedDuration({
|
||||
durationSeconds: durationSeconds as number | null,
|
||||
unknown: { id: "primary", label: "Primary limit", shortLabel: "" },
|
||||
utilizationPct: 11,
|
||||
});
|
||||
expect(window).toMatchObject({ id, label, shortLabel, usedPct: 11 });
|
||||
expect(window.durationSeconds).toBe(durationSeconds ?? undefined);
|
||||
},
|
||||
);
|
||||
|
||||
@@ -16,6 +16,8 @@ export interface UsageWindow {
|
||||
usedPct?: number | null;
|
||||
remainingPct?: number | null;
|
||||
resetsAt?: string | null;
|
||||
/** Full length of the quota window when known. */
|
||||
durationSeconds?: number;
|
||||
runsOutAt?: string | null;
|
||||
shortfallPct?: number | null;
|
||||
tone?: "default" | "ok" | "warning" | "danger";
|
||||
@@ -48,6 +50,8 @@ export type UsageReport =
|
||||
| {
|
||||
status: "available";
|
||||
planLabel?: string;
|
||||
/** When the provider measured the quota, if the report returns a previous reading. */
|
||||
observedAt?: string;
|
||||
windows: UsageWindow[];
|
||||
balances?: UsageBalance[];
|
||||
details?: UsageDetail[];
|
||||
@@ -96,6 +100,7 @@ export function windowFromUsedPct(input: {
|
||||
shortLabel?: string;
|
||||
summary?: boolean;
|
||||
utilizationPct: number | null | undefined;
|
||||
durationSeconds?: number;
|
||||
resetsAt?: string | null;
|
||||
tone?: UsageWindow["tone"];
|
||||
}): UsageWindow {
|
||||
@@ -107,6 +112,7 @@ export function windowFromUsedPct(input: {
|
||||
remainingPct: usedPct === null ? null : Math.max(0, 100 - usedPct),
|
||||
resetsAt: input.resetsAt ?? null,
|
||||
};
|
||||
if (input.durationSeconds !== undefined) window.durationSeconds = input.durationSeconds;
|
||||
if (input.shortLabel !== undefined) window.shortLabel = input.shortLabel;
|
||||
if (input.summary) window.summary = true;
|
||||
if (input.tone) window.tone = input.tone;
|
||||
@@ -129,11 +135,10 @@ export function windowFromReportedDuration(input: {
|
||||
summary?: boolean;
|
||||
tone?: UsageWindow["tone"];
|
||||
}): UsageWindow {
|
||||
const duration = input.durationSeconds;
|
||||
const name =
|
||||
duration !== null && Number.isFinite(duration) && duration > 0
|
||||
? durationWindowName(duration)
|
||||
: input.unknown;
|
||||
const reported = input.durationSeconds;
|
||||
const duration =
|
||||
reported !== null && Number.isFinite(reported) && reported > 0 ? reported : undefined;
|
||||
const name = duration === undefined ? input.unknown : durationWindowName(duration);
|
||||
const scope = input.scope;
|
||||
return windowFromUsedPct({
|
||||
id: scope ? `${scope.id}:${name.id}` : name.id,
|
||||
@@ -142,6 +147,7 @@ export function windowFromReportedDuration(input: {
|
||||
? `${scope.label}${name.shortLabel ? ` ${name.shortLabel}` : ""}`
|
||||
: name.shortLabel,
|
||||
utilizationPct: input.utilizationPct,
|
||||
durationSeconds: duration,
|
||||
resetsAt: input.resetsAt,
|
||||
summary: input.summary,
|
||||
tone: input.tone,
|
||||
|
||||
@@ -6992,6 +6992,7 @@ export const ProviderUsageWindowSchema = z.object({
|
||||
usedPct: z.number().nullable().optional(),
|
||||
remainingPct: z.number().nullable().optional(),
|
||||
resetsAt: z.string().nullable().optional(),
|
||||
durationSeconds: z.number().optional(),
|
||||
runsOutAt: z.string().nullable().optional(),
|
||||
shortfallPct: z.number().nullable().optional(),
|
||||
tone: ProviderUsageToneSchema.optional(),
|
||||
@@ -7054,6 +7055,7 @@ export const UsageProblemSchema = z.discriminatedUnion("kind", [
|
||||
const AvailableUsageReportSchema = z.object({
|
||||
status: z.literal("available"),
|
||||
planLabel: z.string().optional(),
|
||||
observedAt: z.string().optional(),
|
||||
windows: z.array(ProviderUsageWindowSchema),
|
||||
balances: z.array(ProviderUsageBalanceSchema).optional(),
|
||||
details: z.array(ProviderUsageDetailSchema).optional(),
|
||||
|
||||
@@ -881,6 +881,7 @@ export class AgentManager {
|
||||
>();
|
||||
private readonly collectingRuntimes = new Set<string>();
|
||||
private readonly lifecycleMutationTails = new Map<string, Promise<void>>();
|
||||
private readonly pendingCancellations = new Map<string, Promise<unknown>>();
|
||||
private readonly agentStreamCoalescer: AgentStreamCoalescer;
|
||||
private mcpBaseUrl: string | null;
|
||||
private readonly mcpAuthToken: string | null;
|
||||
@@ -2463,80 +2464,83 @@ export class AgentManager {
|
||||
// reload or close; providers do no sequencing of their own.
|
||||
|
||||
async setAgentMode(agentId: string, modeId: string): Promise<AgentProviderNotice | null> {
|
||||
return this.runLifecycleMutation(agentId, async () => {
|
||||
const agent = await this.ensureInteractiveSessionUnlocked(agentId);
|
||||
const notice = (await agent.session.setMode(modeId)) ?? null;
|
||||
await this.drainSessionEvents(agentId);
|
||||
const currentMode = (await agent.session.getCurrentMode()) ?? modeId;
|
||||
agent.config.modeId = currentMode ?? undefined;
|
||||
agent.currentModeId = currentMode;
|
||||
// Update runtimeInfo to reflect the new mode
|
||||
if (agent.runtimeInfo) {
|
||||
agent.runtimeInfo = { ...agent.runtimeInfo, modeId: currentMode };
|
||||
}
|
||||
this.touchUpdatedAt(agent);
|
||||
this.emitState(agent);
|
||||
return notice;
|
||||
});
|
||||
return this.runLifecycleMutation(agentId, () =>
|
||||
this.withLiveInteractiveSessionUnlocked(agentId, async (agent) => {
|
||||
const notice = (await agent.session.setMode(modeId)) ?? null;
|
||||
await this.drainSessionEvents(agentId);
|
||||
const currentMode = (await agent.session.getCurrentMode()) ?? modeId;
|
||||
agent.config.modeId = currentMode ?? undefined;
|
||||
agent.currentModeId = currentMode;
|
||||
// Update runtimeInfo to reflect the new mode
|
||||
if (agent.runtimeInfo) {
|
||||
agent.runtimeInfo = { ...agent.runtimeInfo, modeId: currentMode };
|
||||
}
|
||||
this.touchUpdatedAt(agent);
|
||||
this.emitState(agent);
|
||||
return notice;
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
async setAgentModel(agentId: string, modelId: string | null): Promise<void> {
|
||||
return this.runLifecycleMutation(agentId, async () => {
|
||||
const agent = await this.ensureInteractiveSessionUnlocked(agentId);
|
||||
const normalizedModelId =
|
||||
typeof modelId === "string" && modelId.trim().length > 0 ? modelId : null;
|
||||
return this.runLifecycleMutation(agentId, () =>
|
||||
this.withLiveInteractiveSessionUnlocked(agentId, async (agent) => {
|
||||
const normalizedModelId =
|
||||
typeof modelId === "string" && modelId.trim().length > 0 ? modelId : null;
|
||||
|
||||
const selection = await agent.session.setModel?.(normalizedModelId);
|
||||
await this.drainSessionEvents(agentId);
|
||||
const selection = await agent.session.setModel?.(normalizedModelId);
|
||||
await this.drainSessionEvents(agentId);
|
||||
|
||||
// A reset clears the preference even when the provider retains its active model.
|
||||
let effectiveModelId = normalizedModelId;
|
||||
if (normalizedModelId !== null && selection) effectiveModelId = selection.model;
|
||||
// A reset clears the preference even when the provider retains its active model.
|
||||
let effectiveModelId = normalizedModelId;
|
||||
if (normalizedModelId !== null && selection) effectiveModelId = selection.model;
|
||||
|
||||
agent.config.model = effectiveModelId ?? undefined;
|
||||
if (agent.runtimeInfo) {
|
||||
agent.runtimeInfo = { ...agent.runtimeInfo, model: effectiveModelId };
|
||||
}
|
||||
this.refreshSessionPersistence(agent);
|
||||
this.touchUpdatedAt(agent);
|
||||
this.emitState(agent);
|
||||
});
|
||||
agent.config.model = effectiveModelId ?? undefined;
|
||||
if (agent.runtimeInfo) {
|
||||
agent.runtimeInfo = { ...agent.runtimeInfo, model: effectiveModelId };
|
||||
}
|
||||
this.refreshSessionPersistence(agent);
|
||||
this.touchUpdatedAt(agent);
|
||||
this.emitState(agent);
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
async setAgentThinkingOption(
|
||||
agentId: string,
|
||||
thinkingOptionId: string | null,
|
||||
): Promise<AgentProviderNotice | null> {
|
||||
return this.runLifecycleMutation(agentId, async () => {
|
||||
const agent = await this.ensureInteractiveSessionUnlocked(agentId);
|
||||
const normalizedThinkingOptionId =
|
||||
typeof thinkingOptionId === "string" && thinkingOptionId.trim().length > 0
|
||||
? thinkingOptionId
|
||||
: null;
|
||||
return this.runLifecycleMutation(agentId, () =>
|
||||
this.withLiveInteractiveSessionUnlocked(agentId, async (agent) => {
|
||||
const normalizedThinkingOptionId =
|
||||
typeof thinkingOptionId === "string" && thinkingOptionId.trim().length > 0
|
||||
? thinkingOptionId
|
||||
: null;
|
||||
|
||||
let notice: AgentProviderNotice | null = null;
|
||||
if (agent.session.setThinkingOption) {
|
||||
notice = (await agent.session.setThinkingOption(normalizedThinkingOptionId)) ?? null;
|
||||
}
|
||||
await this.drainSessionEvents(agentId);
|
||||
let notice: AgentProviderNotice | null = null;
|
||||
if (agent.session.setThinkingOption) {
|
||||
notice = (await agent.session.setThinkingOption(normalizedThinkingOptionId)) ?? null;
|
||||
}
|
||||
await this.drainSessionEvents(agentId);
|
||||
|
||||
let effectiveThinkingOptionId = normalizedThinkingOptionId;
|
||||
const runtimeInfo = await agent.session.getRuntimeInfo();
|
||||
if (runtimeInfo.thinkingOptionId !== undefined) {
|
||||
effectiveThinkingOptionId = runtimeInfo.thinkingOptionId;
|
||||
}
|
||||
let effectiveThinkingOptionId = normalizedThinkingOptionId;
|
||||
const runtimeInfo = await agent.session.getRuntimeInfo();
|
||||
if (runtimeInfo.thinkingOptionId !== undefined) {
|
||||
effectiveThinkingOptionId = runtimeInfo.thinkingOptionId;
|
||||
}
|
||||
|
||||
agent.config.thinkingOptionId = effectiveThinkingOptionId ?? undefined;
|
||||
if (agent.runtimeInfo) {
|
||||
agent.runtimeInfo = {
|
||||
...agent.runtimeInfo,
|
||||
thinkingOptionId: effectiveThinkingOptionId,
|
||||
};
|
||||
}
|
||||
this.touchUpdatedAt(agent);
|
||||
this.emitState(agent);
|
||||
return notice;
|
||||
});
|
||||
agent.config.thinkingOptionId = effectiveThinkingOptionId ?? undefined;
|
||||
if (agent.runtimeInfo) {
|
||||
agent.runtimeInfo = {
|
||||
...agent.runtimeInfo,
|
||||
thinkingOptionId: effectiveThinkingOptionId,
|
||||
};
|
||||
}
|
||||
this.touchUpdatedAt(agent);
|
||||
this.emitState(agent);
|
||||
return notice;
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -2546,42 +2550,45 @@ export class AgentManager {
|
||||
* one step once the provider accepts. Patches to one agent run one at a time, in arrival order.
|
||||
*/
|
||||
async setAgentOptions(agentId: string, requested: ProviderOptionsPatch): Promise<void> {
|
||||
return this.runLifecycleMutation(agentId, async () => {
|
||||
const agent = await this.ensureInteractiveSessionUnlocked(agentId);
|
||||
const patch = this.convertLegacyOptions(agent.provider, requested);
|
||||
let ended: ProviderOptionsPatch = {};
|
||||
let sent: ProviderOptionsPatch = {};
|
||||
if (Object.keys(patch).length > 0) {
|
||||
// A provider that cannot apply options to a running agent must not store them either.
|
||||
if (!agent.session.applyOptions) {
|
||||
throw new ProviderOptionsValidationError(
|
||||
agent.provider,
|
||||
Object.keys(patch).map((key) => ({
|
||||
path: [key],
|
||||
message: "cannot change on a running session; it applies when the agent is opened",
|
||||
})),
|
||||
return this.runLifecycleMutation(agentId, () =>
|
||||
this.withLiveInteractiveSessionUnlocked(agentId, async (agent) => {
|
||||
const patch = this.convertLegacyOptions(agent.provider, requested);
|
||||
let ended: ProviderOptionsPatch = {};
|
||||
let sent: ProviderOptionsPatch = {};
|
||||
if (Object.keys(patch).length > 0) {
|
||||
// A provider that cannot apply options to a running agent must not store them either.
|
||||
if (!agent.session.applyOptions) {
|
||||
throw new ProviderOptionsValidationError(
|
||||
agent.provider,
|
||||
Object.keys(patch).map((key) => ({
|
||||
path: [key],
|
||||
message: "cannot change on a running session; it applies when the agent is opened",
|
||||
})),
|
||||
);
|
||||
}
|
||||
const set = Object.fromEntries(
|
||||
Object.entries(patch).filter(([, value]) => value != null),
|
||||
);
|
||||
const resolved = this.effectiveOptionsFor(agent.provider, set);
|
||||
sent = Object.fromEntries(Object.keys(patch).map((key) => [key, resolved[key] ?? null]));
|
||||
const modelBefore = agent.runtimeInfo?.model;
|
||||
ended = (await agent.session.applyOptions(sent)) ?? {};
|
||||
// Changes the provider made on its own while applying are older than its final answer.
|
||||
await this.drainSessionEvents(agentId);
|
||||
await this.refreshRuntimeInfo(agent, { emit: false });
|
||||
// An option can choose the model too, as an fx connection does. Reopening the agent on
|
||||
// the earlier preference would send that model to the new connection.
|
||||
const modelAfter = agent.runtimeInfo?.model;
|
||||
if (agent.config.model && modelAfter && modelAfter !== modelBefore) {
|
||||
agent.config.model = modelAfter;
|
||||
}
|
||||
}
|
||||
const set = Object.fromEntries(Object.entries(patch).filter(([, value]) => value != null));
|
||||
const resolved = this.effectiveOptionsFor(agent.provider, set);
|
||||
sent = Object.fromEntries(Object.keys(patch).map((key) => [key, resolved[key] ?? null]));
|
||||
const modelBefore = agent.runtimeInfo?.model;
|
||||
ended = (await agent.session.applyOptions(sent)) ?? {};
|
||||
// Changes the provider made on its own while applying are older than its final answer.
|
||||
await this.drainSessionEvents(agentId);
|
||||
await this.refreshRuntimeInfo(agent, { emit: false });
|
||||
// An option can choose the model too, as an fx connection does. Reopening the agent on
|
||||
// the earlier preference would send that model to the new connection.
|
||||
const modelAfter = agent.runtimeInfo?.model;
|
||||
if (agent.config.model && modelAfter && modelAfter !== modelBefore) {
|
||||
agent.config.model = modelAfter;
|
||||
}
|
||||
}
|
||||
this.storeOptionsPatch({ agent, patch: { ...patch, ...ended } });
|
||||
this.updateEffectiveOptions({ agent, sent, reported: ended });
|
||||
this.touchUpdatedAt(agent);
|
||||
this.emitState(agent);
|
||||
});
|
||||
this.storeOptionsPatch({ agent, patch: { ...patch, ...ended } });
|
||||
this.updateEffectiveOptions({ agent, sent, reported: ended });
|
||||
this.touchUpdatedAt(agent);
|
||||
this.emitState(agent);
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
/** The config as the opened session left it: its own difference from the options it was given. */
|
||||
@@ -3267,6 +3274,33 @@ export class AgentManager {
|
||||
return this.requireSessionAgent(agentId);
|
||||
}
|
||||
|
||||
/** Inside the agent's lane: transparently reopens a retired plugin session before applying config. */
|
||||
private async withLiveInteractiveSessionUnlocked<T>(
|
||||
agentId: string,
|
||||
operation: (agent: ActiveManagedAgent) => Promise<T>,
|
||||
): Promise<T> {
|
||||
const pendingCancellation = this.pendingCancellations.get(agentId);
|
||||
if (pendingCancellation) {
|
||||
await this.waitWithTimeout({
|
||||
operation: pendingCancellation.then(
|
||||
() => undefined,
|
||||
() => undefined,
|
||||
),
|
||||
timeoutMs: this.rescueTimeouts.interruptSessionMs,
|
||||
});
|
||||
}
|
||||
const agent = await this.ensureInteractiveSessionUnlocked(agentId);
|
||||
try {
|
||||
return await operation(agent);
|
||||
} catch (error) {
|
||||
if (!isStaleProviderSessionError(error)) throw error;
|
||||
await this.runs.getPendingRun(agentId)?.settledPromise.catch(() => undefined);
|
||||
if (this.hasInFlightRun(agentId)) throw error;
|
||||
await this.trackAgentRegistrationOperation(this.reloadAgentSessionInternal(agentId));
|
||||
return await operation(this.requireSessionAgent(agentId));
|
||||
}
|
||||
}
|
||||
|
||||
private async *streamAfterHistoryLoad(
|
||||
agentId: string,
|
||||
prompt: AgentPromptInput,
|
||||
@@ -3925,10 +3959,18 @@ export class AgentManager {
|
||||
}
|
||||
|
||||
async cancelAgentRun(agentId: string): Promise<AgentRunCancellationResult> {
|
||||
return this.runForegroundMutation(agentId, () => {
|
||||
const cancellation = this.runForegroundMutation(agentId, () => {
|
||||
this.requireSessionAgent(agentId).pendingReplacement = false;
|
||||
return this.cancelAgentRunNow(agentId);
|
||||
});
|
||||
this.pendingCancellations.set(agentId, cancellation);
|
||||
try {
|
||||
return await cancellation;
|
||||
} finally {
|
||||
if (this.pendingCancellations.get(agentId) === cancellation) {
|
||||
this.pendingCancellations.delete(agentId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async cancelAgentRunNow(agentId: string): Promise<AgentRunCancellationResult> {
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
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 {
|
||||
@@ -15,13 +16,17 @@ import type {
|
||||
import { writeJsonFileAtomic } from "../../atomic-file.js";
|
||||
|
||||
const DIGEST_WINDOW_MS = 30_000;
|
||||
const watchGroupSchema = z.object({
|
||||
const LEGACY_DEFAULT_FORGE = "github";
|
||||
const LEGACY_INFERENCE_FORGES = ["github", "gitlab"] as const;
|
||||
const persistedWatchGroupSchema = z.object({
|
||||
forge: z.string().min(1).optional(),
|
||||
url: z.url(),
|
||||
snapshot: changeRequestStatusSchema,
|
||||
seenActivity: z.array(z.string()),
|
||||
watchers: z.array(z.object({ agentId: z.string(), startedAt: z.string().optional() })),
|
||||
});
|
||||
type WatchGroup = z.infer<typeof watchGroupSchema>;
|
||||
type PersistedWatchGroup = z.infer<typeof persistedWatchGroupSchema>;
|
||||
type WatchGroup = Omit<PersistedWatchGroup, "forge"> & { forge: string };
|
||||
type Watcher = WatchGroup["watchers"][number];
|
||||
interface DigestWindow {
|
||||
dueAt: number;
|
||||
@@ -35,7 +40,7 @@ interface Observation {
|
||||
release(): void;
|
||||
}
|
||||
interface Dependencies {
|
||||
source: ChangeRequestSource;
|
||||
router: ChangeRequestRouter;
|
||||
paseoHome: string;
|
||||
logger: Logger;
|
||||
isActive(agentId: string): Promise<boolean>;
|
||||
@@ -73,7 +78,7 @@ function describeUpdate(group: WatchGroup, next: ChangeRequestSnapshot) {
|
||||
}
|
||||
for (const activity of next.activity) {
|
||||
if (seen.has(activity.id)) continue;
|
||||
changes.push(`New ${activity.kind}: ${activity.url}`);
|
||||
changes.push(activity.message ?? `New ${activity.kind}: ${activity.url}`);
|
||||
seen.add(activity.id);
|
||||
}
|
||||
if (next.state !== "open") changes.push(`Change request ${next.state}.`);
|
||||
@@ -85,6 +90,7 @@ 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();
|
||||
@@ -156,32 +162,47 @@ export function createChangeRequestWatches(deps: Dependencies) {
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
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;
|
||||
if (!window.recipients.size) {
|
||||
clearTimeout(window.timer);
|
||||
windows.delete(address);
|
||||
windows.delete(url);
|
||||
}
|
||||
}
|
||||
const queued = deps
|
||||
.messages()
|
||||
.withdrawPending(
|
||||
agentId,
|
||||
(source) => source.kind === "change-request-update" && (!url || source.url === url),
|
||||
);
|
||||
return removed || queued > 0;
|
||||
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));
|
||||
}
|
||||
|
||||
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),
|
||||
);
|
||||
await writeJsonFileAtomic(file, [
|
||||
...[...next.values()].filter(({ watchers }) => watchers.length),
|
||||
...unrestored,
|
||||
]);
|
||||
for (const group of updates) {
|
||||
const previous = groups.get(group.url);
|
||||
// An in-flight subscription still needs the committed baseline and its observation.
|
||||
@@ -195,7 +216,20 @@ export function createChangeRequestWatches(deps: Dependencies) {
|
||||
}
|
||||
}
|
||||
|
||||
function syncBackgroundWork({ url, watchers }: WatchGroup, previous: Watcher[] = []): void {
|
||||
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 {
|
||||
if (previous === watchers) return;
|
||||
const current = new Set(watchers);
|
||||
for (const watcher of previous) {
|
||||
@@ -209,7 +243,7 @@ export function createChangeRequestWatches(deps: Dependencies) {
|
||||
deps.backgroundWork.setDaemonBackgroundWork({
|
||||
...backgroundWorkKey(watcher.agentId, url),
|
||||
kind: "monitor",
|
||||
description: deps.source.describe(url),
|
||||
description: describeWatch(forge, url),
|
||||
startedAt: watcher.startedAt ?? new Date().toISOString(),
|
||||
stop: async () => {
|
||||
await unsubscribe(watcher.agentId, url, watcher);
|
||||
@@ -218,9 +252,13 @@ export function createChangeRequestWatches(deps: Dependencies) {
|
||||
}
|
||||
}
|
||||
|
||||
function observe(url: string): Observation {
|
||||
function observe(forge: string, 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) => {
|
||||
@@ -228,7 +266,7 @@ export function createChangeRequestWatches(deps: Dependencies) {
|
||||
reject = fail;
|
||||
});
|
||||
void ready.catch(() => undefined);
|
||||
const release = deps.source.observe(url, {
|
||||
const release = source.observe(url, {
|
||||
knownActivity: () => new Set(groups.get(url)?.seenActivity),
|
||||
snapshot: (snapshot) =>
|
||||
serialize(async () => {
|
||||
@@ -266,14 +304,14 @@ export function createChangeRequestWatches(deps: Dependencies) {
|
||||
}),
|
||||
error(error) {
|
||||
if (!observation.stale) {
|
||||
deps.logger.warn({ err: error, url }, "Change request observation became stale");
|
||||
deps.logger.warn({ err: error, url, forge }, "Change request observation became stale");
|
||||
}
|
||||
observation.stale = true;
|
||||
if (!groups.has(url)) {
|
||||
reject(error);
|
||||
stopObserving(url);
|
||||
}
|
||||
deps.logger.debug({ err: error, url }, "Change request observation failed");
|
||||
deps.logger.debug({ err: error, url, forge }, "Change request observation failed");
|
||||
},
|
||||
});
|
||||
const observation: Observation = {
|
||||
@@ -288,16 +326,62 @@ export function createChangeRequestWatches(deps: Dependencies) {
|
||||
return observation;
|
||||
}
|
||||
|
||||
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 });
|
||||
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) {
|
||||
registrations.set(url, (registrations.get(url) ?? 0) + 1);
|
||||
try {
|
||||
const existing = groups.get(url);
|
||||
const initial = existing ? { ...existing.snapshot, activity: [] } : await observe(url).ready;
|
||||
return await serialize(async () => {
|
||||
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 () => {
|
||||
if (closed || !(await deps.isActive(agentId))) throw new Error("Agent is no longer active");
|
||||
const group = groups.get(url);
|
||||
const { activity, ...initialStatus } = initial;
|
||||
@@ -305,6 +389,7 @@ 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),
|
||||
@@ -322,21 +407,13 @@ export function createChangeRequestWatches(deps: Dependencies) {
|
||||
checks: snapshot.checks,
|
||||
reviewDecision: snapshot.reviewDecision,
|
||||
subscribed,
|
||||
stale: observations.get(url)?.stale ?? false,
|
||||
stale: observations.get(url)?.stale ?? Boolean(existing),
|
||||
};
|
||||
});
|
||||
} 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
const pending = existing
|
||||
? commitSubscription({ ...existing.snapshot, activity: [] })
|
||||
: observe(forge, url).ready.then(commitSubscription);
|
||||
return pending.finally(finish);
|
||||
}
|
||||
|
||||
function removeWatcher(group: WatchGroup, agentId: string): Promise<void> {
|
||||
@@ -355,15 +432,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, url);
|
||||
return { url, removed: Boolean(watcher) || withdrawn };
|
||||
const withdrawn = withdraw(agentId, (address) => address === url);
|
||||
return { url, removed: Boolean(watcher || withdrawn) };
|
||||
});
|
||||
}
|
||||
|
||||
function archive(agentId: string): Promise<void> {
|
||||
return serialize(async () => {
|
||||
if (closed) return;
|
||||
withdraw(agentId);
|
||||
withdraw(agentId, () => true);
|
||||
const updates: WatchGroup[] = [];
|
||||
for (const group of groups.values()) {
|
||||
const watchers = group.watchers.filter((watcher) => watcher.agentId !== agentId);
|
||||
@@ -373,6 +450,20 @@ 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[] = [];
|
||||
@@ -382,8 +473,12 @@ export function createChangeRequestWatches(deps: Dependencies) {
|
||||
if (error.code === "ENOENT") return "[]";
|
||||
throw error;
|
||||
});
|
||||
const restored = z.array(watchGroupSchema).parse(JSON.parse(stored));
|
||||
for (const group of restored) {
|
||||
const restored = z.array(persistedWatchGroupSchema).parse(JSON.parse(stored));
|
||||
for (const record of restored) {
|
||||
const group: WatchGroup = {
|
||||
...record,
|
||||
forge: record.forge ?? inferLegacyForge(record.url),
|
||||
};
|
||||
if (group.snapshot.state !== "open") {
|
||||
pruned = true;
|
||||
continue;
|
||||
@@ -393,7 +488,17 @@ export function createChangeRequestWatches(deps: Dependencies) {
|
||||
if (await deps.isActive(watcher.agentId)) watchers.push(watcher);
|
||||
}
|
||||
pruned ||= watchers.length !== group.watchers.length;
|
||||
if (watchers.length) active.push({ ...group, watchers });
|
||||
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);
|
||||
}
|
||||
} catch (error) {
|
||||
recoveryError = error;
|
||||
@@ -402,7 +507,7 @@ export function createChangeRequestWatches(deps: Dependencies) {
|
||||
}
|
||||
if (pruned) {
|
||||
try {
|
||||
await writeJsonFileAtomic(file, active);
|
||||
await writeJsonFileAtomic(file, [...active, ...unrestored]);
|
||||
} catch (error) {
|
||||
deps.logger.warn({ err: error, file }, "Could not prune archived change request watches");
|
||||
}
|
||||
@@ -410,12 +515,24 @@ export function createChangeRequestWatches(deps: Dependencies) {
|
||||
for (const group of active) {
|
||||
groups.set(group.url, group);
|
||||
syncBackgroundWork(group);
|
||||
observe(group.url);
|
||||
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",
|
||||
);
|
||||
}
|
||||
}
|
||||
},
|
||||
subscribe,
|
||||
unsubscribe(agentId: string, input: string) {
|
||||
return unsubscribe(agentId, deps.source.resolve(input));
|
||||
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);
|
||||
},
|
||||
archive,
|
||||
async close() {
|
||||
|
||||
@@ -1,16 +1,18 @@
|
||||
import { mkdir, mkdtemp, readFile, rename, rm } from "node:fs/promises";
|
||||
import { mkdir, mkdtemp, readFile, rename, rm, writeFile } 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",
|
||||
@@ -31,13 +33,19 @@ async function createTestHome() {
|
||||
|
||||
function createHarness(
|
||||
home: string,
|
||||
{ isActive = async (_id: string) => true, observationFails = false } = {},
|
||||
{
|
||||
isActive = async (_id: string) => true,
|
||||
observationFails = false,
|
||||
resolveFails = false,
|
||||
extraSources = {} as Record<string, ChangeRequestSource>,
|
||||
} = {},
|
||||
) {
|
||||
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) {
|
||||
@@ -52,10 +60,16 @@ function createHarness(
|
||||
throw error;
|
||||
},
|
||||
});
|
||||
const watches = createChangeRequestWatches({
|
||||
source: {
|
||||
resolve: (input) => input,
|
||||
describe: () => "owner/repo #42",
|
||||
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,
|
||||
observe(address, callbacks) {
|
||||
observations.set(address, callbacks);
|
||||
queueMicrotask(() => {
|
||||
@@ -64,7 +78,34 @@ 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,
|
||||
@@ -78,6 +119,7 @@ function createHarness(
|
||||
messages,
|
||||
watches,
|
||||
backgroundWork,
|
||||
resolveCalls,
|
||||
idle(id: string) {
|
||||
busy.delete(id);
|
||||
for (const listener of listeners) listener(id);
|
||||
@@ -255,6 +297,47 @@ 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);
|
||||
@@ -343,3 +426,119 @@ 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 });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -6,6 +6,7 @@ import { createIdleRuntimeCleanup } from "./idle-runtime-cleanup/index.js";
|
||||
import { relative } from "node:path";
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { runAcpProvider, type AcpStreamMessage } from "@getpaseo/plugin/server/acp";
|
||||
import type {
|
||||
ProviderConnection,
|
||||
ProviderLaunch,
|
||||
@@ -13,6 +14,7 @@ import type {
|
||||
ProviderInput,
|
||||
ProviderRegistration,
|
||||
} from "@getpaseo/plugin/server/provider";
|
||||
import { sendPreparedPromptToAgent } from "./agent-prompt.js";
|
||||
import { setImmediate as nextTurn } from "node:timers/promises";
|
||||
import { describe, expect, test } from "vitest";
|
||||
import { createTestLogger } from "../../test-utils/test-logger.js";
|
||||
@@ -2814,3 +2816,592 @@ test("resumes a goose session saved by the generic ACP provider", async () => {
|
||||
await plugins.shutdown();
|
||||
}
|
||||
});
|
||||
|
||||
test("preserves a deferred ACP background job on steer and cancels it on explicit Stop through AgentManager", async () => {
|
||||
const logger = createTestLogger();
|
||||
const home = await mkdtemp(join(tmpdir(), "paseo-acp-deferred-daemon-"));
|
||||
const storage = new AgentStorage(join(home, "agents"), logger);
|
||||
let cancelCount = 0;
|
||||
let promptCount = 0;
|
||||
let currentMode = "default";
|
||||
let notifyAgent: ((message: AcpStreamMessage) => void) | null = null;
|
||||
let holdNextPrompt: ((release: () => void) => void) | null = null;
|
||||
const modeConfig = () => [
|
||||
{
|
||||
id: "mode",
|
||||
name: "Mode",
|
||||
category: "mode",
|
||||
type: "select",
|
||||
currentValue: currentMode,
|
||||
options: [
|
||||
{ value: "default", name: "Default" },
|
||||
{ value: "plan", name: "Plan" },
|
||||
],
|
||||
},
|
||||
];
|
||||
const registration = runAcpProvider({
|
||||
id: "deferred-acp-daemon",
|
||||
label: "Deferred ACP Daemon",
|
||||
acpOptions: {
|
||||
deferTurnOnRunningTools: { settleDelayMs: 25, quietLimitMs: 1_000 },
|
||||
},
|
||||
connector() {
|
||||
let controller!: ReadableStreamDefaultController<AcpStreamMessage>;
|
||||
const readable = new ReadableStream<AcpStreamMessage>({
|
||||
start(ctrl) {
|
||||
controller = ctrl;
|
||||
},
|
||||
});
|
||||
const send = (message: AcpStreamMessage) => controller.enqueue(message);
|
||||
notifyAgent = send;
|
||||
const writable = new WritableStream<AcpStreamMessage>({
|
||||
write(message) {
|
||||
if (!("method" in message)) return;
|
||||
if (message.method === "session/cancel") {
|
||||
cancelCount += 1;
|
||||
return;
|
||||
}
|
||||
if (!("id" in message)) return;
|
||||
if (message.method === "initialize") {
|
||||
send({
|
||||
jsonrpc: "2.0",
|
||||
id: message.id,
|
||||
result: { protocolVersion: 1, agentCapabilities: { loadSession: true } },
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (message.method === "session/new") {
|
||||
send({
|
||||
jsonrpc: "2.0",
|
||||
id: message.id,
|
||||
result: { sessionId: "acp-s1", configOptions: modeConfig() },
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (message.method === "session/load") {
|
||||
send({ jsonrpc: "2.0", id: message.id, result: { configOptions: modeConfig() } });
|
||||
return;
|
||||
}
|
||||
if (message.method === "session/set_config_option") {
|
||||
const params = message.params as { value?: string } | undefined;
|
||||
if (typeof params?.value === "string") currentMode = params.value;
|
||||
send({ jsonrpc: "2.0", id: message.id, result: { configOptions: modeConfig() } });
|
||||
return;
|
||||
}
|
||||
if (message.method === "session/prompt") {
|
||||
promptCount += 1;
|
||||
if (promptCount === 1) {
|
||||
send({
|
||||
jsonrpc: "2.0",
|
||||
method: "session/update",
|
||||
params: {
|
||||
sessionId: "acp-s1",
|
||||
update: {
|
||||
sessionUpdate: "tool_call",
|
||||
toolCallId: "bg-job-1",
|
||||
name: "run_command",
|
||||
title: "Background job",
|
||||
status: "in_progress",
|
||||
},
|
||||
},
|
||||
});
|
||||
} else if (promptCount === 2) {
|
||||
send({
|
||||
jsonrpc: "2.0",
|
||||
method: "session/update",
|
||||
params: {
|
||||
sessionId: "acp-s1",
|
||||
update: {
|
||||
sessionUpdate: "agent_message_chunk",
|
||||
content: { type: "text", text: "Steered reply" },
|
||||
},
|
||||
},
|
||||
});
|
||||
} else {
|
||||
send({
|
||||
jsonrpc: "2.0",
|
||||
method: "session/update",
|
||||
params: {
|
||||
sessionId: "acp-s1",
|
||||
update: {
|
||||
sessionUpdate: "tool_call",
|
||||
toolCallId: "bg-job-2",
|
||||
name: "run_command",
|
||||
title: "Cancelable job",
|
||||
status: "in_progress",
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
if (holdNextPrompt) {
|
||||
const hook = holdNextPrompt;
|
||||
holdNextPrompt = null;
|
||||
hook(() =>
|
||||
send({ jsonrpc: "2.0", id: message.id, result: { stopReason: "cancelled" } }),
|
||||
);
|
||||
return;
|
||||
}
|
||||
send({ jsonrpc: "2.0", id: message.id, result: { stopReason: "end_turn" } });
|
||||
return;
|
||||
}
|
||||
if (message.method === "session/close") {
|
||||
send({ jsonrpc: "2.0", id: message.id, result: {} });
|
||||
}
|
||||
},
|
||||
});
|
||||
return { readable, writable };
|
||||
},
|
||||
});
|
||||
const plugins = new PluginAgentClientRegistry(logger);
|
||||
plugins.replace([registration]);
|
||||
const manager = new AgentManager({ clients: plugins.clients(), registry: storage, logger });
|
||||
try {
|
||||
const agent = await manager.createAgent({ provider: registration.id, cwd: home }, undefined, {
|
||||
workspaceId: undefined,
|
||||
});
|
||||
const first = await sendPreparedPromptToAgent({
|
||||
agentManager: manager,
|
||||
agentStorage: storage,
|
||||
agentId: agent.id,
|
||||
prompt: "start background job",
|
||||
logger,
|
||||
});
|
||||
expect(first.disposition).toBe("turn_started");
|
||||
if (first.disposition === "turn_started") await first.started;
|
||||
await new Promise((resolve) => setTimeout(resolve, 40));
|
||||
expect(manager.getAgent(agent.id)?.lifecycle).toBe("running");
|
||||
|
||||
// Follow-up steer through AgentManager preserves the background job without session/cancel.
|
||||
const followUp = await sendPreparedPromptToAgent({
|
||||
agentManager: manager,
|
||||
agentStorage: storage,
|
||||
agentId: agent.id,
|
||||
prompt: "still working?",
|
||||
activeTurnBehavior: "steer",
|
||||
logger,
|
||||
});
|
||||
expect(followUp.disposition).toBe("steered");
|
||||
expect(cancelCount).toBe(0);
|
||||
await new Promise((resolve) => setTimeout(resolve, 40));
|
||||
expect(manager.getAgent(agent.id)?.lifecycle).toBe("running");
|
||||
|
||||
// Completing the job + reply + usage_update settles the turn cleanly.
|
||||
notifyAgent!({
|
||||
jsonrpc: "2.0",
|
||||
method: "session/update",
|
||||
params: {
|
||||
sessionId: "acp-s1",
|
||||
update: { sessionUpdate: "tool_call_update", toolCallId: "bg-job-1", status: "completed" },
|
||||
},
|
||||
});
|
||||
notifyAgent!({
|
||||
jsonrpc: "2.0",
|
||||
method: "session/update",
|
||||
params: {
|
||||
sessionId: "acp-s1",
|
||||
update: {
|
||||
sessionUpdate: "agent_message_chunk",
|
||||
content: { type: "text", text: "Background job finished." },
|
||||
},
|
||||
},
|
||||
});
|
||||
notifyAgent!({
|
||||
jsonrpc: "2.0",
|
||||
method: "session/update",
|
||||
params: {
|
||||
sessionId: "acp-s1",
|
||||
update: { sessionUpdate: "usage_update", used: 120, size: 1000 },
|
||||
},
|
||||
});
|
||||
await expect.poll(() => manager.getAgent(agent.id)?.lifecycle, { timeout: 3_000 }).toBe("idle");
|
||||
expect(cancelCount).toBe(0);
|
||||
|
||||
// Start a second deferred job, send two steers while steer 1 waits on ACP, and press Stop.
|
||||
let heldSteerResponse: (() => void) | null = null;
|
||||
const second = await sendPreparedPromptToAgent({
|
||||
agentManager: manager,
|
||||
agentStorage: storage,
|
||||
agentId: agent.id,
|
||||
prompt: "start cancelable job",
|
||||
logger,
|
||||
});
|
||||
if (second.disposition === "turn_started") await second.started;
|
||||
await new Promise((resolve) => setTimeout(resolve, 40));
|
||||
expect(manager.getAgent(agent.id)?.lifecycle).toBe("running");
|
||||
|
||||
// Hold the next steer prompt so Stop races with a queued second steer.
|
||||
holdNextPrompt = (release) => {
|
||||
heldSteerResponse = release;
|
||||
};
|
||||
const steerOne = await sendPreparedPromptToAgent({
|
||||
agentManager: manager,
|
||||
agentStorage: storage,
|
||||
agentId: agent.id,
|
||||
prompt: "held steer 1",
|
||||
activeTurnBehavior: "steer",
|
||||
logger,
|
||||
});
|
||||
expect(steerOne.disposition).toBe("steered");
|
||||
const steerTwo = await sendPreparedPromptToAgent({
|
||||
agentManager: manager,
|
||||
agentStorage: storage,
|
||||
agentId: agent.id,
|
||||
prompt: "queued steer 2",
|
||||
activeTurnBehavior: "steer",
|
||||
logger,
|
||||
});
|
||||
expect(steerTwo.disposition).toBe("steered");
|
||||
await expect.poll(() => heldSteerResponse).not.toBeNull();
|
||||
const promptsBeforeStop = promptCount;
|
||||
|
||||
// Stop must send session/cancel immediately, retire the deferred session cleanly,
|
||||
// and never dispatch the queued steer 2 to ACP.
|
||||
await manager.cancelAgentRun(agent.id);
|
||||
expect(cancelCount).toBe(1);
|
||||
await expect.poll(() => manager.getAgent(agent.id)?.lifecycle, { timeout: 3_000 }).toBe("idle");
|
||||
expect(promptCount).toBe(promptsBeforeStop);
|
||||
|
||||
// Changing mode immediately after stopping a deferred turn must transparently reopen the session.
|
||||
await manager.setAgentMode(agent.id, "plan");
|
||||
expect(manager.getAgent(agent.id)?.currentModeId).toBe("plan");
|
||||
expect(currentMode).toBe("plan");
|
||||
} finally {
|
||||
await Promise.all(manager.listAgents().map((item) => manager.closeAgent(item.id)));
|
||||
await plugins.shutdown();
|
||||
await storage.flush();
|
||||
await rm(home, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("reopens cleanly for mode changes and follow-up sends initiated while Stop is closing a slow ACP process", async () => {
|
||||
const logger = createTestLogger();
|
||||
const home = await mkdtemp(join(tmpdir(), "paseo-acp-slow-stop-"));
|
||||
const storage = new AgentStorage(join(home, "agents"), logger);
|
||||
const script = join(home, "slow-stop-agent.cjs");
|
||||
const { writeFile } = await import("node:fs/promises");
|
||||
await writeFile(
|
||||
script,
|
||||
`
|
||||
const { createInterface } = require("node:readline");
|
||||
const send = (msg) => process.stdout.write(JSON.stringify({ jsonrpc: "2.0", ...msg }) + "\\n");
|
||||
let mode = "default";
|
||||
const configOptions = () => [{
|
||||
id: "mode", name: "Mode", category: "mode", type: "select", currentValue: mode,
|
||||
options: [{ value: "default", name: "Default" }, { value: "plan", name: "Plan" }],
|
||||
}];
|
||||
process.on("SIGTERM", () => {
|
||||
setTimeout(() => process.exit(0), 250);
|
||||
});
|
||||
createInterface({ input: process.stdin }).on("line", (line) => {
|
||||
const msg = JSON.parse(line);
|
||||
if (msg.method === "initialize") {
|
||||
send({ id: msg.id, result: { protocolVersion: 1, agentCapabilities: { loadSession: true } } });
|
||||
} else if (msg.method === "session/new") {
|
||||
send({ id: msg.id, result: { sessionId: "slow-s1", configOptions: configOptions() } });
|
||||
} else if (msg.method === "session/load") {
|
||||
send({ id: msg.id, result: { configOptions: configOptions() } });
|
||||
} else if (msg.method === "session/set_config_option") {
|
||||
if (msg.params && typeof msg.params.value === "string") mode = msg.params.value;
|
||||
send({ id: msg.id, result: { configOptions: configOptions() } });
|
||||
} else if (msg.method === "session/prompt") {
|
||||
const text = msg.params?.prompt?.[0]?.text ?? "";
|
||||
if (text.includes("start bg")) {
|
||||
send({ method: "session/update", params: { sessionId: "slow-s1", update: {
|
||||
sessionUpdate: "tool_call", toolCallId: "slow-bg-1", name: "run_command",
|
||||
title: "Slow bg job", status: "in_progress",
|
||||
} } });
|
||||
} else {
|
||||
send({ method: "session/update", params: { sessionId: "slow-s1", update: {
|
||||
sessionUpdate: "agent_message_chunk", content: { type: "text", text: "After stop reply" },
|
||||
} } });
|
||||
}
|
||||
send({ id: msg.id, result: { stopReason: "end_turn" } });
|
||||
} else if (msg.method === "session/close") {
|
||||
send({ id: msg.id, result: {} });
|
||||
}
|
||||
});
|
||||
`,
|
||||
);
|
||||
const registration = runAcpProvider({
|
||||
id: "slow-stop-acp",
|
||||
label: "Slow Stop ACP",
|
||||
command: [process.execPath, script],
|
||||
acpOptions: {
|
||||
deferTurnOnRunningTools: { settleDelayMs: 25, quietLimitMs: 1_000 },
|
||||
},
|
||||
});
|
||||
const plugins = new PluginAgentClientRegistry(logger);
|
||||
plugins.replace([registration]);
|
||||
const manager = new AgentManager({ clients: plugins.clients(), registry: storage, logger });
|
||||
try {
|
||||
const agent = await manager.createAgent({ provider: registration.id, cwd: home }, undefined, {
|
||||
workspaceId: undefined,
|
||||
});
|
||||
const first = await sendPreparedPromptToAgent({
|
||||
agentManager: manager,
|
||||
agentStorage: storage,
|
||||
agentId: agent.id,
|
||||
prompt: "start bg",
|
||||
logger,
|
||||
});
|
||||
if (first.disposition === "turn_started") await first.started;
|
||||
await new Promise((resolve) => setTimeout(resolve, 40));
|
||||
expect(manager.getAgent(agent.id)?.lifecycle).toBe("running");
|
||||
|
||||
// Start Stop (takes 250ms to terminate the child on SIGTERM) and trigger a mode change mid-shutdown.
|
||||
const stopPromise = manager.cancelAgentRun(agent.id);
|
||||
await new Promise((resolve) => setTimeout(resolve, 50));
|
||||
const modePromise = manager.setAgentMode(agent.id, "plan");
|
||||
await Promise.all([stopPromise, modePromise]);
|
||||
expect(manager.getAgent(agent.id)?.currentModeId).toBe("plan");
|
||||
expect(manager.getAgent(agent.id)?.lifecycle).toBe("idle");
|
||||
|
||||
// A follow-up prompt immediately after Stop + mode change succeeds cleanly.
|
||||
const next = await sendPreparedPromptToAgent({
|
||||
agentManager: manager,
|
||||
agentStorage: storage,
|
||||
agentId: agent.id,
|
||||
prompt: "fresh prompt",
|
||||
logger,
|
||||
});
|
||||
expect(next.disposition).toBe("turn_started");
|
||||
if (next.disposition === "turn_started") await next.started;
|
||||
await expect.poll(() => manager.getAgent(agent.id)?.lifecycle, { timeout: 3_000 }).toBe("idle");
|
||||
} finally {
|
||||
await Promise.all(manager.listAgents().map((item) => manager.closeAgent(item.id)));
|
||||
await plugins.shutdown();
|
||||
await storage.flush();
|
||||
await rm(home, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("does not block mode changes after a plugin refuses Stop by ignoring session.interrupt", async () => {
|
||||
const logger = createTestLogger();
|
||||
let currentMode = "code";
|
||||
const harness = createProviderHarness({
|
||||
async handleInput(input, emit) {
|
||||
if (input.type === "session.open") {
|
||||
emit({
|
||||
type: "session.opened",
|
||||
requestId: input.requestId,
|
||||
sessionId: input.sessionId,
|
||||
capabilities: ["prompt.message", "session.interrupt", "session.configure"],
|
||||
restoration: "core",
|
||||
title: input.config.title,
|
||||
cwd: input.config.cwd,
|
||||
});
|
||||
emit({
|
||||
type: "session.config",
|
||||
sessionId: input.sessionId,
|
||||
config: {
|
||||
mode: currentMode,
|
||||
modes: [
|
||||
{ id: "code", label: "Code" },
|
||||
{ id: "plan", label: "Plan" },
|
||||
],
|
||||
models: [],
|
||||
thinkingOptions: [],
|
||||
},
|
||||
});
|
||||
emit({ type: "session.ready", requestId: input.requestId, sessionId: input.sessionId });
|
||||
return true;
|
||||
}
|
||||
if (input.type === "session.prompt") {
|
||||
emit({
|
||||
type: "session.prompt_result",
|
||||
sessionId: input.sessionId,
|
||||
clientMessageId: input.prompt.clientMessageId,
|
||||
result: { type: "turn", turnId: "hung-turn" },
|
||||
});
|
||||
emit({
|
||||
type: "session.turn",
|
||||
sessionId: input.sessionId,
|
||||
turnId: "hung-turn",
|
||||
state: "started",
|
||||
});
|
||||
return true;
|
||||
}
|
||||
if (input.type === "session.interrupt") {
|
||||
// Intentionally never acknowledge session.interrupt.
|
||||
return true;
|
||||
}
|
||||
if (input.type === "session.configure") {
|
||||
if (input.changes.mode) currentMode = input.changes.mode;
|
||||
emit({
|
||||
type: "session.config",
|
||||
sessionId: input.sessionId,
|
||||
config: {
|
||||
mode: currentMode,
|
||||
modes: [
|
||||
{ id: "code", label: "Code" },
|
||||
{ id: "plan", label: "Plan" },
|
||||
],
|
||||
models: [],
|
||||
thinkingOptions: [],
|
||||
},
|
||||
});
|
||||
emit({ type: "request.completed", requestId: input.requestId });
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
},
|
||||
});
|
||||
const plugins = new PluginAgentClientRegistry(logger);
|
||||
plugins.replace([harness.registration]);
|
||||
const registry = buildProviderRegistry(logger, { pluginProviders: plugins.definitions() });
|
||||
const manager = new AgentManager({
|
||||
logger,
|
||||
clients: { "plugin-direct": registry["plugin-direct"].createClient(logger) },
|
||||
providerDefinitions: { "plugin-direct": registry["plugin-direct"] },
|
||||
rescueTimeouts: { interruptSessionMs: 50 },
|
||||
});
|
||||
try {
|
||||
const agent = await manager.createAgent(
|
||||
{ provider: "plugin-direct", cwd: tmpdir() },
|
||||
undefined,
|
||||
{ workspaceId: undefined },
|
||||
);
|
||||
const stream = manager.streamAgent(agent.id, "start");
|
||||
void stream.next();
|
||||
await expect
|
||||
.poll(() => manager.getAgent(agent.id)?.lifecycle, { timeout: 2_000 })
|
||||
.toBe("running");
|
||||
|
||||
const cancelResult = await manager.cancelAgentRun(agent.id);
|
||||
expect(cancelResult.status).toBe("refused");
|
||||
|
||||
// Settings change must not hang behind the unacknowledged session.interrupt.
|
||||
await manager.setAgentMode(agent.id, "plan");
|
||||
expect(manager.getAgent(agent.id)?.currentModeId).toBe("plan");
|
||||
} finally {
|
||||
await Promise.all(manager.listAgents().map((item) => manager.closeAgent(item.id)));
|
||||
await plugins.shutdown();
|
||||
}
|
||||
});
|
||||
|
||||
test("bounds settings wait when Stop is queued behind an unanswered steer", async () => {
|
||||
const logger = createTestLogger();
|
||||
let currentMode = "code";
|
||||
let releaseSteer: (() => void) | null = null;
|
||||
const harness = createProviderHarness({
|
||||
capabilities: ["prompt.message", "prompt.steer", "session.interrupt", "session.configure"],
|
||||
async handleInput(input, emit) {
|
||||
if (input.type === "session.open") {
|
||||
emit({
|
||||
type: "session.opened",
|
||||
requestId: input.requestId,
|
||||
sessionId: input.sessionId,
|
||||
capabilities: [
|
||||
"prompt.message",
|
||||
"prompt.steer",
|
||||
"session.interrupt",
|
||||
"session.configure",
|
||||
],
|
||||
restoration: "core",
|
||||
title: input.config.title,
|
||||
cwd: input.config.cwd,
|
||||
});
|
||||
emit({
|
||||
type: "session.config",
|
||||
sessionId: input.sessionId,
|
||||
config: {
|
||||
mode: currentMode,
|
||||
modes: [
|
||||
{ id: "code", label: "Code" },
|
||||
{ id: "plan", label: "Plan" },
|
||||
],
|
||||
models: [],
|
||||
thinkingOptions: [],
|
||||
},
|
||||
});
|
||||
emit({ type: "session.ready", requestId: input.requestId, sessionId: input.sessionId });
|
||||
return true;
|
||||
}
|
||||
if (input.type === "session.prompt") {
|
||||
if (input.prompt.delivery === "steer") {
|
||||
releaseSteer = () =>
|
||||
emit({
|
||||
type: "session.prompt_result",
|
||||
sessionId: input.sessionId,
|
||||
clientMessageId: input.prompt.clientMessageId,
|
||||
result: { type: "steer", turnId: "steer-turn" },
|
||||
});
|
||||
return true;
|
||||
}
|
||||
emit({
|
||||
type: "session.prompt_result",
|
||||
sessionId: input.sessionId,
|
||||
clientMessageId: input.prompt.clientMessageId,
|
||||
result: { type: "turn", turnId: "steer-turn" },
|
||||
});
|
||||
emit({
|
||||
type: "session.turn",
|
||||
sessionId: input.sessionId,
|
||||
turnId: "steer-turn",
|
||||
state: "started",
|
||||
});
|
||||
return true;
|
||||
}
|
||||
if (input.type === "session.interrupt") {
|
||||
return true;
|
||||
}
|
||||
if (input.type === "session.configure") {
|
||||
if (input.changes.mode) currentMode = input.changes.mode;
|
||||
emit({
|
||||
type: "session.config",
|
||||
sessionId: input.sessionId,
|
||||
config: {
|
||||
mode: currentMode,
|
||||
modes: [
|
||||
{ id: "code", label: "Code" },
|
||||
{ id: "plan", label: "Plan" },
|
||||
],
|
||||
models: [],
|
||||
thinkingOptions: [],
|
||||
},
|
||||
});
|
||||
emit({ type: "request.completed", requestId: input.requestId });
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
},
|
||||
});
|
||||
const plugins = new PluginAgentClientRegistry(logger);
|
||||
plugins.replace([harness.registration]);
|
||||
const registry = buildProviderRegistry(logger, { pluginProviders: plugins.definitions() });
|
||||
const manager = new AgentManager({
|
||||
logger,
|
||||
clients: { "plugin-direct": registry["plugin-direct"].createClient(logger) },
|
||||
providerDefinitions: { "plugin-direct": registry["plugin-direct"] },
|
||||
rescueTimeouts: { interruptSessionMs: 50 },
|
||||
});
|
||||
try {
|
||||
const agent = await manager.createAgent(
|
||||
{ provider: "plugin-direct", cwd: tmpdir() },
|
||||
undefined,
|
||||
{ workspaceId: undefined },
|
||||
);
|
||||
const stream = manager.streamAgent(agent.id, "start");
|
||||
void stream.next();
|
||||
await expect
|
||||
.poll(() => manager.getAgent(agent.id)?.lifecycle, { timeout: 2_000 })
|
||||
.toBe("running");
|
||||
|
||||
// Start an unanswered steer, queue Stop behind it, then change mode.
|
||||
const steerPromise = manager.steerAgentRun(agent.id, "unanswered steer").catch(() => undefined);
|
||||
await new Promise((resolve) => setTimeout(resolve, 20));
|
||||
const stopPromise = manager.cancelAgentRun(agent.id);
|
||||
await new Promise((resolve) => setTimeout(resolve, 10));
|
||||
|
||||
// Mode change must complete within the bounded interrupt timeout even while Stop is queued.
|
||||
await manager.setAgentMode(agent.id, "plan");
|
||||
expect(manager.getAgent(agent.id)?.currentModeId).toBe("plan");
|
||||
|
||||
releaseSteer?.();
|
||||
await Promise.all([steerPromise, stopPromise]);
|
||||
} finally {
|
||||
releaseSteer?.();
|
||||
await Promise.all(manager.listAgents().map((item) => manager.closeAgent(item.id)));
|
||||
await plugins.shutdown();
|
||||
}
|
||||
});
|
||||
|
||||
@@ -739,6 +739,7 @@ class ProviderRuntimeSession {
|
||||
}
|
||||
|
||||
async configure(changes: ProviderConfigChanges): Promise<void> {
|
||||
if (this.terminal) throw new StaleProviderSessionError(this.id);
|
||||
const input: Extract<ProviderInput, { type: "session.configure" }> = {
|
||||
type: "session.configure",
|
||||
requestId: randomUUID(),
|
||||
|
||||
@@ -99,6 +99,74 @@ describe("ClaudeAgentSession persisted history load", () => {
|
||||
rmSync(tempRoot, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
test("resumes many records within a chunk-sized event-loop turn budget", async () => {
|
||||
const count = 3_072;
|
||||
const text = "🙂".repeat(128);
|
||||
const entries = Array.from({ length: count }, (_, index) =>
|
||||
JSON.stringify({ type: "assistant", message: { content: `${index}:${text}` } }),
|
||||
);
|
||||
entries.splice(count / 2, 0, JSON.stringify({ type: "system", subtype: "compact_boundary" }));
|
||||
mkdirSync(path.dirname(transcriptPath()), { recursive: true });
|
||||
writeFileSync(transcriptPath(), entries.join("\n"));
|
||||
|
||||
let turns = 0;
|
||||
let ticker: NodeJS.Immediate;
|
||||
function tick() {
|
||||
turns++;
|
||||
const deadline = performance.now() + 2;
|
||||
while (performance.now() < deadline) {}
|
||||
ticker = setImmediate(tick);
|
||||
}
|
||||
ticker = setImmediate(tick);
|
||||
|
||||
const session = await resume().finally(() => clearImmediate(ticker));
|
||||
|
||||
try {
|
||||
const messages = [];
|
||||
for await (const event of session.streamHistory()) {
|
||||
if (event.type === "timeline" && event.item.type === "assistant_message") {
|
||||
messages.push(event.item.text);
|
||||
}
|
||||
}
|
||||
expect(messages).toEqual(Array.from({ length: count }, (_, index) => `${index}:${text}`));
|
||||
expect(turns).toBeLessThan(count);
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
}, 30_000);
|
||||
|
||||
test("yields during replay of a dense window with an expensive consumer", async () => {
|
||||
const file = transcriptPath();
|
||||
const count = 500;
|
||||
const record = JSON.stringify({ type: "assistant", message: { content: "saved reply" } });
|
||||
mkdirSync(path.dirname(file), { recursive: true });
|
||||
writeFileSync(file, (record + "\n").repeat(count));
|
||||
|
||||
await withClaudeReplayHistory(file, async (history) => {
|
||||
let turns = 0;
|
||||
let ticker: NodeJS.Immediate | undefined;
|
||||
function tick() {
|
||||
turns++;
|
||||
ticker = setImmediate(tick);
|
||||
}
|
||||
|
||||
let entries = 0;
|
||||
try {
|
||||
for await (const _entry of history.parentEntries) {
|
||||
// Start counting after the read so only yields within the window count.
|
||||
ticker ??= setImmediate(tick);
|
||||
const deadline = performance.now() + 1;
|
||||
while (performance.now() < deadline) {}
|
||||
entries++;
|
||||
}
|
||||
} finally {
|
||||
if (ticker) clearImmediate(ticker);
|
||||
}
|
||||
expect(entries).toBe(count);
|
||||
expect(turns).toBeGreaterThanOrEqual(20);
|
||||
});
|
||||
});
|
||||
|
||||
test("serves unrelated health requests while resuming 32 MiB of ordered history", async () => {
|
||||
const startedAt = performance.now();
|
||||
mkdirSync(path.dirname(transcriptPath()), { recursive: true });
|
||||
@@ -700,6 +768,75 @@ describe("ClaudeAgentSession persisted history load", () => {
|
||||
},
|
||||
);
|
||||
|
||||
test.each(["return", "throw"])(
|
||||
"replays oversized records and closes every source after callback %s",
|
||||
async (exit) => {
|
||||
const parent = transcriptPath();
|
||||
const directory = path.join(parent.slice(0, -".jsonl".length), "subagents");
|
||||
const child = path.join(directory, "agent-child.jsonl");
|
||||
const workflow = path.join(directory, "workflows", "wf_test", "agent-child.jsonl");
|
||||
const notification = {
|
||||
type: "system",
|
||||
subtype: "task_notification",
|
||||
task_id: "task-id",
|
||||
status: "completed",
|
||||
};
|
||||
const result = {
|
||||
type: "user",
|
||||
message: {
|
||||
content: [
|
||||
{ type: "tool_result", tool_use_id: "tool-id", content: "é".repeat(600 * 1024) },
|
||||
],
|
||||
},
|
||||
};
|
||||
const parentRecords = [notification, result, notification];
|
||||
const childRecords = parentRecords.map((entry) => ({
|
||||
...entry,
|
||||
isSidechain: true,
|
||||
agentId: "child",
|
||||
}));
|
||||
mkdirSync(path.dirname(workflow), { recursive: true });
|
||||
writeFileSync(parent, parentRecords.map((entry) => JSON.stringify(entry)).join("\n"));
|
||||
writeFileSync(child, childRecords.map((entry) => JSON.stringify(entry)).join("\n"));
|
||||
writeFileSync(workflow, childRecords.map((entry) => JSON.stringify(entry)).join("\n"));
|
||||
|
||||
const sources: AsyncIterable<unknown>[] = [];
|
||||
const failure = new Error("consumer failed");
|
||||
const replay = withClaudeReplayHistory(parent, async (history) => {
|
||||
const parentEntries = await Array.fromAsync(history.parentEntries);
|
||||
const firstId = expect.stringMatching(/^task_notification_.*_1$/);
|
||||
const secondId = expect.stringMatching(/^task_notification_.*_2$/);
|
||||
expect(parentEntries).toEqual([
|
||||
{ ...notification, notificationId: firstId },
|
||||
result,
|
||||
{ ...notification, notificationId: secondId },
|
||||
]);
|
||||
const [first, , last] = parentEntries;
|
||||
const childEntries = history.subagents[0]!.entries;
|
||||
const workflowEntries = history.workflowEntriesByRunId.get("wf_test")!;
|
||||
sources.push(history.parentEntries, childEntries, workflowEntries);
|
||||
const expectedChildEntries = [
|
||||
{ ...childRecords[0], notificationId: first!.notificationId },
|
||||
childRecords[1],
|
||||
{ ...childRecords[2], notificationId: last!.notificationId },
|
||||
];
|
||||
expect(await Array.fromAsync(childEntries)).toEqual(expectedChildEntries);
|
||||
expect(await Array.fromAsync(workflowEntries)).toEqual(expectedChildEntries);
|
||||
expect(await Array.fromAsync(history.parentEntries)).toEqual(parentEntries);
|
||||
if (exit === "throw") throw failure;
|
||||
});
|
||||
if (exit === "throw") await expect(replay).rejects.toBe(failure);
|
||||
else await replay;
|
||||
|
||||
// Reading again probes whether replay released each descriptor when the callback ended.
|
||||
for (const source of sources) {
|
||||
await expect(source[Symbol.asyncIterator]().next()).rejects.toMatchObject({
|
||||
code: "EBADF",
|
||||
});
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
// chmod does not remove read access on Windows, or for root.
|
||||
test.skipIf(process.platform === "win32" || process.getuid?.() === 0)(
|
||||
"logs a warning with the error when Claude's project folders cannot be listed",
|
||||
|
||||
@@ -878,11 +878,12 @@ describe("ClaudeAgentSession persisted subagent replay", () => {
|
||||
const text = "é🙂".repeat(30_000);
|
||||
const historyDir = claudeProjectDirSync(cwd, { configDir });
|
||||
mkdirSync(historyDir, { recursive: true });
|
||||
const first = parentEntry([{ type: "text", text }]);
|
||||
// Put the first byte of é at the end of a 1 MiB read.
|
||||
const padding = " ".repeat(1024 * 1024 - 1 - first.indexOf(text));
|
||||
writeFileSync(
|
||||
path.join(historyDir, "replay-session.jsonl"),
|
||||
parentEntry([{ type: "text", text }]) +
|
||||
"\r\nnot json\r\n" +
|
||||
parentEntry([{ type: "text", text: "final row" }]),
|
||||
padding + first + "\r\nnot json\r\n" + parentEntry([{ type: "text", text: "final row" }]),
|
||||
);
|
||||
const events = await replayEvents();
|
||||
expect(events.filter((event) => event.type === "timeline").map((event) => event.item)).toEqual([
|
||||
|
||||
+28
@@ -41,6 +41,34 @@ function parentEntries(
|
||||
}
|
||||
|
||||
describe("Claude workflow replay", () => {
|
||||
it("skips parent history when there are no workflow summaries", async () => {
|
||||
const entries = {
|
||||
[Symbol.iterator](): Iterator<ClaudeWorkflowParentEntry> {
|
||||
throw new Error("parent history must not be read");
|
||||
},
|
||||
};
|
||||
await expect(
|
||||
observeReplayWorkflows({ workflows: [], parentEntries: entries }),
|
||||
).resolves.toEqual([]);
|
||||
});
|
||||
|
||||
it("links workflow results from a single traversal, including results before their calls", async () => {
|
||||
const [call, result] = parentEntries();
|
||||
const entries = (async function* () {
|
||||
yield result!;
|
||||
yield call!;
|
||||
})();
|
||||
const observations = await observeReplayWorkflows({
|
||||
workflows: [{ runId: RUN_ID, status: "completed" }],
|
||||
parentEntries: entries,
|
||||
});
|
||||
expect(observations).toEqual([
|
||||
{ kind: "declared", id: TOOL_CALL_ID, toolCallId: TOOL_CALL_ID, title: "Workflow" },
|
||||
{ kind: "subtitle", id: TOOL_CALL_ID, subtitle: "Workflow" },
|
||||
{ kind: "status", id: TOOL_CALL_ID, status: "completed" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("parses the persisted run summary observed from Claude Code 2.1.220", async () => {
|
||||
expect(
|
||||
parseClaudeWorkflowRun(
|
||||
|
||||
+16
-15
@@ -55,7 +55,9 @@ export async function observeReplayWorkflows(input: {
|
||||
>;
|
||||
convertEntry?: (entry: ClaudeReplayEntry) => AgentTimelineItem[] | Promise<AgentTimelineItem[]>;
|
||||
}): Promise<SubagentObservation[]> {
|
||||
const toolCallIdByRunId = await readWorkflowLinks(input.parentEntries);
|
||||
if (input.workflows.length === 0) return [];
|
||||
const runIds = new Set(input.workflows.map((workflow) => workflow.runId));
|
||||
const toolCallIdByRunId = await readWorkflowLinks(input.parentEntries, runIds);
|
||||
const observations: SubagentObservation[] = [];
|
||||
|
||||
for (const workflow of input.workflows) {
|
||||
@@ -155,34 +157,33 @@ async function observeWorkflowTimeline(input: {
|
||||
|
||||
async function readWorkflowLinks(
|
||||
entries: Iterable<ClaudeWorkflowParentEntry> | AsyncIterable<ClaudeWorkflowParentEntry>,
|
||||
runIds: ReadonlySet<string>,
|
||||
): Promise<Map<string, string>> {
|
||||
const workflowToolCallIds = new Set<string>();
|
||||
const toolCallIdByRunId = new Map<string, string>();
|
||||
|
||||
for await (const entry of entries) {
|
||||
const content = entry.message?.content;
|
||||
if (!Array.isArray(content)) continue;
|
||||
for (const value of content) {
|
||||
const block = toRecord(value);
|
||||
if (block?.type !== "tool_use" || block.name !== "Workflow") continue;
|
||||
const id = readString(block.id);
|
||||
if (id) workflowToolCallIds.add(id);
|
||||
}
|
||||
}
|
||||
const results: { runId: string; toolCallId: string }[] = [];
|
||||
|
||||
for await (const entry of entries) {
|
||||
const content = entry.message?.content;
|
||||
if (!Array.isArray(content)) continue;
|
||||
for (const value of content) {
|
||||
const block = toRecord(value);
|
||||
if (block?.type === "tool_use" && block.name === "Workflow") {
|
||||
const id = readString(block.id);
|
||||
if (id) workflowToolCallIds.add(id);
|
||||
}
|
||||
if (block?.type !== "tool_result") continue;
|
||||
const toolCallId = readString(block.tool_use_id);
|
||||
if (!toolCallId || !workflowToolCallIds.has(toolCallId)) continue;
|
||||
if (!toolCallId) continue;
|
||||
const runId = readRunId(block.content);
|
||||
if (runId) toolCallIdByRunId.set(runId, toolCallId);
|
||||
if (runId && runIds.has(runId)) results.push({ runId, toolCallId });
|
||||
}
|
||||
}
|
||||
|
||||
// Resolve IDs in result order after all calls are known, even if a result precedes its call.
|
||||
const toolCallIdByRunId = new Map<string, string>();
|
||||
for (const { runId, toolCallId } of results) {
|
||||
if (workflowToolCallIds.has(toolCallId)) toolCallIdByRunId.set(runId, toolCallId);
|
||||
}
|
||||
return toolCallIdByRunId;
|
||||
}
|
||||
|
||||
|
||||
@@ -13,6 +13,10 @@ import {
|
||||
type ClaudeWorkflowRun,
|
||||
} from "./subagents/workflow-replay-source.js";
|
||||
|
||||
const READ_CHUNK_BYTES = 1024 * 1024;
|
||||
// Async iteration between reads uses microtasks, including work inside the consumer.
|
||||
const REPLAY_SLICE_MS = 10;
|
||||
|
||||
interface TranscriptEntry extends ClaudeReplayEntry {
|
||||
isSidechain?: unknown;
|
||||
}
|
||||
@@ -43,13 +47,18 @@ async function* locatedRecords(
|
||||
let pieces: Buffer[] = [];
|
||||
let length = 0;
|
||||
while (remaining > 0) {
|
||||
const buffer = Buffer.allocUnsafe(Math.min(64 * 1024, remaining));
|
||||
const buffer = Buffer.allocUnsafe(Math.min(READ_CHUNK_BYTES, remaining));
|
||||
const { bytesRead: count } = await fd.read(buffer, 0, buffer.length, null);
|
||||
if (count === 0) break;
|
||||
remaining -= count;
|
||||
let sliceStartedAt = performance.now();
|
||||
let start = 0;
|
||||
let end: number;
|
||||
while ((end = buffer.indexOf(10, start)) !== -1 && end < count) {
|
||||
if (performance.now() - sliceStartedAt >= REPLAY_SLICE_MS) {
|
||||
await setImmediate();
|
||||
sliceStartedAt = performance.now();
|
||||
}
|
||||
pieces.push(buffer.subarray(start, end));
|
||||
length += end - start;
|
||||
const entry = parseRecord(Buffer.concat(pieces, length).toString("utf8"));
|
||||
@@ -65,8 +74,6 @@ async function* locatedRecords(
|
||||
if (entry) yield { entry, location };
|
||||
start = end + 1;
|
||||
}
|
||||
// Bound parsing work as well as IO; microtasks alone do not service timers or sockets.
|
||||
await setImmediate();
|
||||
if (start < count) {
|
||||
pieces.push(buffer.subarray(start, count));
|
||||
length += count - start;
|
||||
@@ -96,27 +103,52 @@ function indexedRecords(
|
||||
},
|
||||
};
|
||||
async function* readEntries(): AsyncGenerator<TranscriptEntry> {
|
||||
const chunk = Buffer.allocUnsafe(READ_CHUNK_BYTES);
|
||||
let window: { file: string; offset: number; bytes: Buffer } | undefined;
|
||||
let sliceStartedAt = performance.now();
|
||||
for (const location of locations) {
|
||||
const fd = descriptors.get(location.file)!;
|
||||
const buffer = Buffer.allocUnsafe(location.length);
|
||||
let read = 0;
|
||||
while (read < buffer.length) {
|
||||
const { bytesRead: count } = await fd.read(
|
||||
buffer,
|
||||
read,
|
||||
buffer.length - read,
|
||||
location.offset + read,
|
||||
);
|
||||
if (count === 0)
|
||||
throw new Error(`Claude transcript was truncated during replay: ${location.file}`);
|
||||
read += count;
|
||||
if (
|
||||
window?.file !== location.file ||
|
||||
location.offset < window.offset ||
|
||||
location.offset + location.length > window.offset + window.bytes.length
|
||||
) {
|
||||
const fd = descriptors.get(location.file)!;
|
||||
const buffer = location.length > chunk.length ? Buffer.allocUnsafe(location.length) : chunk;
|
||||
// Read ahead from the next indexed record. The index still owns selection and order,
|
||||
// including sparse sidechains and workflow records sorted across files.
|
||||
window = {
|
||||
file: location.file,
|
||||
offset: location.offset,
|
||||
bytes: await readRecordWindow(fd, buffer, location),
|
||||
};
|
||||
sliceStartedAt = performance.now();
|
||||
}
|
||||
const entry = parseRecord(buffer.toString("utf8"));
|
||||
if (performance.now() - sliceStartedAt >= REPLAY_SLICE_MS) {
|
||||
await setImmediate();
|
||||
sliceStartedAt = performance.now();
|
||||
}
|
||||
const start = location.offset - window.offset;
|
||||
const entry = parseRecord(window.bytes.toString("utf8", start, start + location.length));
|
||||
if (entry) yield entry;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function readRecordWindow(
|
||||
fd: FileHandle,
|
||||
buffer: Buffer,
|
||||
location: RecordLocation,
|
||||
): Promise<Buffer> {
|
||||
let read = 0;
|
||||
while (read < location.length) {
|
||||
const { bytesRead } = await fd.read(buffer, read, buffer.length - read, location.offset + read);
|
||||
if (bytesRead === 0)
|
||||
throw new Error(`Claude transcript was truncated during replay: ${location.file}`);
|
||||
read += bytesRead;
|
||||
}
|
||||
return buffer.subarray(0, read);
|
||||
}
|
||||
|
||||
function isToolResult(entry: TranscriptEntry): boolean {
|
||||
return (
|
||||
Array.isArray(entry.message?.content) &&
|
||||
|
||||
@@ -1,4 +1,13 @@
|
||||
import { existsSync, rmSync, statSync } from "node:fs";
|
||||
import {
|
||||
existsSync,
|
||||
mkdtempSync,
|
||||
readFileSync,
|
||||
rmSync,
|
||||
statSync,
|
||||
symlinkSync,
|
||||
writeFileSync,
|
||||
} from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { describe, expect, test } from "vitest";
|
||||
|
||||
@@ -22,3 +31,30 @@ describe.skipIf(process.platform === "win32")("materializeProviderImage", () =>
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
test.skipIf(process.platform === "win32")(
|
||||
"replaces a cached attachment directory turned into a symlink",
|
||||
async () => {
|
||||
const image = { data: "c3ltbGluayByZWdyZXNzaW9u", mimeType: "image/png" };
|
||||
const first = await materializeProviderImage(image);
|
||||
const dir = path.dirname(first.path);
|
||||
const target = mkdtempSync(path.join(os.tmpdir(), "paseo-image-symlink-test-"));
|
||||
let replacement: string | undefined;
|
||||
try {
|
||||
rmSync(dir, { recursive: true });
|
||||
// Populate the target to exercise validation before accepting a cache hit.
|
||||
writeFileSync(path.join(target, path.basename(first.path)), "symlink target");
|
||||
symlinkSync(target, dir, "dir");
|
||||
|
||||
const second = await materializeProviderImage(image);
|
||||
replacement = path.dirname(second.path);
|
||||
expect(replacement).not.toBe(dir);
|
||||
expect(path.basename(replacement)).toMatch(/^paseo-attachments-/);
|
||||
expect(readFileSync(second.path, "utf8")).toBe("symlink regression");
|
||||
} finally {
|
||||
if (replacement && replacement !== dir) rmSync(replacement, { recursive: true });
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
rmSync(target, { recursive: true, force: true });
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { AsyncLocalStorage, createHook } from "node:async_hooks";
|
||||
import { existsSync, rmSync, statSync, readFileSync } from "node:fs";
|
||||
import path from "node:path";
|
||||
import MarkdownIt from "markdown-it";
|
||||
@@ -211,7 +212,7 @@ test("64 MiB materialization leaves the event loop responsive and preserves byte
|
||||
});
|
||||
|
||||
test("preserves base64 decoding across whitespace and chunk boundaries", async () => {
|
||||
const bytes = Buffer.alloc(512 * 1024, 123);
|
||||
const bytes = Buffer.alloc(1024 * 1024, 123);
|
||||
const base64 = bytes.toString("base64");
|
||||
const data = base64.match(/.{1,77}/g)!.join("\n");
|
||||
const result = await materializeProviderImage({ data, mimeType: "image/png" });
|
||||
@@ -247,3 +248,114 @@ test("simultaneous requests for the same content share the published file", asyn
|
||||
expect(results[0]).toEqual(results[1]);
|
||||
expect(readFileSync(results[0].path).toString()).toBe("concurrent dedupe fixture");
|
||||
});
|
||||
|
||||
test("a small image finishes before an earlier distinct 64 MiB image", async () => {
|
||||
const largeData = Buffer.alloc(64 * 1024 * 1024, 42).toString("base64");
|
||||
const smallData = Buffer.from("live image during large replay").toString("base64");
|
||||
const completionOrder: string[] = [];
|
||||
const large = materializeProviderImage({ data: largeData, mimeType: "image/png" }).then(
|
||||
(image) => {
|
||||
completionOrder.push("large");
|
||||
return image;
|
||||
},
|
||||
);
|
||||
const small = materializeProviderImage({ data: smallData, mimeType: "image/png" }).then(
|
||||
(image) => {
|
||||
completionOrder.push("small");
|
||||
return image;
|
||||
},
|
||||
);
|
||||
const images = await Promise.all([large, small]);
|
||||
for (const image of images) rmSync(image.path, { force: true });
|
||||
expect(completionOrder).toEqual(["small", "large"]);
|
||||
});
|
||||
|
||||
test("publishing small distinct images stays within eight event-loop turns per image", async () => {
|
||||
const count = 20;
|
||||
const materializing = new AsyncLocalStorage<boolean>();
|
||||
let turn = 0;
|
||||
let lastActiveTurn = -1;
|
||||
let activeTurns = 0;
|
||||
const hook = createHook({
|
||||
before() {
|
||||
// A spinning immediate can tick many times while a filesystem worker is
|
||||
// still running. Count only turns that advance the materializations.
|
||||
if (materializing.getStore() && turn !== lastActiveTurn) {
|
||||
lastActiveTurn = turn;
|
||||
activeTurns++;
|
||||
}
|
||||
},
|
||||
});
|
||||
let probe = setImmediate(function tick() {
|
||||
turn++;
|
||||
probe = setImmediate(tick);
|
||||
});
|
||||
const images: string[] = [];
|
||||
hook.enable();
|
||||
try {
|
||||
await materializing.run(true, async () => {
|
||||
for (let index = 0; index < count; index++) {
|
||||
const data = Buffer.from(`small attachment ${index}`).toString("base64");
|
||||
const image = await materializeProviderImage({ data, mimeType: "image/png" });
|
||||
images.push(image.path);
|
||||
}
|
||||
});
|
||||
} finally {
|
||||
hook.disable();
|
||||
clearImmediate(probe);
|
||||
for (const image of images) rmSync(image, { force: true });
|
||||
}
|
||||
expect(activeTurns).toBeLessThanOrEqual(8 * count);
|
||||
});
|
||||
|
||||
test("six concurrent 8 MiB images share the main-thread CPU budget", async () => {
|
||||
const inputs = Array.from({ length: 6 }, (_, index) => ({
|
||||
data: Buffer.alloc(8 * 1024 * 1024, index + 1).toString("base64"),
|
||||
mimeType: "image/png",
|
||||
}));
|
||||
const threadCpuMs = () => {
|
||||
const { user, system } = process.threadCpuUsage();
|
||||
return (user + system) / 1000;
|
||||
};
|
||||
let previous = threadCpuMs();
|
||||
let longest = 0;
|
||||
const probe = setInterval(() => {
|
||||
const now = threadCpuMs();
|
||||
longest = Math.max(longest, now - previous);
|
||||
previous = now;
|
||||
}, 1);
|
||||
try {
|
||||
const images = await Promise.all(inputs.map(materializeProviderImage));
|
||||
await new Promise((resolve) => setTimeout(resolve, 5));
|
||||
for (const image of images) rmSync(image.path, { force: true });
|
||||
expect(longest).toBeLessThan(50);
|
||||
} finally {
|
||||
clearInterval(probe);
|
||||
}
|
||||
});
|
||||
|
||||
test("a busy event loop does not spend the image decode budget", async () => {
|
||||
const count = 8;
|
||||
let turns = 0;
|
||||
let probe = setImmediate(function tick() {
|
||||
turns++;
|
||||
// Simulate unrelated work that exceeds a 10 ms decode slice.
|
||||
const end = performance.now() + 20;
|
||||
while (performance.now() < end) {
|
||||
// Keep this event-loop turn busy.
|
||||
}
|
||||
probe = setImmediate(tick);
|
||||
});
|
||||
const paths: string[] = [];
|
||||
try {
|
||||
for (let index = 0; index < count; index++) {
|
||||
const data = Buffer.from(`attachment on a busy loop ${index}`).toString("base64");
|
||||
const image = await materializeProviderImage({ data, mimeType: "image/png" });
|
||||
paths.push(image.path);
|
||||
}
|
||||
} finally {
|
||||
clearImmediate(probe);
|
||||
for (const image of paths) rmSync(image, { force: true });
|
||||
}
|
||||
expect(turns).toBeLessThanOrEqual(7 * count);
|
||||
});
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { createHash, randomUUID } from "node:crypto";
|
||||
import * as fs from "node:fs/promises";
|
||||
import { setImmediate } from "node:timers/promises";
|
||||
import os from "node:os";
|
||||
@@ -23,28 +23,26 @@ const PROVIDER_IMAGE_ATTACHMENT_DIR_PREFIX = `${PROVIDER_IMAGE_ATTACHMENT_DIR}-`
|
||||
const PRIVATE_ATTACHMENT_DIR_MODE = 0o700;
|
||||
const MATERIALIZED_IMAGE_FILE_MODE = 0o600;
|
||||
|
||||
let materializedImageAttachmentDir: string | null = null;
|
||||
// Serialize materializations: one decoder and one file operation at a time, including
|
||||
// concurrent history replay and live turns. A rejected operation must not poison the queue.
|
||||
let pendingMaterialization: Promise<unknown> = Promise.resolve();
|
||||
let attachmentDirectory: Promise<string> | undefined;
|
||||
const pendingWrites = new Map<string, Promise<MaterializedProviderImage>>();
|
||||
|
||||
async function getMaterializedImageAttachmentDir(): Promise<string> {
|
||||
if (materializedImageAttachmentDir) {
|
||||
try {
|
||||
const stats = await fs.lstat(materializedImageAttachmentDir);
|
||||
if (stats.isDirectory()) {
|
||||
await fs.chmod(materializedImageAttachmentDir, PRIVATE_ATTACHMENT_DIR_MODE);
|
||||
return materializedImageAttachmentDir;
|
||||
}
|
||||
} catch {
|
||||
/* Temp storage may have been removed between turns. */
|
||||
}
|
||||
}
|
||||
materializedImageAttachmentDir = await fs.mkdtemp(
|
||||
path.join(os.tmpdir(), PROVIDER_IMAGE_ATTACHMENT_DIR_PREFIX),
|
||||
);
|
||||
await fs.chmod(materializedImageAttachmentDir, PRIVATE_ATTACHMENT_DIR_MODE);
|
||||
return materializedImageAttachmentDir;
|
||||
function getMaterializedImageAttachmentDir(): Promise<string> {
|
||||
attachmentDirectory ??= createAttachmentDirectory().catch((error) => {
|
||||
attachmentDirectory = undefined;
|
||||
throw error;
|
||||
});
|
||||
return attachmentDirectory;
|
||||
}
|
||||
|
||||
async function createAttachmentDirectory(): Promise<string> {
|
||||
const dir = await fs.mkdtemp(path.join(os.tmpdir(), PROVIDER_IMAGE_ATTACHMENT_DIR_PREFIX));
|
||||
await fs.chmod(dir, PRIVATE_ATTACHMENT_DIR_MODE);
|
||||
return dir;
|
||||
}
|
||||
|
||||
function isMissingPath(error: unknown): boolean {
|
||||
const code = (error as NodeJS.ErrnoException).code;
|
||||
return code === "ENOENT" || code === "ENOTDIR";
|
||||
}
|
||||
|
||||
function getImageExtension(mimeType: string): string {
|
||||
@@ -69,18 +67,18 @@ function getImageExtension(mimeType: string): string {
|
||||
// 128 MiB admits the measured 64 MiB fixture with headroom while bounding disk
|
||||
// and decoding per image. This is materialization admission, not a wire schema limit.
|
||||
export const MAX_PROVIDER_IMAGE_BYTES = 128 * 1024 * 1024;
|
||||
const BASE64_CHUNK_CHARACTERS = 256 * 1024; // Multiple of four; decode units stay aligned.
|
||||
const BASE64_CHUNK_CHARACTERS = 1024 * 1024; // Multiple of four; decode units stay aligned.
|
||||
const DECODE_SLICE_MS = 10;
|
||||
let decodeBudgetMs = DECODE_SLICE_MS;
|
||||
let pendingDecodeYield: Promise<void> | undefined;
|
||||
|
||||
export function materializeProviderImage(image: {
|
||||
data: string;
|
||||
mimeType: string | null;
|
||||
}): Promise<MaterializedProviderImage> {
|
||||
const result = pendingMaterialization.then(() => materializeImage(image));
|
||||
pendingMaterialization = result.catch(() => {});
|
||||
return result;
|
||||
async function refillDecodeBudget(): Promise<void> {
|
||||
await setImmediate();
|
||||
decodeBudgetMs = DECODE_SLICE_MS;
|
||||
pendingDecodeYield = undefined;
|
||||
}
|
||||
|
||||
async function materializeImage(image: {
|
||||
export async function materializeProviderImage(image: {
|
||||
data: string;
|
||||
mimeType: string | null;
|
||||
}): Promise<MaterializedProviderImage> {
|
||||
@@ -103,32 +101,74 @@ async function materializeImage(image: {
|
||||
}
|
||||
const hash = createHash("sha256");
|
||||
for await (const bytes of decodeImage(data)) hash.update(bytes);
|
||||
const dir = await getMaterializedImageAttachmentDir();
|
||||
const filePath = path.join(dir, `${hash.digest("hex")}.${getImageExtension(mimeType)}`);
|
||||
const filename = `${hash.digest("hex")}.${getImageExtension(mimeType)}`;
|
||||
const directory = getMaterializedImageAttachmentDir();
|
||||
const dir = await directory;
|
||||
try {
|
||||
await fs.stat(filePath);
|
||||
return { path: filePath };
|
||||
return await materializeInDirectory(dir, filename, data);
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
|
||||
if (!isMissingPath(error)) throw error;
|
||||
// Other requests may have already replaced the directory after the same deletion.
|
||||
if (attachmentDirectory === directory) attachmentDirectory = undefined;
|
||||
const replacement = await getMaterializedImageAttachmentDir();
|
||||
return materializeInDirectory(replacement, filename, data);
|
||||
}
|
||||
}
|
||||
|
||||
const staging = await fs.mkdtemp(path.join(dir, ".pending-"));
|
||||
const stagingPath = path.join(staging, "image");
|
||||
function materializeInDirectory(
|
||||
dir: string,
|
||||
filename: string,
|
||||
data: string,
|
||||
): Promise<MaterializedProviderImage> {
|
||||
const filePath = path.join(dir, filename);
|
||||
const pending = pendingWrites.get(filePath);
|
||||
if (pending) return pending;
|
||||
|
||||
const write = publishImage(dir, filePath, data).finally(() => {
|
||||
pendingWrites.delete(filePath);
|
||||
});
|
||||
pendingWrites.set(filePath, write);
|
||||
return write;
|
||||
}
|
||||
|
||||
async function publishImage(
|
||||
dir: string,
|
||||
filePath: string,
|
||||
data: string,
|
||||
): Promise<MaterializedProviderImage> {
|
||||
const [directory, existing] = await Promise.allSettled([fs.lstat(dir), fs.stat(filePath)]);
|
||||
if (directory.status === "rejected") throw directory.reason;
|
||||
const stats = directory.value;
|
||||
const uid = process.platform === "win32" ? undefined : process.getuid?.();
|
||||
if (
|
||||
!stats.isDirectory() ||
|
||||
(uid !== undefined && (stats.uid !== uid || (stats.mode & 0o077) !== 0))
|
||||
) {
|
||||
throw Object.assign(new Error("Private image attachment directory is unavailable"), {
|
||||
code: "ENOENT",
|
||||
});
|
||||
}
|
||||
if (existing.status === "fulfilled") return { path: filePath };
|
||||
if (!isMissingPath(existing.reason)) throw existing.reason;
|
||||
|
||||
const stagingPath = path.join(dir, `.pending-${randomUUID()}`);
|
||||
const file = await fs.open(stagingPath, "wx", MATERIALIZED_IMAGE_FILE_MODE);
|
||||
try {
|
||||
await fs.chmod(staging, PRIVATE_ATTACHMENT_DIR_MODE);
|
||||
const file = await fs.open(stagingPath, "wx", MATERIALIZED_IMAGE_FILE_MODE);
|
||||
try {
|
||||
// Restore owner permissions if the umask masked them at open.
|
||||
await file.chmod(MATERIALIZED_IMAGE_FILE_MODE);
|
||||
// Decode again only for a new hash. This bounds retained memory to one chunk
|
||||
// and performs no writes at all for repeated content, including history replay.
|
||||
// Decode again only for new content, retaining one chunk at a time.
|
||||
for await (const bytes of decodeImage(data)) await file.writeFile(bytes);
|
||||
} finally {
|
||||
await file.close();
|
||||
}
|
||||
await fs.rename(stagingPath, filePath);
|
||||
return { path: filePath };
|
||||
} finally {
|
||||
await fs.rm(staging, { recursive: true, force: true });
|
||||
} catch (error) {
|
||||
await fs.unlink(stagingPath).catch((cleanupError) => {
|
||||
if (!isMissingPath(cleanupError)) throw cleanupError;
|
||||
});
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -136,6 +176,13 @@ async function* decodeImage(data: string): AsyncGenerator<Buffer> {
|
||||
let carry = "";
|
||||
let decodedBytes = 0;
|
||||
for (let offset = 0; offset < data.length; offset += BASE64_CHUNK_CHARACTERS) {
|
||||
let pause = pendingDecodeYield;
|
||||
while (pause) {
|
||||
await pause;
|
||||
pause = pendingDecodeYield;
|
||||
}
|
||||
// Charge synchronous work across decoders. File I/O and idle time leave the budget intact.
|
||||
const startedAt = performance.now();
|
||||
// Buffer.from ignores non-base64 characters. Carry incomplete quartets so
|
||||
// line-wrapped payloads decode identically across chunk boundaries.
|
||||
const chunk =
|
||||
@@ -144,12 +191,13 @@ async function* decodeImage(data: string): AsyncGenerator<Buffer> {
|
||||
const finalChunk = offset + BASE64_CHUNK_CHARACTERS >= data.length || chunk.includes("=");
|
||||
const end = finalChunk ? chunk.length : chunk.length - (chunk.length % 4);
|
||||
const bytes = Buffer.from(chunk.slice(0, end), "base64");
|
||||
decodeBudgetMs -= performance.now() - startedAt;
|
||||
if (decodeBudgetMs <= 0) pendingDecodeYield = refillDecodeBudget();
|
||||
carry = chunk.slice(end);
|
||||
decodedBytes += bytes.length;
|
||||
if (decodedBytes > MAX_PROVIDER_IMAGE_BYTES)
|
||||
throw new Error("Image attachment exceeds size limit");
|
||||
yield bytes;
|
||||
await setImmediate();
|
||||
if (finalChunk) break;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2728,13 +2728,19 @@ function createToolCatalog(
|
||||
|
||||
if (options.changeRequestWatches) {
|
||||
const watches = options.changeRequestWatches;
|
||||
const inputSchema = { url: z.string().trim().min(1).describe("URL of a GitHub pull request.") };
|
||||
const inputSchema = {
|
||||
url: z
|
||||
.string()
|
||||
.trim()
|
||||
.min(1)
|
||||
.describe("URL of a pull request or merge request on a supported forge."),
|
||||
};
|
||||
registerTool(
|
||||
"subscribe_change_request",
|
||||
{
|
||||
title: "Watch change request",
|
||||
description:
|
||||
"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.",
|
||||
"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.",
|
||||
inputSchema,
|
||||
outputSchema: {
|
||||
url: z.string(),
|
||||
|
||||
@@ -132,6 +132,9 @@ 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";
|
||||
@@ -954,12 +957,15 @@ 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: {
|
||||
forgeOverrides: { github },
|
||||
forgeResolver,
|
||||
},
|
||||
});
|
||||
const workspaceRuntimeStore = createWorkspaceRuntimeStore();
|
||||
@@ -1472,7 +1478,7 @@ export async function createPaseoDaemon(
|
||||
await scheduleService.start();
|
||||
|
||||
const changeRequestWatches = createChangeRequestWatches({
|
||||
source: github.changeRequests,
|
||||
router: createChangeRequestRouter({ forgeResolver }),
|
||||
backgroundWork: agentManager,
|
||||
paseoHome: config.paseoHome,
|
||||
logger,
|
||||
@@ -2056,6 +2062,7 @@ 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
|
||||
|
||||
@@ -2404,6 +2404,46 @@ 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,6 +422,8 @@ 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>;
|
||||
@@ -723,10 +725,12 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
|
||||
this.fileObserver.subscribe.bind(this.fileObserver),
|
||||
options.deps,
|
||||
);
|
||||
this.forgeResolver = createForgeResolver({
|
||||
createService: (forge) => this.deps.forgeOverrides?.[forge] ?? createForgeService(forge),
|
||||
resolveSshHostname: this.deps.resolveSshHostname,
|
||||
});
|
||||
this.forgeResolver =
|
||||
this.deps.forgeResolver ??
|
||||
createForgeResolver({
|
||||
createService: (forge) => this.deps.forgeOverrides?.[forge] ?? createForgeService(forge),
|
||||
resolveSshHostname: this.deps.resolveSshHostname,
|
||||
});
|
||||
}
|
||||
|
||||
resolveForge(cwd: string): Promise<ForgeResolution | null> {
|
||||
@@ -834,9 +838,10 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
|
||||
cwd = resolve(cwd);
|
||||
const request = this.normalizeRefreshRequest(options, "getSnapshot");
|
||||
const target = this.ensureWorkspaceTarget(cwd);
|
||||
// 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) {
|
||||
// Restoration clears folderMissing before the fresh snapshot is ready.
|
||||
if (target.folderRestorePromise) {
|
||||
await target.folderRestorePromise;
|
||||
} else if (target.folderMissing) {
|
||||
await this.resumeWorkspaceIfFolderRestored(target);
|
||||
}
|
||||
if (!request.force && target.latestSnapshot) {
|
||||
|
||||
@@ -0,0 +1,230 @@
|
||||
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();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,362 @@
|
||||
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();
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
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();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,80 @@
|
||||
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,8 +17,9 @@ const changeRequestSnapshotSchema = changeRequestStatusSchema.extend({
|
||||
activity: z.array(
|
||||
z.object({
|
||||
id: z.string(),
|
||||
kind: z.enum(["comment", "inline comment", "review"]),
|
||||
kind: z.enum(["comment", "inline comment", "review", "approval"]),
|
||||
url: z.string(),
|
||||
message: z.string().optional(),
|
||||
}),
|
||||
),
|
||||
});
|
||||
|
||||
@@ -373,4 +373,40 @@ 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,5 +1,9 @@
|
||||
import { LRUCache } from "lru-cache";
|
||||
import { parseGitRemoteLocation, type GitRemoteLocation } from "@getpaseo/protocol/git-remote";
|
||||
import {
|
||||
normalizeHost,
|
||||
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";
|
||||
@@ -24,6 +28,7 @@ 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;
|
||||
@@ -36,12 +41,18 @@ 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
|
||||
@@ -64,6 +75,7 @@ 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;
|
||||
@@ -110,22 +122,34 @@ export function createForgeResolver(options: CreateForgeResolverOptions = {}): F
|
||||
if (!entry) {
|
||||
return undefined;
|
||||
}
|
||||
if (entry.expiresAt !== null && Date.now() >= entry.expiresAt) {
|
||||
if (entry.expiresAt !== null && now() >= entry.expiresAt) {
|
||||
probedForgeByHost.delete(host);
|
||||
return undefined;
|
||||
}
|
||||
return entry.forge;
|
||||
}
|
||||
|
||||
function buildResolution(forge: string, host: string): ForgeResolution | null {
|
||||
let service = services.get(forge);
|
||||
function getService(forge: string): ForgeService | null {
|
||||
const normalized = forge.trim().toLowerCase();
|
||||
if (!normalized) {
|
||||
return null;
|
||||
}
|
||||
let service = services.get(normalized);
|
||||
if (!service) {
|
||||
const created = create(forge);
|
||||
const created = create(normalized);
|
||||
if (!created) {
|
||||
return null;
|
||||
}
|
||||
service = created;
|
||||
services.set(forge, service);
|
||||
services.set(normalized, service);
|
||||
}
|
||||
return service;
|
||||
}
|
||||
|
||||
function buildResolution(forge: string, host: string): ForgeResolution | null {
|
||||
const service = getService(forge);
|
||||
if (!service) {
|
||||
return null;
|
||||
}
|
||||
return { forge, host, service };
|
||||
}
|
||||
@@ -151,7 +175,7 @@ export function createForgeResolver(options: CreateForgeResolverOptions = {}): F
|
||||
}
|
||||
probedForgeByHost.set(host, {
|
||||
forge: probed,
|
||||
expiresAt: probed === null ? Date.now() + NEGATIVE_PROBE_TTL_MS : null,
|
||||
expiresAt: probed === null ? now() + NEGATIVE_PROBE_TTL_MS : null,
|
||||
});
|
||||
return probed;
|
||||
} finally {
|
||||
@@ -170,13 +194,29 @@ export function createForgeResolver(options: CreateForgeResolverOptions = {}): F
|
||||
if (!host) {
|
||||
return null;
|
||||
}
|
||||
const forge = forgeForHost(host) ?? readFreshProbe(host) ?? null;
|
||||
const forge = matchHost(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> {
|
||||
@@ -187,7 +227,7 @@ export function createForgeResolver(options: CreateForgeResolverOptions = {}): F
|
||||
if (!location) {
|
||||
return null;
|
||||
}
|
||||
const directForge = forgeForHost(location.host);
|
||||
const directForge = matchHost(location.host);
|
||||
if (directForge) {
|
||||
return buildResolution(directForge, location.host);
|
||||
}
|
||||
@@ -215,7 +255,7 @@ export function createForgeResolver(options: CreateForgeResolverOptions = {}): F
|
||||
}
|
||||
probedForgeByHost.set(aliasHost, {
|
||||
forge,
|
||||
expiresAt: forge === null ? Date.now() + NEGATIVE_PROBE_TTL_MS : null,
|
||||
expiresAt: forge === null ? now() + NEGATIVE_PROBE_TTL_MS : null,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -231,7 +271,7 @@ export function createForgeResolver(options: CreateForgeResolverOptions = {}): F
|
||||
return { host: location.host };
|
||||
}
|
||||
|
||||
const resolvedForge = forgeForHost(resolvedHost);
|
||||
const resolvedForge = matchHost(resolvedHost);
|
||||
if (resolvedForge) {
|
||||
return { host: resolvedHost, forge: resolvedForge };
|
||||
}
|
||||
@@ -246,10 +286,19 @@ 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,4 +1,5 @@
|
||||
import type { ForgeSearchKind } from "@getpaseo/protocol/messages";
|
||||
import type { ChangeRequestSource } from "./change-request-source.js";
|
||||
|
||||
export type ForgeSearchRequestKind = ForgeSearchKind | "github-issue" | "github-pr" | "pr";
|
||||
|
||||
@@ -533,6 +534,8 @@ 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
@@ -0,0 +1,936 @@
|
||||
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();
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,253 @@
|
||||
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,6 +61,23 @@ 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 = {
|
||||
@@ -77,10 +94,6 @@ 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;
|
||||
|
||||
@@ -142,6 +155,8 @@ export interface CreateGiteaServiceOptions {
|
||||
resolveRemoteUrl?: (cwd: string) => Promise<string | null>;
|
||||
resolveCurrentBranch?: (cwd: string) => Promise<string | null>;
|
||||
now?: () => number;
|
||||
watchPollMs?: number;
|
||||
watchInitialDelayMs?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -180,14 +195,6 @@ 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(),
|
||||
@@ -288,55 +295,6 @@ 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(),
|
||||
@@ -410,9 +368,6 @@ 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>;
|
||||
@@ -797,10 +752,6 @@ 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 {
|
||||
@@ -814,136 +765,6 @@ 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[],
|
||||
@@ -1219,32 +1040,6 @@ 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;
|
||||
}
|
||||
@@ -1409,19 +1204,35 @@ export function createGiteaService(options: CreateGiteaServiceOptions = {}): For
|
||||
const now = options.now ?? Date.now;
|
||||
const currentPrHeadShaCache = new Map<string, { sha: string; expiresAt: number }>();
|
||||
|
||||
async function run(args: string[], runOptions: TeaCommandRunnerOptions): Promise<string> {
|
||||
async function runRaw(
|
||||
args: string[],
|
||||
runOptions: TeaCommandRunnerOptions,
|
||||
): Promise<TeaCommandResult> {
|
||||
const teaPath = await resolveTea();
|
||||
if (!teaPath) {
|
||||
throw new TeaCliMissingError();
|
||||
}
|
||||
try {
|
||||
const result = await runner(args, runOptions);
|
||||
return result.stdout.trim();
|
||||
return await runner(args, runOptions);
|
||||
} 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,
|
||||
@@ -2359,6 +2170,8 @@ 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()) {
|
||||
@@ -2367,5 +2180,9 @@ export function createGiteaService(options: CreateGiteaServiceOptions = {}): For
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
dispose(): void {
|
||||
changeRequests.dispose();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,917 @@
|
||||
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,6 +60,7 @@ 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 = {
|
||||
@@ -112,6 +113,9 @@ export interface CreateGitLabServiceOptions {
|
||||
runner?: GlabCommandRunner;
|
||||
resolveGlabPath?: () => Promise<string | null>;
|
||||
resolveRemoteUrl?: (cwd: string) => Promise<string | null>;
|
||||
now?: () => number;
|
||||
watchPollMs?: number;
|
||||
watchInitialDelayMs?: number;
|
||||
}
|
||||
|
||||
const GitLabPipelineSchema = z
|
||||
@@ -925,19 +929,37 @@ export function createGitLabService(options: CreateGitLabServiceOptions = {}): F
|
||||
const resolveGlab = createCachedCliPathResolver(options.resolveGlabPath ?? resolveGlabPath);
|
||||
const resolveRemoteUrl = options.resolveRemoteUrl ?? defaultResolveRemoteUrl;
|
||||
|
||||
async function run(args: string[], runOptions: GlabCommandRunnerOptions): Promise<string> {
|
||||
async function runRaw(
|
||||
args: string[],
|
||||
runOptions: GlabCommandRunnerOptions,
|
||||
): Promise<GlabCommandResult> {
|
||||
const glabPath = await resolveGlab();
|
||||
if (!glabPath) {
|
||||
throw new GlabCliMissingError();
|
||||
}
|
||||
try {
|
||||
const result = await runner(args, runOptions);
|
||||
return result.stdout.trim();
|
||||
return await runner(args, runOptions);
|
||||
} 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.
|
||||
@@ -1486,6 +1508,12 @@ export function createGitLabService(options: CreateGitLabServiceOptions = {}): F
|
||||
return { success: true };
|
||||
},
|
||||
|
||||
changeRequests,
|
||||
|
||||
invalidate(_input: { cwd: string }): void {},
|
||||
|
||||
dispose(): void {
|
||||
changeRequests.dispose();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -109,6 +109,63 @@ test("switches language on the same page, keeping the query and then every link"
|
||||
await expect(page.locator("html")).toHaveAttribute("lang", "en");
|
||||
});
|
||||
|
||||
async function openHubDoc(page: Page, prefix: string, slug: string, heading: string) {
|
||||
await page.goto(`${prefix}/docs/hub/${slug}`);
|
||||
await expect(page.getByRole("heading", { name: heading, level: 1 })).toBeVisible();
|
||||
}
|
||||
|
||||
async function expectHubDocRedirect(
|
||||
page: Page,
|
||||
prefix: string,
|
||||
legacySlug: string,
|
||||
slug: string,
|
||||
heading: string,
|
||||
) {
|
||||
await page.goto(`${prefix}/docs/hub/${legacySlug}`);
|
||||
await expect(page).toHaveURL(`${prefix}/docs/hub/${slug}`);
|
||||
await expect(page.getByRole("heading", { name: heading, level: 1 })).toBeVisible();
|
||||
}
|
||||
|
||||
for (const { locale, prefix, linear, linearApp, webhooks, triggers, reference } of [
|
||||
{
|
||||
locale: "English",
|
||||
prefix: "",
|
||||
linear: "Linear triggers",
|
||||
linearApp: "Linear for Hub",
|
||||
webhooks: "Inbound webhooks",
|
||||
triggers: "Triggers",
|
||||
reference: "Trigger YAML reference",
|
||||
},
|
||||
{
|
||||
locale: "Simplified Chinese",
|
||||
prefix: "/zh-CN",
|
||||
linear: "Linear 触发器",
|
||||
linearApp: "为 Hub 配置 Linear",
|
||||
webhooks: "入站 webhook",
|
||||
triggers: "触发器",
|
||||
reference: "触发器 YAML 参考",
|
||||
},
|
||||
]) {
|
||||
test(`opens ${locale} Hub guides and redirects legacy bookmarks`, async ({ page }) => {
|
||||
await test.step("opens direct links to the new guides", async () => {
|
||||
await openHubDoc(page, prefix, "triggers/linear", linear);
|
||||
await openHubDoc(page, prefix, "self-hosting/linear-app", linearApp);
|
||||
await openHubDoc(page, prefix, "triggers/webhooks", webhooks);
|
||||
});
|
||||
|
||||
await test.step("redirects legacy guides within the same language", async () => {
|
||||
await expectHubDocRedirect(page, prefix, "workflows", "triggers", triggers);
|
||||
await expectHubDocRedirect(
|
||||
page,
|
||||
prefix,
|
||||
"configuration/hub-yml",
|
||||
"configuration/reference",
|
||||
reference,
|
||||
);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
test("shows the language as an abbreviation and lists every language by name", async ({ page }) => {
|
||||
await page.goto("/docs/cli#running-agents");
|
||||
const button = languageButton(page);
|
||||
|
||||
@@ -166,6 +166,14 @@ export function getLegacyDocsRedirect(pathname: string): string | undefined {
|
||||
const provider = /^\/docs\/(claude-code|codex|muse-code)(\.md)?\/?$/.exec(pathname);
|
||||
if (provider) return `/docs/supported-providers/${provider[1]}${provider[2] ?? ""}`;
|
||||
|
||||
// Legacy Hub stepped-workflow docs moved to self-contained trigger docs and YAML reference.
|
||||
const hubLegacy = /^\/docs\/hub\/(workflows|configuration\/hub-yml)(\.md)?\/?$/.exec(pathname);
|
||||
if (hubLegacy) {
|
||||
const target =
|
||||
hubLegacy[1] === "workflows" ? "/docs/hub/triggers" : "/docs/hub/configuration/reference";
|
||||
return `${target}${hubLegacy[2] ?? ""}`;
|
||||
}
|
||||
|
||||
const match =
|
||||
/^\/docs\/plugins\/v0\.[78](?:(\.md)|\/(index|reference|providers|migration)(\.md)?)?\/?$/.exec(
|
||||
pathname,
|
||||
|
||||
@@ -2,12 +2,13 @@ import { readFile, readdir } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import YAML from "yaml";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { getDoc, getDocs, getLegacyDocsRedirect, parseHeadings } from "./docs";
|
||||
|
||||
const repositoryRoot = path.resolve(import.meta.dirname, "../../..");
|
||||
const hubDocs = path.join(repositoryRoot, "public-docs", "hub");
|
||||
|
||||
describe("Hub public documentation examples", () => {
|
||||
it("parses every Hub YAML example and keeps resource maps canonical", async () => {
|
||||
it("parses every Hub YAML example and keeps trigger documents canonical", async () => {
|
||||
const files = [
|
||||
...(await markdownFiles(hubDocs)),
|
||||
path.join(repositoryRoot, "public-docs", "cli.md"),
|
||||
@@ -24,6 +25,9 @@ describe("Hub public documentation examples", () => {
|
||||
expect(parsed, `${label} must not teach monolithic triggers`).not.toHaveProperty(
|
||||
"triggers",
|
||||
);
|
||||
expect(parsed, `${label} must not teach legacy stepped workflows`).not.toHaveProperty(
|
||||
"steps",
|
||||
);
|
||||
if (Object.hasOwn(parsed, "environments")) {
|
||||
expect(isRecord(parsed["environments"]), `${label} environments`).toBe(true);
|
||||
}
|
||||
@@ -35,18 +39,75 @@ describe("Hub public documentation examples", () => {
|
||||
expect(exampleCount).toBeGreaterThan(20);
|
||||
});
|
||||
|
||||
it("does not teach removed Hub authoring paths or composition fields", async () => {
|
||||
it("does not teach removed Hub authoring paths or legacy stepped workflows", async () => {
|
||||
const markdown = (
|
||||
await Promise.all((await markdownFiles(hubDocs)).map((file) => readFile(file, "utf8")))
|
||||
).join("\n");
|
||||
|
||||
expect(markdown).not.toContain(".paseo/partials/");
|
||||
expect(markdown).not.toContain(".paseo/workflows/");
|
||||
expect(markdown).not.toContain(".paseo/hub.yml");
|
||||
expect(markdown).not.toMatch(/^triggers:/mu);
|
||||
expect(markdown).not.toMatch(/^steps:/mu);
|
||||
expect(markdown).not.toMatch(/^\s+allow_outputs:/mu);
|
||||
expect(markdown).not.toMatch(/^\s+uses:/mu);
|
||||
expect(markdown).not.toContain("paseo hub deploy [file]");
|
||||
});
|
||||
|
||||
it.each(["en", "zh-CN"] as const)(
|
||||
"resolves every internal /docs/hub link and heading anchor in %s",
|
||||
(locale) => {
|
||||
const docs = getDocs(locale);
|
||||
const headingsByHref = new Map(docs.map((doc) => [doc.href, headingIds(doc.content)]));
|
||||
const hubPages = docs.filter(
|
||||
(doc) => doc.href === "/docs/hub" || doc.href.startsWith("/docs/hub/"),
|
||||
);
|
||||
expect(hubPages.length).toBeGreaterThanOrEqual(25);
|
||||
|
||||
const broken: string[] = [];
|
||||
for (const doc of hubPages) {
|
||||
for (const match of doc.content.matchAll(/\]\((\/docs\/hub[^)\s]*)\)/gu)) {
|
||||
const target = match[1] ?? "";
|
||||
const [rawPath, hash] = target.split("#");
|
||||
const cleanPath = (rawPath ?? "").replace(/\/$/u, "");
|
||||
const headings = headingsByHref.get(cleanPath);
|
||||
if (!headings) {
|
||||
broken.push(`${doc.sourcePath} -> missing page ${target}`);
|
||||
} else if (hash && !headings.has(hash)) {
|
||||
broken.push(`${doc.sourcePath} -> missing anchor ${target}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
expect(broken).toEqual([]);
|
||||
},
|
||||
);
|
||||
|
||||
it("redirects removed legacy Hub workflow and hub-yml paths to current pages", () => {
|
||||
const redirects = [
|
||||
["/docs/hub/workflows", "/docs/hub/triggers"],
|
||||
["/docs/hub/configuration/hub-yml", "/docs/hub/configuration/reference"],
|
||||
] as const;
|
||||
|
||||
for (const [legacyPath, targetPath] of redirects) {
|
||||
expect(getDoc(targetPath.slice("/docs/".length), "en")).toBeDefined();
|
||||
expect(getDoc(targetPath.slice("/docs/".length), "zh-CN")).toBeDefined();
|
||||
for (const extension of ["", ".md"]) {
|
||||
expect(getLegacyDocsRedirect(`${legacyPath}${extension}`)).toBe(
|
||||
`${targetPath}${extension}`,
|
||||
);
|
||||
expect(getLegacyDocsRedirect(`${legacyPath}${extension}/`)).toBe(
|
||||
`${targetPath}${extension}`,
|
||||
);
|
||||
expect(getLegacyDocsRedirect(`${targetPath}${extension}`)).toBeUndefined();
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
function headingIds(content: string): Set<string> {
|
||||
return new Set(parseHeadings(content).map((heading) => heading.id));
|
||||
}
|
||||
|
||||
function yamlFences(markdown: string): readonly string[] {
|
||||
return [...markdown.matchAll(/```yaml\s*\n([\s\S]*?)```/gu)].map((match) => match[1] ?? "");
|
||||
}
|
||||
|
||||
@@ -50,7 +50,7 @@ Distribution: native apps for Mac, Windows, Linux, iOS, and Android; web app; Ho
|
||||
path: "/hub",
|
||||
title: "Paseo Hub",
|
||||
description:
|
||||
"Connect daemons and run GitHub, Slack, Discord, and Linear workflows through the hosted service or your own deployment.",
|
||||
"Connect daemons and automate agents from GitHub, Linear, Slack, Discord, schedules, and webhooks through the hosted service or your own deployment.",
|
||||
},
|
||||
{
|
||||
path: "/blog",
|
||||
@@ -104,7 +104,7 @@ Paseo 支持 Claude Code、Codex、GitHub Copilot、OpenCode、Pi、Antigravity
|
||||
path: "/hub",
|
||||
title: "Paseo Hub",
|
||||
description:
|
||||
"连接 daemon,通过托管服务或你自己的部署运行 GitHub、Slack、Discord 和 Linear 工作流。",
|
||||
"连接 daemon,通过托管服务或你自己的部署,使用 GitHub、Linear、Slack、Discord、定时任务和 webhook 自动化运行 Agent。",
|
||||
},
|
||||
{ path: "/blog", title: "博客", description: "Paseo 团队的动态和技术文章。" },
|
||||
{ path: "/privacy", title: "隐私", description: "隐私政策。" },
|
||||
|
||||
@@ -28,17 +28,28 @@ index 73466dd..8440ac9 100644
|
||||
|
||||
auto textSize = textLayoutManager_
|
||||
diff --git a/node_modules/@mattermost/react-native-paste-input/android/src/main/java/com/mattermost/pasteinputtext/PasteInputEditText.kt b/node_modules/@mattermost/react-native-paste-input/android/src/main/java/com/mattermost/pasteinputtext/PasteInputEditText.kt
|
||||
index 9e429b8..1d10014 100644
|
||||
index 1794b53..eca5e57 100644
|
||||
--- a/node_modules/@mattermost/react-native-paste-input/android/src/main/java/com/mattermost/pasteinputtext/PasteInputEditText.kt
|
||||
+++ b/node_modules/@mattermost/react-native-paste-input/android/src/main/java/com/mattermost/pasteinputtext/PasteInputEditText.kt
|
||||
@@ -36,2 +36,2 @@ class PasteInputEditText(context: ThemedReactContext) : ReactEditText(context) {
|
||||
@@ -33,8 +33,8 @@ class PasteInputEditText(context: ThemedReactContext) : ReactEditText(context) {
|
||||
return mOnPasteListener
|
||||
}
|
||||
|
||||
- override fun onCreateInputConnection(outAttrs: EditorInfo): InputConnection {
|
||||
- val ic = super.onCreateInputConnection(outAttrs)
|
||||
+ override fun onCreateInputConnection(outAttrs: EditorInfo): InputConnection? {
|
||||
+ val ic = super.onCreateInputConnection(outAttrs) ?: return null
|
||||
@@ -58 +58 @@ class PasteInputEditText(context: ThemedReactContext) : ReactEditText(context) {
|
||||
|
||||
EditorInfoCompat.setContentMimeTypes(outAttrs, arrayOf("*/*"))
|
||||
|
||||
@@ -55,6 +55,6 @@ class PasteInputEditText(context: ThemedReactContext) : ReactEditText(context) {
|
||||
true
|
||||
}
|
||||
|
||||
- return InputConnectionCompat.createWrapper(ic!!, outAttrs, callback)
|
||||
+ return InputConnectionCompat.createWrapper(ic, outAttrs, callback)
|
||||
}
|
||||
}
|
||||
diff --git a/node_modules/@mattermost/react-native-paste-input/lib/commonjs/PasteInput.js b/node_modules/@mattermost/react-native-paste-input/lib/commonjs/PasteInput.js
|
||||
index 51b9dfa..501badf 100644
|
||||
--- a/node_modules/@mattermost/react-native-paste-input/lib/commonjs/PasteInput.js
|
||||
@@ -108,10 +119,18 @@ index 51b9dfa..501badf 100644
|
||||
// For Android, PasteTextInput already handles everything internally
|
||||
// Just need to adapt the onPaste callback format
|
||||
diff --git a/node_modules/@mattermost/react-native-paste-input/lib/commonjs/PasteTextInput.js b/node_modules/@mattermost/react-native-paste-input/lib/commonjs/PasteTextInput.js
|
||||
index 5119e65..287216a 100644
|
||||
index 5119e65..77c3aea 100644
|
||||
--- a/node_modules/@mattermost/react-native-paste-input/lib/commonjs/PasteTextInput.js
|
||||
+++ b/node_modules/@mattermost/react-native-paste-input/lib/commonjs/PasteTextInput.js
|
||||
@@ -52,6 +52,7 @@ function InternalTextInput(props) {
|
||||
@@ -16,7 +16,6 @@ var _nullthrows = _interopRequireDefault(require("nullthrows"));
|
||||
var _jsxRuntime = require("react/jsx-runtime");
|
||||
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
|
||||
function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); }
|
||||
-const emptyFunctionThatReturnsTrue = () => true;
|
||||
function useMergeRefs(...refs) {
|
||||
return React.useCallback(current => {
|
||||
for (const ref of refs) {
|
||||
@@ -52,6 +51,7 @@ function InternalTextInput(props) {
|
||||
end: propsSelection.end ?? propsSelection.start
|
||||
}, [propsSelection]);
|
||||
const [mostRecentEventCount, setMostRecentEventCount] = React.useState(0);
|
||||
@@ -119,7 +138,7 @@ index 5119e65..287216a 100644
|
||||
const [lastNativeText, setLastNativeText] = React.useState(props.value);
|
||||
const [lastNativeSelectionState, setLastNativeSelection] = React.useState({
|
||||
selection: {
|
||||
@@ -103,7 +104,12 @@ function InternalTextInput(props) {
|
||||
@@ -103,7 +103,12 @@ function InternalTextInput(props) {
|
||||
Object.assign(instance, {
|
||||
clear() {
|
||||
if (inputRef.current != null) {
|
||||
@@ -133,7 +152,7 @@ index 5119e65..287216a 100644
|
||||
}
|
||||
},
|
||||
isFocused() {
|
||||
@@ -114,12 +120,12 @@ function InternalTextInput(props) {
|
||||
@@ -114,12 +119,12 @@ function InternalTextInput(props) {
|
||||
},
|
||||
setSelection(start, end) {
|
||||
if (inputRef.current != null) {
|
||||
@@ -148,7 +167,7 @@ index 5119e65..287216a 100644
|
||||
const ref = useMergeRefs(setLocalRef, props.forwardedRef);
|
||||
const _onChange = event => {
|
||||
const currentText = event.nativeEvent.text;
|
||||
@@ -128,6 +134,7 @@ function InternalTextInput(props) {
|
||||
@@ -128,6 +133,7 @@ function InternalTextInput(props) {
|
||||
if (inputRef.current == null) {
|
||||
return;
|
||||
}
|
||||
@@ -156,6 +175,14 @@ index 5119e65..287216a 100644
|
||||
setLastNativeText(currentText);
|
||||
setMostRecentEventCount(event.nativeEvent.eventCount);
|
||||
};
|
||||
@@ -294,7 +300,6 @@ function InternalTextInput(props) {
|
||||
onPaste: _onPaste,
|
||||
onScroll: _onScroll,
|
||||
onSelectionChange: _onSelectionChange,
|
||||
- onSelectionChangeShouldSetResponder: emptyFunctionThatReturnsTrue,
|
||||
placeholder: placeholder,
|
||||
style: _style,
|
||||
text: text,
|
||||
diff --git a/node_modules/@mattermost/react-native-paste-input/lib/module/PasteInput.js b/node_modules/@mattermost/react-native-paste-input/lib/module/PasteInput.js
|
||||
index 75fe015..1d3cd64 100644
|
||||
--- a/node_modules/@mattermost/react-native-paste-input/lib/module/PasteInput.js
|
||||
@@ -225,10 +252,18 @@ index 75fe015..1d3cd64 100644
|
||||
// For Android, PasteTextInput already handles everything internally
|
||||
// Just need to adapt the onPaste callback format
|
||||
diff --git a/node_modules/@mattermost/react-native-paste-input/lib/module/PasteTextInput.js b/node_modules/@mattermost/react-native-paste-input/lib/module/PasteTextInput.js
|
||||
index 39bd607..f2b1d2f 100644
|
||||
index 39bd607..832dcc2 100644
|
||||
--- a/node_modules/@mattermost/react-native-paste-input/lib/module/PasteTextInput.js
|
||||
+++ b/node_modules/@mattermost/react-native-paste-input/lib/module/PasteTextInput.js
|
||||
@@ -46,6 +46,7 @@ function InternalTextInput(props) {
|
||||
@@ -10,7 +10,6 @@ import usePressability from 'react-native/Libraries/Pressability/usePressability
|
||||
import flattenStyle from 'react-native/Libraries/StyleSheet/flattenStyle';
|
||||
import nullthrows from 'nullthrows';
|
||||
import { jsx as _jsx } from "react/jsx-runtime";
|
||||
-const emptyFunctionThatReturnsTrue = () => true;
|
||||
function useMergeRefs(...refs) {
|
||||
return React.useCallback(current => {
|
||||
for (const ref of refs) {
|
||||
@@ -46,6 +45,7 @@ function InternalTextInput(props) {
|
||||
end: propsSelection.end ?? propsSelection.start
|
||||
}, [propsSelection]);
|
||||
const [mostRecentEventCount, setMostRecentEventCount] = React.useState(0);
|
||||
@@ -236,7 +271,7 @@ index 39bd607..f2b1d2f 100644
|
||||
const [lastNativeText, setLastNativeText] = React.useState(props.value);
|
||||
const [lastNativeSelectionState, setLastNativeSelection] = React.useState({
|
||||
selection: {
|
||||
@@ -97,7 +98,12 @@ function InternalTextInput(props) {
|
||||
@@ -97,7 +97,12 @@ function InternalTextInput(props) {
|
||||
Object.assign(instance, {
|
||||
clear() {
|
||||
if (inputRef.current != null) {
|
||||
@@ -250,7 +285,7 @@ index 39bd607..f2b1d2f 100644
|
||||
}
|
||||
},
|
||||
isFocused() {
|
||||
@@ -108,12 +114,12 @@ function InternalTextInput(props) {
|
||||
@@ -108,12 +113,12 @@ function InternalTextInput(props) {
|
||||
},
|
||||
setSelection(start, end) {
|
||||
if (inputRef.current != null) {
|
||||
@@ -265,7 +300,7 @@ index 39bd607..f2b1d2f 100644
|
||||
const ref = useMergeRefs(setLocalRef, props.forwardedRef);
|
||||
const _onChange = event => {
|
||||
const currentText = event.nativeEvent.text;
|
||||
@@ -122,6 +128,7 @@ function InternalTextInput(props) {
|
||||
@@ -122,6 +127,7 @@ function InternalTextInput(props) {
|
||||
if (inputRef.current == null) {
|
||||
return;
|
||||
}
|
||||
@@ -273,6 +308,14 @@ index 39bd607..f2b1d2f 100644
|
||||
setLastNativeText(currentText);
|
||||
setMostRecentEventCount(event.nativeEvent.eventCount);
|
||||
};
|
||||
@@ -288,7 +294,6 @@ function InternalTextInput(props) {
|
||||
onPaste: _onPaste,
|
||||
onScroll: _onScroll,
|
||||
onSelectionChange: _onSelectionChange,
|
||||
- onSelectionChangeShouldSetResponder: emptyFunctionThatReturnsTrue,
|
||||
placeholder: placeholder,
|
||||
style: _style,
|
||||
text: text,
|
||||
diff --git a/node_modules/@mattermost/react-native-paste-input/src/PasteInput.tsx b/node_modules/@mattermost/react-native-paste-input/src/PasteInput.tsx
|
||||
index 12befab..0d23ca5 100644
|
||||
--- a/node_modules/@mattermost/react-native-paste-input/src/PasteInput.tsx
|
||||
@@ -342,10 +385,19 @@ index 12befab..0d23ca5 100644
|
||||
// For Android, PasteTextInput already handles everything internally
|
||||
// Just need to adapt the onPaste callback format
|
||||
diff --git a/node_modules/@mattermost/react-native-paste-input/src/PasteTextInput.tsx b/node_modules/@mattermost/react-native-paste-input/src/PasteTextInput.tsx
|
||||
index dcc4a2b..1156458 100644
|
||||
index dcc4a2b..7d10e11 100644
|
||||
--- a/node_modules/@mattermost/react-native-paste-input/src/PasteTextInput.tsx
|
||||
+++ b/node_modules/@mattermost/react-native-paste-input/src/PasteTextInput.tsx
|
||||
@@ -84,6 +84,7 @@ function InternalTextInput(props: PasteInputProps): React.ReactNode {
|
||||
@@ -27,8 +27,6 @@ import usePressability from 'react-native/Libraries/Pressability/usePressability
|
||||
import flattenStyle from 'react-native/Libraries/StyleSheet/flattenStyle';
|
||||
import nullthrows from 'nullthrows';
|
||||
|
||||
-const emptyFunctionThatReturnsTrue = () => true;
|
||||
-
|
||||
function useMergeRefs<Instance>(
|
||||
...refs: ReadonlyArray<React.ForwardedRef<Instance> | null | undefined>
|
||||
): (arg0: Instance | null) => void {
|
||||
@@ -84,6 +82,7 @@ function InternalTextInput(props: PasteInputProps): React.ReactNode {
|
||||
|
||||
const [mostRecentEventCount, setMostRecentEventCount] =
|
||||
React.useState<number>(0);
|
||||
@@ -353,7 +405,7 @@ index dcc4a2b..1156458 100644
|
||||
const [lastNativeText, setLastNativeText] = React.useState<
|
||||
string | undefined
|
||||
>(props.value);
|
||||
@@ -181,13 +182,24 @@ function InternalTextInput(props: PasteInputProps): React.ReactNode {
|
||||
@@ -181,13 +180,24 @@ function InternalTextInput(props: PasteInputProps): React.ReactNode {
|
||||
if (inputRef.current != null) {
|
||||
Commands.setTextAndSelection(
|
||||
inputRef.current,
|
||||
@@ -379,7 +431,7 @@ index dcc4a2b..1156458 100644
|
||||
isFocused(): boolean {
|
||||
return (
|
||||
TextInputState.currentlyFocusedInput() ===
|
||||
@@ -203,7 +215,7 @@ function InternalTextInput(props: PasteInputProps): React.ReactNode {
|
||||
@@ -203,7 +213,7 @@ function InternalTextInput(props: PasteInputProps): React.ReactNode {
|
||||
if (inputRef.current != null) {
|
||||
Commands.setTextAndSelection(
|
||||
inputRef.current,
|
||||
@@ -388,7 +440,7 @@ index dcc4a2b..1156458 100644
|
||||
null,
|
||||
start,
|
||||
end
|
||||
@@ -213,7 +225,7 @@ function InternalTextInput(props: PasteInputProps): React.ReactNode {
|
||||
@@ -213,7 +223,7 @@ function InternalTextInput(props: PasteInputProps): React.ReactNode {
|
||||
});
|
||||
}
|
||||
},
|
||||
@@ -397,7 +449,7 @@ index dcc4a2b..1156458 100644
|
||||
);
|
||||
|
||||
const ref = useMergeRefs<PasteTextInputInstance>(
|
||||
@@ -232,6 +244,7 @@ function InternalTextInput(props: PasteInputProps): React.ReactNode {
|
||||
@@ -232,6 +242,7 @@ function InternalTextInput(props: PasteInputProps): React.ReactNode {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -405,3 +457,11 @@ index dcc4a2b..1156458 100644
|
||||
setLastNativeText(currentText);
|
||||
setMostRecentEventCount(event.nativeEvent.eventCount);
|
||||
};
|
||||
@@ -445,7 +456,6 @@ function InternalTextInput(props: PasteInputProps): React.ReactNode {
|
||||
onPaste={_onPaste}
|
||||
onScroll={_onScroll}
|
||||
onSelectionChange={_onSelectionChange}
|
||||
- onSelectionChangeShouldSetResponder={emptyFunctionThatReturnsTrue}
|
||||
placeholder={placeholder}
|
||||
style={_style}
|
||||
text={text}
|
||||
|
||||
@@ -0,0 +1,223 @@
|
||||
diff --git a/node_modules/react-native/Libraries/Renderer/implementations/ReactFabric-dev.js b/node_modules/react-native/Libraries/Renderer/implementations/ReactFabric-dev.js
|
||||
index daab0e3..d3a629c 100644
|
||||
--- a/node_modules/react-native/Libraries/Renderer/implementations/ReactFabric-dev.js
|
||||
+++ b/node_modules/react-native/Libraries/Renderer/implementations/ReactFabric-dev.js
|
||||
@@ -16214,12 +16214,21 @@ __DEV__ &&
|
||||
else if (
|
||||
"topTouchEnd" === topLevelType ||
|
||||
"topTouchCancel" === topLevelType
|
||||
- )
|
||||
- if (
|
||||
- (nativeEvent.changedTouches.forEach(recordTouchEnd),
|
||||
- (touchHistory.numberActiveTouches = nativeEvent.touches.length),
|
||||
- 1 === touchHistory.numberActiveTouches)
|
||||
- ) {
|
||||
+ ) {
|
||||
+ nativeEvent.changedTouches.forEach(recordTouchEnd);
|
||||
+ touchHistory.numberActiveTouches = nativeEvent.touches.length;
|
||||
+ if (0 === touchHistory.numberActiveTouches) {
|
||||
+ for (
|
||||
+ topLevelType = 0;
|
||||
+ topLevelType < touchBank.length;
|
||||
+ topLevelType++
|
||||
+ )
|
||||
+ if (
|
||||
+ ((nativeEvent = touchBank[topLevelType]),
|
||||
+ null != nativeEvent && nativeEvent.touchActive)
|
||||
+ )
|
||||
+ nativeEvent.touchActive = !1;
|
||||
+ } else if (1 === touchHistory.numberActiveTouches) {
|
||||
for (
|
||||
topLevelType = 0;
|
||||
topLevelType < touchBank.length;
|
||||
@@ -16236,6 +16245,7 @@ __DEV__ &&
|
||||
(null != topLevelType && topLevelType.touchActive) ||
|
||||
console.error("Cannot find single active touch.");
|
||||
}
|
||||
+ }
|
||||
},
|
||||
touchHistory: touchHistory
|
||||
},
|
||||
@@ -16314,12 +16324,18 @@ __DEV__ &&
|
||||
nativeEvent,
|
||||
nativeEventTarget
|
||||
) {
|
||||
- if (isStartish(topLevelType)) trackedTouchCount += 1;
|
||||
+ if (isStartish(topLevelType))
|
||||
+ trackedTouchCount =
|
||||
+ nativeEvent && Array.isArray(nativeEvent.touches)
|
||||
+ ? nativeEvent.touches.length
|
||||
+ : trackedTouchCount + 1;
|
||||
else if (
|
||||
"topTouchEnd" === topLevelType ||
|
||||
"topTouchCancel" === topLevelType
|
||||
)
|
||||
- if (0 <= trackedTouchCount) --trackedTouchCount;
|
||||
+ if (nativeEvent && Array.isArray(nativeEvent.touches))
|
||||
+ trackedTouchCount = nativeEvent.touches.length;
|
||||
+ else if (0 <= trackedTouchCount) --trackedTouchCount;
|
||||
else
|
||||
return (
|
||||
console.warn(
|
||||
diff --git a/node_modules/react-native/Libraries/Renderer/implementations/ReactFabric-prod.js b/node_modules/react-native/Libraries/Renderer/implementations/ReactFabric-prod.js
|
||||
index 2625bf6..3d85e32 100644
|
||||
--- a/node_modules/react-native/Libraries/Renderer/implementations/ReactFabric-prod.js
|
||||
+++ b/node_modules/react-native/Libraries/Renderer/implementations/ReactFabric-prod.js
|
||||
@@ -546,12 +546,21 @@ var instrumentationCallback,
|
||||
else if (
|
||||
"topTouchEnd" === topLevelType ||
|
||||
"topTouchCancel" === topLevelType
|
||||
- )
|
||||
- if (
|
||||
- (nativeEvent.changedTouches.forEach(recordTouchEnd),
|
||||
- (touchHistory.numberActiveTouches = nativeEvent.touches.length),
|
||||
- 1 === touchHistory.numberActiveTouches)
|
||||
- )
|
||||
+ ) {
|
||||
+ nativeEvent.changedTouches.forEach(recordTouchEnd);
|
||||
+ touchHistory.numberActiveTouches = nativeEvent.touches.length;
|
||||
+ if (0 === touchHistory.numberActiveTouches) {
|
||||
+ for (
|
||||
+ topLevelType = 0;
|
||||
+ topLevelType < touchBank.length;
|
||||
+ topLevelType++
|
||||
+ )
|
||||
+ if (
|
||||
+ ((nativeEvent = touchBank[topLevelType]),
|
||||
+ null != nativeEvent && nativeEvent.touchActive)
|
||||
+ )
|
||||
+ nativeEvent.touchActive = !1;
|
||||
+ } else if (1 === touchHistory.numberActiveTouches)
|
||||
for (
|
||||
topLevelType = 0;
|
||||
topLevelType < touchBank.length;
|
||||
@@ -564,6 +573,7 @@ var instrumentationCallback,
|
||||
touchHistory.indexOfSingleActiveTouch = topLevelType;
|
||||
break;
|
||||
}
|
||||
+ }
|
||||
},
|
||||
touchHistory: touchHistory
|
||||
};
|
||||
@@ -745,12 +755,18 @@ var ResponderEventPlugin = {
|
||||
nativeEvent,
|
||||
nativeEventTarget
|
||||
) {
|
||||
- if (isStartish(topLevelType)) trackedTouchCount += 1;
|
||||
+ if (isStartish(topLevelType))
|
||||
+ trackedTouchCount =
|
||||
+ nativeEvent && Array.isArray(nativeEvent.touches)
|
||||
+ ? nativeEvent.touches.length
|
||||
+ : trackedTouchCount + 1;
|
||||
else if (
|
||||
"topTouchEnd" === topLevelType ||
|
||||
"topTouchCancel" === topLevelType
|
||||
)
|
||||
- if (0 <= trackedTouchCount) --trackedTouchCount;
|
||||
+ if (nativeEvent && Array.isArray(nativeEvent.touches))
|
||||
+ trackedTouchCount = nativeEvent.touches.length;
|
||||
+ else if (0 <= trackedTouchCount) --trackedTouchCount;
|
||||
else return null;
|
||||
ResponderTouchHistoryStore.recordTouchTrack(topLevelType, nativeEvent);
|
||||
if (
|
||||
diff --git a/node_modules/react-native/Libraries/Renderer/implementations/ReactFabric-profiling.js b/node_modules/react-native/Libraries/Renderer/implementations/ReactFabric-profiling.js
|
||||
index 544c754..4d5ec08 100644
|
||||
--- a/node_modules/react-native/Libraries/Renderer/implementations/ReactFabric-profiling.js
|
||||
+++ b/node_modules/react-native/Libraries/Renderer/implementations/ReactFabric-profiling.js
|
||||
@@ -611,12 +611,21 @@ var instrumentationCallback,
|
||||
else if (
|
||||
"topTouchEnd" === topLevelType ||
|
||||
"topTouchCancel" === topLevelType
|
||||
- )
|
||||
- if (
|
||||
- (nativeEvent.changedTouches.forEach(recordTouchEnd),
|
||||
- (touchHistory.numberActiveTouches = nativeEvent.touches.length),
|
||||
- 1 === touchHistory.numberActiveTouches)
|
||||
- )
|
||||
+ ) {
|
||||
+ nativeEvent.changedTouches.forEach(recordTouchEnd);
|
||||
+ touchHistory.numberActiveTouches = nativeEvent.touches.length;
|
||||
+ if (0 === touchHistory.numberActiveTouches) {
|
||||
+ for (
|
||||
+ topLevelType = 0;
|
||||
+ topLevelType < touchBank.length;
|
||||
+ topLevelType++
|
||||
+ )
|
||||
+ if (
|
||||
+ ((nativeEvent = touchBank[topLevelType]),
|
||||
+ null != nativeEvent && nativeEvent.touchActive)
|
||||
+ )
|
||||
+ nativeEvent.touchActive = !1;
|
||||
+ } else if (1 === touchHistory.numberActiveTouches)
|
||||
for (
|
||||
topLevelType = 0;
|
||||
topLevelType < touchBank.length;
|
||||
@@ -629,6 +638,7 @@ var instrumentationCallback,
|
||||
touchHistory.indexOfSingleActiveTouch = topLevelType;
|
||||
break;
|
||||
}
|
||||
+ }
|
||||
},
|
||||
touchHistory: touchHistory
|
||||
};
|
||||
@@ -810,12 +820,18 @@ var ResponderEventPlugin = {
|
||||
nativeEvent,
|
||||
nativeEventTarget
|
||||
) {
|
||||
- if (isStartish(topLevelType)) trackedTouchCount += 1;
|
||||
+ if (isStartish(topLevelType))
|
||||
+ trackedTouchCount =
|
||||
+ nativeEvent && Array.isArray(nativeEvent.touches)
|
||||
+ ? nativeEvent.touches.length
|
||||
+ : trackedTouchCount + 1;
|
||||
else if (
|
||||
"topTouchEnd" === topLevelType ||
|
||||
"topTouchCancel" === topLevelType
|
||||
)
|
||||
- if (0 <= trackedTouchCount) --trackedTouchCount;
|
||||
+ if (nativeEvent && Array.isArray(nativeEvent.touches))
|
||||
+ trackedTouchCount = nativeEvent.touches.length;
|
||||
+ else if (0 <= trackedTouchCount) --trackedTouchCount;
|
||||
else return null;
|
||||
ResponderTouchHistoryStore.recordTouchTrack(topLevelType, nativeEvent);
|
||||
if (
|
||||
diff --git a/node_modules/react-native/src/private/renderer/events/ReactNativeResponder.js b/node_modules/react-native/src/private/renderer/events/ReactNativeResponder.js
|
||||
index da29336..7167a2f 100644
|
||||
--- a/node_modules/react-native/src/private/renderer/events/ReactNativeResponder.js
|
||||
+++ b/node_modules/react-native/src/private/renderer/events/ReactNativeResponder.js
|
||||
@@ -560,9 +560,13 @@ export function processResponderEvent(
|
||||
): void {
|
||||
// Track touch count
|
||||
if (isStartish(topLevelType)) {
|
||||
- trackedTouchCount += 1;
|
||||
+ trackedTouchCount = Array.isArray(nativeEvent.touches)
|
||||
+ ? nativeEvent.touches.length
|
||||
+ : trackedTouchCount + 1;
|
||||
} else if (isEndish(topLevelType)) {
|
||||
- if (trackedTouchCount >= 0) {
|
||||
+ if (Array.isArray(nativeEvent.touches)) {
|
||||
+ trackedTouchCount = nativeEvent.touches.length;
|
||||
+ } else if (trackedTouchCount >= 0) {
|
||||
trackedTouchCount -= 1;
|
||||
} else {
|
||||
if (__DEV__) {
|
||||
diff --git a/node_modules/react-native/src/private/renderer/events/ResponderTouchHistoryStore.js b/node_modules/react-native/src/private/renderer/events/ResponderTouchHistoryStore.js
|
||||
index c0b4d12..b4aab95 100644
|
||||
--- a/node_modules/react-native/src/private/renderer/events/ResponderTouchHistoryStore.js
|
||||
+++ b/node_modules/react-native/src/private/renderer/events/ResponderTouchHistoryStore.js
|
||||
@@ -234,7 +234,14 @@ const ResponderTouchHistoryStore = {
|
||||
} else if (isEndish(topLevelType)) {
|
||||
nativeEvent.changedTouches.forEach(recordTouchEnd);
|
||||
touchHistory.numberActiveTouches = nativeEvent.touches.length;
|
||||
- if (touchHistory.numberActiveTouches === 1) {
|
||||
+ if (touchHistory.numberActiveTouches === 0) {
|
||||
+ for (let i = 0; i < touchBank.length; i++) {
|
||||
+ const touchTrackToCheck = touchBank[i];
|
||||
+ if (touchTrackToCheck != null && touchTrackToCheck.touchActive) {
|
||||
+ touchTrackToCheck.touchActive = false;
|
||||
+ }
|
||||
+ }
|
||||
+ } else if (touchHistory.numberActiveTouches === 1) {
|
||||
for (let i = 0; i < touchBank.length; i++) {
|
||||
const touchTrackToCheck = touchBank[i];
|
||||
if (touchTrackToCheck != null && touchTrackToCheck.touchActive) {
|
||||
@@ -152,92 +152,18 @@ index 8d78aea..b84d19e 100644
|
||||
viewGroup: ViewGroup,
|
||||
coords: FloatArray,
|
||||
diff --git a/node_modules/react-native-gesture-handler/android/src/main/java/com/swmansion/gesturehandler/react/RNGestureHandlerRootHelper.kt b/node_modules/react-native-gesture-handler/android/src/main/java/com/swmansion/gesturehandler/react/RNGestureHandlerRootHelper.kt
|
||||
index 629c155..2efd508 100644
|
||||
index 629c155..dc0790d 100644
|
||||
--- a/node_modules/react-native-gesture-handler/android/src/main/java/com/swmansion/gesturehandler/react/RNGestureHandlerRootHelper.kt
|
||||
+++ b/node_modules/react-native-gesture-handler/android/src/main/java/com/swmansion/gesturehandler/react/RNGestureHandlerRootHelper.kt
|
||||
@@ -19,7 +19,9 @@ class RNGestureHandlerRootHelper(private val context: ReactContext, wrappedView:
|
||||
@@ -19,6 +19,7 @@ class RNGestureHandlerRootHelper(private val context: ReactContext, wrappedView:
|
||||
private val jsGestureHandler: GestureHandler?
|
||||
val rootView: ViewGroup
|
||||
private var shouldIntercept = false
|
||||
+ private var wasIntercepting = false
|
||||
private var passingTouch = false
|
||||
+ private var lastTouch: MotionEvent? = null
|
||||
|
||||
init {
|
||||
UiThreadUtil.assertOnUiThread()
|
||||
@@ -47,6 +49,7 @@ class RNGestureHandlerRootHelper(private val context: ReactContext, wrappedView:
|
||||
}
|
||||
|
||||
fun tearDown() {
|
||||
+ clearLastTouch()
|
||||
Log.i(
|
||||
ReactConstants.TAG,
|
||||
"[GESTURE HANDLER] Tearing down gesture handler registered for root view $rootView",
|
||||
@@ -90,17 +93,46 @@ class RNGestureHandlerRootHelper(private val context: ReactContext, wrappedView:
|
||||
|
||||
override fun onCancel() {
|
||||
shouldIntercept = true
|
||||
- val time = SystemClock.uptimeMillis()
|
||||
- val event = MotionEvent.obtain(time, time, MotionEvent.ACTION_CANCEL, 0f, 0f, 0).apply {
|
||||
- action = MotionEvent.ACTION_CANCEL
|
||||
- }
|
||||
if (rootView is RootView) {
|
||||
- rootView.onChildStartedNativeGesture(rootView, event)
|
||||
+ val cancel = createReactCancelEvent()
|
||||
+ try {
|
||||
+ rootView.onChildStartedNativeGesture(rootView, cancel)
|
||||
+ } finally {
|
||||
+ cancel.recycle()
|
||||
+ clearLastTouch()
|
||||
+ }
|
||||
}
|
||||
- event.recycle()
|
||||
}
|
||||
}
|
||||
|
||||
+ private fun clearLastTouch() {
|
||||
+ lastTouch?.recycle()
|
||||
+ lastTouch = null
|
||||
+ }
|
||||
+
|
||||
+ private fun createReactCancelEvent(): MotionEvent {
|
||||
+ val now = SystemClock.uptimeMillis()
|
||||
+ val touch = lastTouch ?: return MotionEvent.obtain(now, now, MotionEvent.ACTION_CANCEL, 0f, 0f, 0)
|
||||
+ // The enclosing React root already dispatched this event before it reached the
|
||||
+ // gesture handler. A POINTER_UP is still in MotionEvent but already ended in JS.
|
||||
+ val lifted = if (touch.actionMasked == MotionEvent.ACTION_POINTER_UP) touch.actionIndex else -1
|
||||
+ val count = touch.pointerCount - if (lifted >= 0) 1 else 0
|
||||
+ val properties = Array(count) { MotionEvent.PointerProperties() }
|
||||
+ val coords = Array(count) { MotionEvent.PointerCoords() }
|
||||
+ var index = 0
|
||||
+ for (pointer in 0 until touch.pointerCount) {
|
||||
+ if (pointer == lifted) continue
|
||||
+ touch.getPointerProperties(pointer, properties[index])
|
||||
+ touch.getPointerCoords(pointer, coords[index])
|
||||
+ index++
|
||||
+ }
|
||||
+ return MotionEvent.obtain(
|
||||
+ touch.downTime, now, MotionEvent.ACTION_CANCEL, count, properties, coords,
|
||||
+ touch.metaState, touch.buttonState, touch.xPrecision, touch.yPrecision,
|
||||
+ touch.deviceId, touch.edgeFlags, touch.source, touch.flags,
|
||||
+ )
|
||||
+ }
|
||||
+
|
||||
fun requestDisallowInterceptTouchEvent() {
|
||||
// If this method gets called it means that some native view is attempting to grab lock for
|
||||
// touch event delivery. In that case we cancel all gesture recognizers
|
||||
@@ -115,9 +147,25 @@ class RNGestureHandlerRootHelper(private val context: ReactContext, wrappedView:
|
||||
// We mark `mPassingTouch` before we get into `mOrchestrator.onTouchEvent` so that we can tell
|
||||
// if `requestDisallow` has been called as a result of a normal gesture handling process or
|
||||
// as a result of one of the gesture handlers activating
|
||||
+ // Keep the stream for recognizers that activate between events (e.g. long press).
|
||||
+ // Once native handling begins, React no longer receives the remaining touches.
|
||||
+ if (!event.isHoverAction() && (!shouldIntercept || event.actionMasked == MotionEvent.ACTION_DOWN)) {
|
||||
+ clearLastTouch()
|
||||
+ if (event.actionMasked != MotionEvent.ACTION_UP && event.actionMasked != MotionEvent.ACTION_CANCEL) {
|
||||
+ lastTouch = MotionEvent.obtainNoHistory(event)
|
||||
+ }
|
||||
+ }
|
||||
@@ -118,6 +119,14 @@ class RNGestureHandlerRootHelper(private val context: ReactContext, wrappedView:
|
||||
passingTouch = true
|
||||
orchestrator!!.onTouchEvent(event)
|
||||
passingTouch = false
|
||||
|
||||
@@ -213,3 +213,156 @@ describe("installation", () => {
|
||||
).resolves.toEqual({ status: "not_installed" });
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps a turn open for backgrounded run_command calls but not IsDaemon commands", async () => {
|
||||
const { directory, launch } = await launchAgent(`
|
||||
const { createInterface } = require("node:readline");
|
||||
const send = (message) => process.stdout.write(JSON.stringify({ jsonrpc: "2.0", ...message }) + "\\n");
|
||||
let turn = 0;
|
||||
createInterface({ input: process.stdin }).on("line", (line) => {
|
||||
const { id, method, params } = JSON.parse(line);
|
||||
switch (method) {
|
||||
case "initialize":
|
||||
send({ id, result: { protocolVersion: 1, agentCapabilities: {} } });
|
||||
break;
|
||||
case "session/new":
|
||||
send({ id, result: { sessionId: "agy-session", configOptions: [
|
||||
{ id: "mode", name: "Mode", category: "mode", type: "select", currentValue: "default",
|
||||
options: [{ value: "default", name: "Default" }] },
|
||||
] } });
|
||||
break;
|
||||
case "session/prompt":
|
||||
turn += 1;
|
||||
if (turn === 1) {
|
||||
send({ method: "session/update", params: { sessionId: params.sessionId, update: {
|
||||
sessionUpdate: "tool_call", toolCallId: "daemon-1", name: "run_command",
|
||||
title: "Dev server", status: "in_progress", rawInput: { CommandLine: "npm run dev", IsDaemon: true },
|
||||
} } });
|
||||
send({ id, result: { stopReason: "end_turn" } });
|
||||
} else {
|
||||
send({ method: "session/update", params: { sessionId: params.sessionId, update: {
|
||||
sessionUpdate: "tool_call", toolCallId: "bg-1", name: "run_command",
|
||||
title: "Background build", status: "in_progress", rawInput: { CommandLine: "sleep 1" },
|
||||
} } });
|
||||
send({ id, result: { stopReason: "end_turn" } });
|
||||
setTimeout(() => {
|
||||
send({ method: "session/update", params: { sessionId: params.sessionId, update: {
|
||||
sessionUpdate: "tool_call_update", toolCallId: "bg-1", status: "completed",
|
||||
} } });
|
||||
send({ method: "session/update", params: { sessionId: params.sessionId, update: {
|
||||
sessionUpdate: "agent_message_chunk", content: { type: "text", text: "Build finished." },
|
||||
} } });
|
||||
send({ method: "session/update", params: { sessionId: params.sessionId, update: {
|
||||
sessionUpdate: "usage_update", used: 50, size: 1000,
|
||||
} } });
|
||||
}, 80);
|
||||
}
|
||||
break;
|
||||
case "session/close":
|
||||
send({ id, result: {} });
|
||||
break;
|
||||
}
|
||||
});
|
||||
`);
|
||||
const provider = createAntigravityProvider();
|
||||
const connection = await provider.connect({
|
||||
launch,
|
||||
versions: [1],
|
||||
capabilities: ["prompt.message"],
|
||||
});
|
||||
const events: ProviderEvent[] = [];
|
||||
connection.onEvent((event) => events.push(event));
|
||||
try {
|
||||
await connection.send({
|
||||
type: "session.open",
|
||||
requestId: "open-1",
|
||||
sessionId: "agy-test",
|
||||
history: "skip",
|
||||
config: {
|
||||
cwd: directory,
|
||||
env: {},
|
||||
mcpServers: {},
|
||||
settings: {},
|
||||
persist: false,
|
||||
},
|
||||
});
|
||||
await expect
|
||||
.poll(() => events.find((event) => event.type === "session.ready"), { timeout: 3_000 })
|
||||
.toBeDefined();
|
||||
|
||||
// Turn 1: IsDaemon: true completes immediately on end_turn.
|
||||
await connection.send({
|
||||
type: "session.prompt",
|
||||
sessionId: "agy-test",
|
||||
prompt: {
|
||||
clientMessageId: "daemon-turn",
|
||||
delivery: "auto",
|
||||
input: { type: "message", content: [{ type: "text", text: "start dev server" }] },
|
||||
},
|
||||
});
|
||||
await expect
|
||||
.poll(
|
||||
() =>
|
||||
events.find(
|
||||
(event) =>
|
||||
event.type === "session.turn" &&
|
||||
event.turnId === "acp:daemon-turn" &&
|
||||
event.state === "completed",
|
||||
),
|
||||
{ timeout: 3_000 },
|
||||
)
|
||||
.toBeDefined();
|
||||
|
||||
// Turn 2: non-daemon background command keeps turn open until completion + reply + usage_update.
|
||||
await connection.send({
|
||||
type: "session.prompt",
|
||||
sessionId: "agy-test",
|
||||
prompt: {
|
||||
clientMessageId: "bg-turn",
|
||||
delivery: "auto",
|
||||
input: { type: "message", content: [{ type: "text", text: "run build" }] },
|
||||
},
|
||||
});
|
||||
await expect
|
||||
.poll(
|
||||
() =>
|
||||
events.find(
|
||||
(event) =>
|
||||
event.type === "timeline.item" &&
|
||||
event.item.type === "tool_call" &&
|
||||
event.item.id === "bg-1" &&
|
||||
event.item.status === "running",
|
||||
),
|
||||
{ timeout: 3_000 },
|
||||
)
|
||||
.toBeDefined();
|
||||
expect(
|
||||
events.some(
|
||||
(event) =>
|
||||
event.type === "session.turn" &&
|
||||
event.turnId === "acp:bg-turn" &&
|
||||
event.state === "completed",
|
||||
),
|
||||
).toBe(false);
|
||||
await expect
|
||||
.poll(
|
||||
() =>
|
||||
events.find(
|
||||
(event) =>
|
||||
event.type === "session.turn" &&
|
||||
event.turnId === "acp:bg-turn" &&
|
||||
event.state === "completed",
|
||||
),
|
||||
{ timeout: 3_000 },
|
||||
)
|
||||
.toBeDefined();
|
||||
expect(events).toContainEqual(
|
||||
expect.objectContaining({
|
||||
type: "timeline.item",
|
||||
item: expect.objectContaining({ type: "assistant_message", text: "Build finished." }),
|
||||
}),
|
||||
);
|
||||
} finally {
|
||||
await connection.close();
|
||||
}
|
||||
});
|
||||
|
||||
@@ -95,6 +95,16 @@ export function createAntigravityProvider(): ProviderRegistration {
|
||||
acpOptions: {
|
||||
waitForInitialCommands: true,
|
||||
loadReplayQuietPeriodMs: 200,
|
||||
// COMPAT(antigravityAcpV1DeferredTurn): added in v0.18.0, remove once Antigravity CLI supports ACP v2 state_update.
|
||||
deferTurnOnRunningTools: {
|
||||
keepsTurnOpen(toolCall) {
|
||||
const input = toolCall.input;
|
||||
if (typeof input === "object" && input !== null && !Array.isArray(input)) {
|
||||
return input.IsDaemon !== true;
|
||||
}
|
||||
return true;
|
||||
},
|
||||
},
|
||||
autoAcceptMode: {
|
||||
mode: {
|
||||
id: "full-access",
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user