Compare commits

..
Author SHA1 Message Date
Mohamed Boudra 7eec266f50 fix(usage): keep window shorthands visible in sidebar usage row (#10274)
* fix(usage): keep window shorthands visible in sidebar usage row

Antigravity usage windows emitted full group names and raw period strings (for example "Gemini Models weekly") in shortLabel, which pushed the measured labels row past the maximum sidebar width. On the app side, choosePinnedUsageLayout dropped every window on the row straight to bare percentages whenever any scoped short label overflowed the row.

Normalize Antigravity shortLabel periods (weekly -> wk, monthly -> mo) and shorten group prefixes, and add a compact period-shorthand tier between full labels and bare percentages in PinnedUsageTrigger so tight sidebar rows keep shorthands like 5h and wk visible instead of collapsing to percentages alone.

* test(usage): expect compact shorthands in usage modal sidebar summary

With the compact period-shorthand tier between full labels and bare percentages, three Weekly windows now render as "31% wk", "20% wk", "12% wk" in the 320px sidebar instead of dropping to bare percentages.
2026-11-20 13:58:45 +07:00
23 changed files with 368 additions and 2813 deletions
+2 -2
View File
@@ -233,8 +233,8 @@ test.describe("usage modal", () => {
],
});
await gotoAppShell(page);
// Three windows leave no room for labels in the summary, so it reads percents.
await expectPinnedUsage(page, ["31%", "20%", "12%"]);
// Three Weekly labels overflow the summary, so it falls back to compact shorthands.
await expectPinnedUsage(page, ["31% wk", "20% wk", "12% wk"]);
await openUsageFromItem(page);
await expectUsageCardOrder(page, ["alpha:a", "beta:home", "beta:work"]);
@@ -40,6 +40,7 @@ import {
usageModal,
installTallUsageSource,
} from "../support/helpers/usage-sidebar-item";
import { seedDockedSidebarWidth } from "../support/helpers/sidebar-footer-overflow";
import { seedSidebarFooterPreferences } from "../support/helpers/sidebar-nav-settings";
import { waitForSettledPosition } from "../support/helpers/sheet-layout";
import { createTempGitRepo } from "../support/helpers/workspace";
@@ -577,3 +578,97 @@ test("visible usage summary requests reports on load", async ({ page }) => {
await expectPinnedUsage(page, ["31% 5h", "54% wk", "7% 5h", "12% wk"]);
expect(usage.listRequests()).toHaveLength(1);
});
test("sidebar usage falls back to period shorthands before dropping all labels", async ({
page,
}) => {
test.setTimeout(120_000);
const [claude, codex] = claudeAndCodexReports();
const fetchedAt = new Date().toISOString();
await installUsageReportsFixture(page, {
lists: [
() => [
{
...codex!,
report: {
status: "available",
windows: [
{ id: "weekly", label: "Weekly", shortLabel: "wk", summary: true, usedPct: 97 },
],
},
},
{
...claude!,
report: {
status: "available",
windows: [
{ id: "five_hour", label: "Session", shortLabel: "5h", summary: true, usedPct: 100 },
{ id: "weekly", label: "Weekly", shortLabel: "wk", summary: true, usedPct: 14 },
{
id: "weekly_model_opus",
label: "Weekly · Opus",
shortLabel: "wk Opus",
summary: true,
usedPct: 22,
},
],
},
},
{
id: "antigravity:default",
account: {},
fetchedAt,
sourceId: "antigravity",
sourceLabel: "Antigravity",
report: {
status: "available",
windows: [
{
id: "gemini-weekly",
label: "Gemini Models · Weekly",
shortLabel: "Gemini wk",
summary: true,
usedPct: 6,
},
{
id: "gemini-5h",
label: "Gemini Models · 5h",
shortLabel: "Gemini 5h",
summary: true,
usedPct: 20,
},
],
},
},
],
],
});
await seedSidebarFooterPreferences(page, [{ key: "usage", visible: true }]);
await seedDockedSidebarWidth(page, 432);
await page.setViewportSize(WIDE);
await gotoAppShell(page);
await expectPinnedUsage(page, ["6% wk", "20% 5h", "100% 5h", "14% wk", "22% wk", "97% wk"]);
const handle = page.getByTestId("left-sidebar-resize-handle");
const dragSidebarTo = async (targetX: number) => {
const box = (await handle.boundingBox())!;
await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2);
await page.mouse.down();
await page.mouse.move(targetX, box.y + box.height / 2, { steps: 10 });
await page.mouse.up();
};
await dragSidebarTo(600);
await expectPinnedUsage(page, [
"6% Gemini wk",
"20% Gemini 5h",
"100% 5h",
"14% wk",
"22% wk Opus",
"97% wk",
]);
await dragSidebarTo(300);
await expectPinnedUsage(page, ["6%", "20%", "100%", "14%", "22%", "97%"]);
});
+65 -1
View File
@@ -53,7 +53,7 @@ function preferences(
}
describe("choosePinnedUsageLayout", () => {
const widths = { labelsWidth: 200, percentsWidth: 120, windowCount: 2 };
const widths = { labelsWidth: 200, compactWidth: 200, percentsWidth: 120, windowCount: 2 };
it("shows meters only when every window's meter fits beside the labels", () => {
expect(choosePinnedUsageLayout({ ...widths, available: 240 })).toBe("meters");
@@ -64,11 +64,27 @@ describe("choosePinnedUsageLayout", () => {
expect(choosePinnedUsageLayout({ ...widths, available: 199 })).toBe("percents");
});
it("uses compact period shorthands when full labels overflow but compact labels fit", () => {
const scoped = { labelsWidth: 485, compactWidth: 388, percentsWidth: 268, windowCount: 6 };
expect(choosePinnedUsageLayout({ ...scoped, available: 485 })).toBe("labels");
expect(choosePinnedUsageLayout({ ...scoped, available: 399 })).toBe("compact");
expect(choosePinnedUsageLayout({ ...scoped, available: 388 })).toBe("compact");
expect(choosePinnedUsageLayout({ ...scoped, available: 387 })).toBe("percents");
});
it("skips compact mode when no window has a compact label", () => {
const noPeriod = { labelsWidth: 220, compactWidth: 120, percentsWidth: 120, windowCount: 2 };
expect(choosePinnedUsageLayout({ ...noPeriod, available: 180 })).toBe("percents");
});
it("shows labels until the widths are measured", () => {
expect(choosePinnedUsageLayout({ ...widths, available: null })).toBe("labels");
expect(choosePinnedUsageLayout({ ...widths, available: 999, labelsWidth: null })).toBe(
"labels",
);
expect(choosePinnedUsageLayout({ ...widths, available: 999, compactWidth: null })).toBe(
"labels",
);
});
});
@@ -145,6 +161,7 @@ describe("resolvePinnedUsage", () => {
key: "claude:default/five-hour",
label: "Claude Session 31% used",
shortLabel: "5h",
compactLabel: "5h",
percent: 31,
percentText: "31%",
tone: "default",
@@ -153,6 +170,7 @@ describe("resolvePinnedUsage", () => {
key: "claude:default/weekly",
label: "Claude Weekly 80% used",
shortLabel: "wk",
compactLabel: "wk",
percent: 80,
percentText: "80%",
tone: "warning",
@@ -216,6 +234,52 @@ describe("resolvePinnedUsage", () => {
const items = windows([opencode], preferences(null));
expect(items.map((item) => item.shortLabel)).toEqual([""]);
expect(items.map((item) => item.compactLabel)).toEqual([""]);
});
it("extracts bare period tokens as compact labels for scoped or verbose short labels", () => {
const mixed = report({
sourceId: "mixed",
sourceLabel: "Mixed",
windows: [
{ id: "a", label: "Session", shortLabel: "5h", summary: true, usedPct: 10 },
{ id: "b", label: "Weekly · Opus", shortLabel: "wk Opus", summary: true, usedPct: 20 },
{
id: "c",
label: "Code review · Weekly",
shortLabel: "Code review wk",
summary: true,
usedPct: 30,
},
{
id: "d",
label: "Gemini Models · Weekly",
shortLabel: "Gemini Models weekly",
summary: true,
usedPct: 40,
},
{
id: "e",
label: "Gemini Models · 5h",
shortLabel: "Gemini Models 5h",
summary: true,
usedPct: 50,
},
{ id: "f", label: "Monthly", shortLabel: "Monthly", summary: true, usedPct: 60 },
{ id: "g", label: "Premium requests", summary: true, usedPct: 70 },
],
});
const items = windows([mixed], preferences(null));
expect(items.map((item) => [item.shortLabel, item.compactLabel])).toEqual([
["5h", "5h"],
["wk Opus", "wk"],
["Code review wk", "wk"],
["Gemini Models weekly", "wk"],
["Gemini Models 5h", "5h"],
["Monthly", "mo"],
["Premium requests", ""],
]);
});
it("formats the share left when the user reads usage as remaining", () => {
+49 -6
View File
@@ -18,6 +18,8 @@ export interface PinnedUsageWindow {
label: string;
/** The window's short name ("5h"), empty for none, or its label when the source sends none. */
shortLabel: string;
/** Bare period token ("5h", "wk", "mo") used when full short labels overflow the sidebar row. */
compactLabel: string;
/** The share shown, under the user's used/remaining preference. */
percent: number;
percentText: string;
@@ -34,28 +36,66 @@ export interface PinnedUsageSource {
}
/** How much of each window the one-line summary has room for. */
export type PinnedUsageLayout = "meters" | "labels" | "percents";
export type PinnedUsageLayout = "meters" | "labels" | "compact" | "percents";
// A meter narrower than this is a sliver that reads as noise rather than a share.
export const MIN_METER_WIDTH = 16;
/** The space between a meter and its text. */
export const METER_GAP = 4;
const DURATION_TOKEN_PATTERN = /^\d+[smhd]$/i;
function normalizePeriodToken(token: string): string | null {
const lower = token.toLowerCase();
if (lower === "wk" || lower === "weekly") return "wk";
if (lower === "mo" || lower === "monthly") return "mo";
if (DURATION_TOKEN_PATTERN.test(token)) return lower;
return null;
}
/**
* Extracts a bare period token ("5h", "wk", "mo") from a window's short label so tight sidebar
* rows can keep shorthands visible instead of dropping every label when one window is scoped.
*/
function compactShortLabel(shortLabel: string): string {
const trimmed = shortLabel.trim();
if (trimmed === "") return "";
const exact = normalizePeriodToken(trimmed);
if (exact !== null) return exact;
const parts = trimmed.split(/\s+/);
if (parts.length > 1) {
const first = normalizePeriodToken(parts[0]!);
if (first !== null) return first;
const last = normalizePeriodToken(parts[parts.length - 1]!);
if (last !== null) return last;
}
return "";
}
/**
* The richest layout that fits on one line: every window's meter, else its short label, else its
* percent alone. Meters are all or none; a line never mixes them. Until the widths are known it
* shows labels, which never flashes meters that turn out not to fit.
* bare period shorthand, else its percent alone. Meters are all or none; a line never mixes them.
* Until the widths are known it shows labels, which never flashes meters that turn out not to fit.
*/
export function choosePinnedUsageLayout(input: {
available: number | null;
labelsWidth: number | null;
compactWidth: number | null;
percentsWidth: number | null;
windowCount: number;
}): PinnedUsageLayout {
const { available, labelsWidth, percentsWidth, windowCount } = input;
if (available === null || labelsWidth === null || percentsWidth === null) return "labels";
const { available, labelsWidth, compactWidth, percentsWidth, windowCount } = input;
if (
available === null ||
labelsWidth === null ||
compactWidth === null ||
percentsWidth === null
) {
return "labels";
}
if (labelsWidth + windowCount * (MIN_METER_WIDTH + METER_GAP) <= available) return "meters";
if (labelsWidth <= available) return "labels";
if (compactWidth <= available && compactWidth > percentsWidth) return "compact";
return percentsWidth < labelsWidth ? "percents" : "labels";
}
@@ -85,10 +125,13 @@ export function resolvePinnedUsage(
.map((window) => {
const percent = displayPercent(window, preferences.displayAs) ?? 0;
const percentText = formatPct(percent);
const shortLabel =
window.shortLabel ?? formatProviderUsageLabel(window.id, window.label, t);
return {
key: `${entry.id}/${window.id}`,
label: `${describe(entry, formatProviderUsageLabel(window.id, window.label, t))} ${formatDisplayPct(percent, preferences.displayAs, undefined, t)}`,
shortLabel: window.shortLabel ?? formatProviderUsageLabel(window.id, window.label, t),
shortLabel,
compactLabel: compactShortLabel(shortLabel),
percent,
percentText,
tone: windowTone(window),
+19 -5
View File
@@ -29,6 +29,7 @@ import {
resolvePinnedUsage,
type PinnedUsageLayout,
type PinnedUsageSource,
type PinnedUsageWindow,
} from "./pinned";
import { UsageModal } from "./usage-modal";
@@ -123,8 +124,8 @@ function layoutWidth(event: LayoutChangeEvent): number {
/**
* One line: each account's icon, then per window a meter and "31% 5h". Off-screen copies measure
* the line with labels and with percents alone; the richest layout that fits is shown, and what
* it leaves out takes no space at all.
* the line with full labels, bare period shorthands, and percents alone; the richest layout that
* fits is shown, and what it leaves out takes no space at all.
*/
function PinnedUsageTrigger({
label,
@@ -139,6 +140,7 @@ function PinnedUsageTrigger({
}) {
const [available, setAvailable] = useState<number | null>(null);
const [labelsWidth, setLabelsWidth] = useState<number | null>(null);
const [compactWidth, setCompactWidth] = useState<number | null>(null);
const [percentsWidth, setPercentsWidth] = useState<number | null>(null);
const handleAvailableLayout = useCallback((event: LayoutChangeEvent) => {
setAvailable(layoutWidth(event));
@@ -146,12 +148,16 @@ function PinnedUsageTrigger({
const handleLabelsLayout = useCallback((event: LayoutChangeEvent) => {
setLabelsWidth(layoutWidth(event));
}, []);
const handleCompactLayout = useCallback((event: LayoutChangeEvent) => {
setCompactWidth(layoutWidth(event));
}, []);
const handlePercentsLayout = useCallback((event: LayoutChangeEvent) => {
setPercentsWidth(layoutWidth(event));
}, []);
const layout = choosePinnedUsageLayout({
available,
labelsWidth,
compactWidth,
percentsWidth,
windowCount: sources.reduce((count, source) => count + source.windows.length, 0),
});
@@ -177,6 +183,9 @@ function PinnedUsageTrigger({
<View style={styles.measured} onLayout={handleLabelsLayout}>
<PinnedUsageLine sources={sources} layout="labels" measuring />
</View>
<View style={styles.measured} onLayout={handleCompactLayout}>
<PinnedUsageLine sources={sources} layout="compact" measuring />
</View>
<View style={styles.measured} onLayout={handlePercentsLayout}>
<PinnedUsageLine sources={sources} layout="percents" measuring />
</View>
@@ -185,6 +194,12 @@ function PinnedUsageTrigger({
);
}
function windowSuffix(window: PinnedUsageWindow, layout: PinnedUsageLayout): string {
if (layout === "percents") return "";
if (layout === "compact") return window.compactLabel;
return window.shortLabel;
}
/**
* The line's items as direct children of one row, so every meter shares the leftover width
* equally.
@@ -215,6 +230,7 @@ function PinnedUsageLine({
</View>
{source.windows.map((window, windowIndex) => {
const leadStyle = windowIndex === 0 ? styles.iconGap : styles.windowGap;
const suffix = windowSuffix(window, layout);
return (
<Fragment key={window.key}>
{layout === "meters" ? (
@@ -228,9 +244,7 @@ function PinnedUsageLine({
testID={measuring ? undefined : "sidebar-usage-pinned-window"}
>
{window.percentText}
{layout === "percents" || window.shortLabel === "" ? null : (
<Text style={styles.windowLabel}>{` ${window.shortLabel}`}</Text>
)}
{suffix === "" ? null : <Text style={styles.windowLabel}>{` ${suffix}`}</Text>}
</Text>
</Fragment>
);
@@ -2,10 +2,10 @@ import { readFile } from "node:fs/promises";
import { join } from "node:path";
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,17 +15,13 @@ import type {
import { writeJsonFileAtomic } from "../../atomic-file.js";
const DIGEST_WINDOW_MS = 30_000;
const LEGACY_DEFAULT_FORGE = "github";
const LEGACY_INFERENCE_FORGES = ["github", "gitlab"] as const;
const persistedWatchGroupSchema = z.object({
forge: z.string().min(1).optional(),
const watchGroupSchema = z.object({
url: z.url(),
snapshot: changeRequestStatusSchema,
seenActivity: z.array(z.string()),
watchers: z.array(z.object({ agentId: z.string(), startedAt: z.string().optional() })),
});
type PersistedWatchGroup = z.infer<typeof persistedWatchGroupSchema>;
type WatchGroup = Omit<PersistedWatchGroup, "forge"> & { forge: string };
type WatchGroup = z.infer<typeof watchGroupSchema>;
type Watcher = WatchGroup["watchers"][number];
interface DigestWindow {
dueAt: number;
@@ -39,7 +35,7 @@ interface Observation {
release(): void;
}
interface Dependencies {
router: ChangeRequestRouter;
source: ChangeRequestSource;
paseoHome: string;
logger: Logger;
isActive(agentId: string): Promise<boolean>;
@@ -77,7 +73,7 @@ function describeUpdate(group: WatchGroup, next: ChangeRequestSnapshot) {
}
for (const activity of next.activity) {
if (seen.has(activity.id)) continue;
changes.push(activity.message ?? `New ${activity.kind}: ${activity.url}`);
changes.push(`New ${activity.kind}: ${activity.url}`);
seen.add(activity.id);
}
if (next.state !== "open") changes.push(`Change request ${next.state}.`);
@@ -89,7 +85,6 @@ export type ChangeRequestWatches = ReturnType<typeof createChangeRequestWatches>
export function createChangeRequestWatches(deps: Dependencies) {
const file = join(deps.paseoHome, "change-request-watches.json");
const groups = new Map<string, WatchGroup>();
const unrestored: WatchGroup[] = [];
const observations = new Map<string, Observation>();
const registrations = new Map<string, number>();
let mutations = Promise.resolve();
@@ -183,10 +178,10 @@ export function createChangeRequestWatches(deps: Dependencies) {
async function commit(...updates: WatchGroup[]): Promise<void> {
const next = new Map(groups);
for (const group of updates) next.set(group.url, group);
await writeJsonFileAtomic(file, [
...[...next.values()].filter(({ watchers }) => watchers.length),
...unrestored,
]);
await writeJsonFileAtomic(
file,
[...next.values()].filter(({ watchers }) => watchers.length),
);
for (const group of updates) {
const previous = groups.get(group.url);
// An in-flight subscription still needs the committed baseline and its observation.
@@ -200,20 +195,7 @@ export function createChangeRequestWatches(deps: Dependencies) {
}
}
function describeWatch(forge: string, url: string): string {
const source = deps.router.source(forge);
if (!source) return url;
try {
return source.describe(url);
} catch {
return url;
}
}
function syncBackgroundWork(
{ forge, url, watchers }: WatchGroup,
previous: Watcher[] = [],
): void {
function syncBackgroundWork({ url, watchers }: WatchGroup, previous: Watcher[] = []): void {
if (previous === watchers) return;
const current = new Set(watchers);
for (const watcher of previous) {
@@ -227,7 +209,7 @@ export function createChangeRequestWatches(deps: Dependencies) {
deps.backgroundWork.setDaemonBackgroundWork({
...backgroundWorkKey(watcher.agentId, url),
kind: "monitor",
description: describeWatch(forge, url),
description: deps.source.describe(url),
startedAt: watcher.startedAt ?? new Date().toISOString(),
stop: async () => {
await unsubscribe(watcher.agentId, url, watcher);
@@ -236,13 +218,9 @@ export function createChangeRequestWatches(deps: Dependencies) {
}
}
function observe(forge: string, url: string): Observation {
function observe(url: string): Observation {
const existing = observations.get(url);
if (existing) return existing;
const source = deps.router.source(forge);
if (!source) {
throw new Error(`Change request watches are not supported for ${forge}.`);
}
let resolve!: (snapshot: ChangeRequestSnapshot) => void;
let reject!: (error: unknown) => void;
const ready = new Promise<ChangeRequestSnapshot>((accept, fail) => {
@@ -250,7 +228,7 @@ export function createChangeRequestWatches(deps: Dependencies) {
reject = fail;
});
void ready.catch(() => undefined);
const release = source.observe(url, {
const release = deps.source.observe(url, {
knownActivity: () => new Set(groups.get(url)?.seenActivity),
snapshot: (snapshot) =>
serialize(async () => {
@@ -288,14 +266,14 @@ export function createChangeRequestWatches(deps: Dependencies) {
}),
error(error) {
if (!observation.stale) {
deps.logger.warn({ err: error, url, forge }, "Change request observation became stale");
deps.logger.warn({ err: error, url }, "Change request observation became stale");
}
observation.stale = true;
if (!groups.has(url)) {
reject(error);
stopObserving(url);
}
deps.logger.debug({ err: error, url, forge }, "Change request observation failed");
deps.logger.debug({ err: error, url }, "Change request observation failed");
},
});
const observation: Observation = {
@@ -310,62 +288,16 @@ export function createChangeRequestWatches(deps: Dependencies) {
return observation;
}
function matchActiveGroup(input: string): { forge: string; url: string } | null {
const trimmed = input.trim();
const direct = groups.get(trimmed);
if (direct) return { forge: direct.forge, url: direct.url };
const sourcesTried = new Set<string>();
for (const group of groups.values()) {
if (sourcesTried.has(group.forge)) continue;
sourcesTried.add(group.forge);
const source = deps.router.source(group.forge);
if (!source) continue;
try {
const canonical = source.resolve(trimmed);
const matched = groups.get(canonical);
if (matched && matched.forge === group.forge) {
return { forge: matched.forge, url: matched.url };
}
} catch {
// Input did not belong to this forge.
}
}
return null;
}
function subscribe(agentId: string, input: string) {
if (closed) return Promise.reject(new Error("Change request watches are closed"));
if (recoveryError) {
return Promise.reject(
new Error("Change request watches could not recover.", { cause: recoveryError }),
);
}
const active = matchActiveGroup(input);
if (active) {
return subscribeResolved(agentId, active.forge, active.url);
}
return deps.router
.resolve(input)
.then(({ forge, url }) => subscribeResolved(agentId, forge, url));
}
function subscribeResolved(agentId: string, forge: string, url: string) {
async function subscribe(agentId: string, input: string) {
if (closed) throw new Error("Change request watches are closed");
const url = deps.source.resolve(input);
if (recoveryError)
throw new Error("Change request watches could not recover.", { cause: recoveryError });
registrations.set(url, (registrations.get(url) ?? 0) + 1);
const existing = groups.get(url);
const finish = () => {
const remaining = registrations.get(url)! - 1;
if (remaining) {
registrations.set(url, remaining);
} else {
registrations.delete(url);
if (!groups.get(url)?.watchers.length) {
groups.delete(url);
stopObserving(url);
}
}
};
const commitSubscription = (initial: ChangeRequestSnapshot) =>
serialize(async () => {
try {
const existing = groups.get(url);
const initial = existing ? { ...existing.snapshot, activity: [] } : await observe(url).ready;
return await serialize(async () => {
if (closed || !(await deps.isActive(agentId))) throw new Error("Agent is no longer active");
const group = groups.get(url);
const { activity, ...initialStatus } = initial;
@@ -373,7 +305,6 @@ export function createChangeRequestWatches(deps: Dependencies) {
const subscribed = snapshot.state === "open";
if (subscribed && !group?.watchers.some((watcher) => watcher.agentId === agentId)) {
await commit({
forge: group?.forge ?? forge,
url,
snapshot,
seenActivity: group?.seenActivity ?? activity.map(({ id }) => id),
@@ -391,13 +322,21 @@ export function createChangeRequestWatches(deps: Dependencies) {
checks: snapshot.checks,
reviewDecision: snapshot.reviewDecision,
subscribed,
stale: observations.get(url)?.stale ?? Boolean(existing),
stale: observations.get(url)?.stale ?? false,
};
});
const pending = existing
? commitSubscription({ ...existing.snapshot, activity: [] })
: observe(forge, url).ready.then(commitSubscription);
return pending.finally(finish);
} finally {
const remaining = registrations.get(url)! - 1;
if (remaining) {
registrations.set(url, remaining);
} else {
registrations.delete(url);
if (!groups.get(url)?.watchers.length) {
groups.delete(url);
stopObserving(url);
}
}
}
}
function removeWatcher(group: WatchGroup, agentId: string): Promise<void> {
@@ -434,20 +373,6 @@ export function createChangeRequestWatches(deps: Dependencies) {
});
}
function inferLegacyForge(url: string): string {
for (const candidate of LEGACY_INFERENCE_FORGES) {
const source = deps.router.source(candidate);
if (!source) continue;
try {
source.resolve(url);
return candidate;
} catch {
// URL does not match this forge's canonical path shape.
}
}
return LEGACY_DEFAULT_FORGE;
}
return {
async start() {
const active: WatchGroup[] = [];
@@ -457,12 +382,8 @@ export function createChangeRequestWatches(deps: Dependencies) {
if (error.code === "ENOENT") return "[]";
throw error;
});
const restored = z.array(persistedWatchGroupSchema).parse(JSON.parse(stored));
for (const record of restored) {
const group: WatchGroup = {
...record,
forge: record.forge ?? inferLegacyForge(record.url),
};
const restored = z.array(watchGroupSchema).parse(JSON.parse(stored));
for (const group of restored) {
if (group.snapshot.state !== "open") {
pruned = true;
continue;
@@ -472,17 +393,7 @@ export function createChangeRequestWatches(deps: Dependencies) {
if (await deps.isActive(watcher.agentId)) watchers.push(watcher);
}
pruned ||= watchers.length !== group.watchers.length;
if (!watchers.length) continue;
const nextGroup = { ...group, watchers };
if (!deps.router.source(nextGroup.forge)) {
deps.logger.warn(
{ forge: nextGroup.forge, url: nextGroup.url },
"Skipping persisted change request watch for unsupported forge",
);
unrestored.push(nextGroup);
continue;
}
active.push(nextGroup);
if (watchers.length) active.push({ ...group, watchers });
}
} catch (error) {
recoveryError = error;
@@ -491,7 +402,7 @@ export function createChangeRequestWatches(deps: Dependencies) {
}
if (pruned) {
try {
await writeJsonFileAtomic(file, [...active, ...unrestored]);
await writeJsonFileAtomic(file, active);
} catch (error) {
deps.logger.warn({ err: error, file }, "Could not prune archived change request watches");
}
@@ -499,21 +410,12 @@ export function createChangeRequestWatches(deps: Dependencies) {
for (const group of active) {
groups.set(group.url, group);
syncBackgroundWork(group);
try {
observe(group.forge, group.url);
} catch (error) {
deps.logger.warn(
{ err: error, forge: group.forge, url: group.url },
"Could not start observing restored change request watch",
);
}
observe(group.url);
}
},
subscribe,
unsubscribe(agentId: string, input: string) {
const active = matchActiveGroup(input);
if (active) return unsubscribe(agentId, active.url);
return deps.router.resolve(input).then(({ url }) => unsubscribe(agentId, url));
return unsubscribe(agentId, deps.source.resolve(input));
},
archive,
async close() {
@@ -1,18 +1,16 @@
import { mkdir, mkdtemp, readFile, rename, rm, writeFile } from "node:fs/promises";
import { mkdir, mkdtemp, readFile, rename, rm } from "node:fs/promises";
import { join } from "node:path";
import pino from "pino";
import { afterEach, expect, test, vi } from "vitest";
import { createChangeRequestWatches } from "./index.js";
import { AgentBackgroundWorkStore } from "../background-work/index.js";
import { createAgentMessageDelivery, parseAgentMessages } from "../agent-messages/index.js";
import type { ChangeRequestRouter } from "../../../services/change-request-router.js";
import type {
ChangeRequestSnapshot,
ChangeRequestSource,
} from "../../../services/change-request-source.js";
const url = "https://github.com/owner/repo/pull/42";
const gitlabUrl = "https://gitlab.com/org/sub/app/-/merge_requests/9";
const reviewUrl = url + "#pullrequestreview-1";
const initial: ChangeRequestSnapshot = {
state: "open",
@@ -33,19 +31,13 @@ async function createTestHome() {
function createHarness(
home: string,
{
isActive = async (_id: string) => true,
observationFails = false,
resolveFails = false,
extraSources = {} as Record<string, ChangeRequestSource>,
} = {},
{ isActive = async (_id: string) => true, observationFails = false } = {},
) {
const observations = new Map<string, Parameters<ChangeRequestSource["observe"]>[1]>();
const backgroundWork = new AgentBackgroundWorkStore();
const busy = new Set<string>();
const turns: { recipientId: string; prompt: string }[] = [];
const listeners = new Set<(id: string) => void>();
const resolveCalls: string[] = [];
const messages = createAgentMessageDelivery({
isRunning: (id) => busy.has(id),
subscribe(listener) {
@@ -60,16 +52,10 @@ function createHarness(
throw error;
},
});
function createFakeSource(
describe: (address: string) => string,
accepts: (input: string) => boolean,
): ChangeRequestSource {
return {
resolve: (input) => {
if (!accepts(input)) throw new Error("Unsupported URL for fake forge");
return input.replace(/\/+$/, "");
},
describe,
const watches = createChangeRequestWatches({
source: {
resolve: (input) => input,
describe: () => "owner/repo #42",
observe(address, callbacks) {
observations.set(address, callbacks);
queueMicrotask(() => {
@@ -78,34 +64,7 @@ function createHarness(
});
return () => observations.delete(address);
},
};
}
const sources: Record<string, ChangeRequestSource> = {
github: createFakeSource(
() => "owner/repo #42",
(input) => input.includes("/pull/"),
),
gitlab: createFakeSource(
() => "org/sub/app !9",
(input) => input.includes("/merge_requests/"),
),
...extraSources,
};
const router: ChangeRequestRouter = {
async resolve(input) {
resolveCalls.push(input);
if (resolveFails) throw new Error("Host probe failed");
const forge = input.includes("gitlab") ? "gitlab" : "github";
const source = sources[forge];
if (!source) throw new Error(`Unsupported forge: ${forge}`);
return { forge, url: source.resolve(input) };
},
source(forge) {
return sources[forge] ?? null;
},
};
const watches = createChangeRequestWatches({
router,
paseoHome: home,
logger: pino({ enabled: false }),
isActive,
@@ -119,7 +78,6 @@ function createHarness(
messages,
watches,
backgroundWork,
resolveCalls,
idle(id: string) {
busy.delete(id);
for (const listener of listeners) listener(id);
@@ -385,119 +343,3 @@ test("recovers active watches even when pruning archived watchers cannot be writ
await rm(home, { recursive: true, force: true });
}
});
test("persists forge ids, restores legacy GitHub watches without probing, and preserves unknown forges", async () => {
const home = await createTestHome();
const file = join(home, "change-request-watches.json");
const legacyRecord = {
url,
snapshot: {
state: "open",
headSha: "aaa",
checksState: "pending",
checks: [],
reviewDecision: null,
},
seenActivity: [],
watchers: [{ agentId: "legacy-agent", startedAt: "2026-01-01T00:00:00.000Z" }],
};
const unknownForgeRecord = {
forge: "futureforge",
url: "https://future.example.com/team/repo/cr/5",
snapshot: legacyRecord.snapshot,
seenActivity: [],
watchers: [{ agentId: "future-agent", startedAt: "2026-01-01T00:00:00.000Z" }],
};
const strippedGitLabRecord = {
url: gitlabUrl,
snapshot: legacyRecord.snapshot,
seenActivity: [],
watchers: [{ agentId: "gitlab-agent", startedAt: "2026-01-01T00:00:00.000Z" }],
};
await writeFile(
file,
JSON.stringify([legacyRecord, strippedGitLabRecord, unknownForgeRecord]),
"utf8",
);
const h = createHarness(home, { resolveFails: true });
try {
await h.watches.start();
expect(h.resolveCalls).toEqual([]);
expect(h.backgroundWork.list("legacy-agent")).toEqual([
expect.objectContaining({ description: "owner/repo #42", kind: "monitor" }),
]);
expect(h.backgroundWork.list("gitlab-agent")).toEqual([
expect.objectContaining({ description: "org/sub/app !9", kind: "monitor" }),
]);
expect(h.observations.has(url)).toBe(true);
expect(h.observations.has(gitlabUrl)).toBe(true);
// Unsubscribing an active watch succeeds even when host resolution is temporarily down.
await expect(h.watches.unsubscribe("legacy-agent", `${url}/`)).resolves.toEqual({
url,
removed: true,
});
expect(h.backgroundWork.list("legacy-agent")).toEqual([]);
const persisted = JSON.parse(await readFile(file, "utf8")) as Array<{
forge?: string;
url: string;
}>;
expect(persisted).toEqual([
expect.objectContaining({ forge: "gitlab", url: gitlabUrl }),
unknownForgeRecord,
]);
} finally {
await h.close();
await rm(home, { recursive: true, force: true });
}
});
test("watches multiple forges concurrently with forge-native descriptions and custom approval messages", async () => {
vi.useFakeTimers();
const home = await createTestHome();
const file = join(home, "change-request-watches.json");
const h = createHarness(home);
try {
await h.watches.start();
await h.watches.subscribe("agent-1", url);
await h.watches.subscribe("agent-1", gitlabUrl);
expect(h.backgroundWork.list("agent-1").map((item) => item.description)).toEqual([
"owner/repo #42",
"org/sub/app !9",
]);
const persisted = JSON.parse(await readFile(file, "utf8")) as Array<{
forge?: string;
url: string;
}>;
expect(persisted.map(({ forge, url: entryUrl }) => ({ forge, url: entryUrl }))).toEqual([
{ forge: "github", url },
{ forge: "gitlab", url: gitlabUrl },
]);
await h.observations.get(gitlabUrl)!.snapshot({
...initial,
activity: [
{
id: "approval-note:77",
kind: "approval",
url: `${gitlabUrl}#note_77`,
message: `Merge request approved by @alice (1/1 approvals): ${gitlabUrl}#note_77`,
},
],
});
await vi.advanceTimersByTimeAsync(32_000);
expect(h.turns).toEqual([
{
recipientId: "agent-1",
prompt: expect.stringContaining(
`Merge request approved by @alice (1/1 approvals): ${gitlabUrl}#note_77`,
),
},
]);
} finally {
await h.close();
await rm(home, { recursive: true, force: true });
}
});
@@ -2728,19 +2728,13 @@ function createToolCatalog(
if (options.changeRequestWatches) {
const watches = options.changeRequestWatches;
const inputSchema = {
url: z
.string()
.trim()
.min(1)
.describe("URL of a pull request or merge request on a supported forge."),
};
const inputSchema = { url: z.string().trim().min(1).describe("URL of a GitHub pull request.") };
registerTool(
"subscribe_change_request",
{
title: "Watch change request",
description:
"Watch a pull request or merge request for check failures, passing checks, new comments, reviews, approvals, and closure. Returns the current state and sends future updates after your current turn.",
"Watch a pull request for check failures, passing checks, new comments, reviews, and closure. Returns the current state and sends future updates after your current turn.",
inputSchema,
outputSchema: {
url: z.string(),
+2 -9
View File
@@ -132,9 +132,6 @@ export async function fanOutReconciledWorkspaceUpdates(input: {
import { VoiceAssistantWebSocketServer, isDaemonOriginAllowed } from "./websocket-server.js";
import { WorkspaceSetupRuntime } from "./workspace-setup-runtime.js";
import { createWorkspaceLabelService } from "./workspace-labels/index.js";
import { createChangeRequestRouter } from "../services/change-request-router.js";
import { createForgeService } from "../services/forge-registry.js";
import { createForgeResolver } from "../services/forge-resolver.js";
import { createGitHubService } from "../services/github-service.js";
import { createPaseoWorktree as createRegisteredPaseoWorktree } from "./paseo-worktree-service.js";
import { createWorkspaceProvisioningService } from "./session/workspace-provisioning/workspace-provisioning-service.js";
@@ -957,15 +954,12 @@ export async function createPaseoDaemon(
workspaceRegistry,
});
const github = createGitHubService();
const forgeResolver = createForgeResolver({
createService: (forge) => (forge === "github" ? github : createForgeService(forge)),
});
const workspaceGitService = new WorkspaceGitServiceImpl({
logger,
paseoHome: config.paseoHome,
worktreesRoot: config.worktreesRoot,
deps: {
forgeResolver,
forgeOverrides: { github },
},
});
const workspaceRuntimeStore = createWorkspaceRuntimeStore();
@@ -1478,7 +1472,7 @@ export async function createPaseoDaemon(
await scheduleService.start();
const changeRequestWatches = createChangeRequestWatches({
router: createChangeRequestRouter({ forgeResolver }),
source: github.changeRequests,
backgroundWork: agentManager,
paseoHome: config.paseoHome,
logger,
@@ -2062,7 +2056,6 @@ export async function createPaseoDaemon(
if (wsServer) {
await wsServer.close();
}
forgeResolver.dispose();
await serviceProxy.stopStandalone();
// Force-drop remaining sockets so httpServer.close() resolves promptly.
// We've already closed wsServer (which sent ws-layer close frames) and
@@ -422,8 +422,6 @@ interface WorkspaceGitServiceDependencies {
* fakes. Any forge not listed here is built (and cached once) by the registry.
*/
forgeOverrides?: Record<string, ForgeService>;
/** Shared forge resolver when callers share adapter instances with other services. */
forgeResolver?: ForgeResolver;
/** Resolves an SSH config alias to its HostName; defaults to `ssh -G`. */
resolveSshHostname?: SshHostnameResolver;
resolveAbsoluteGitDir: (cwd: string) => Promise<string | null>;
@@ -725,12 +723,10 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
this.fileObserver.subscribe.bind(this.fileObserver),
options.deps,
);
this.forgeResolver =
this.deps.forgeResolver ??
createForgeResolver({
createService: (forge) => this.deps.forgeOverrides?.[forge] ?? createForgeService(forge),
resolveSshHostname: this.deps.resolveSshHostname,
});
this.forgeResolver = createForgeResolver({
createService: (forge) => this.deps.forgeOverrides?.[forge] ?? createForgeService(forge),
resolveSshHostname: this.deps.resolveSshHostname,
});
}
resolveForge(cwd: string): Promise<ForgeResolution | null> {
@@ -1,230 +0,0 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import type { ChangeRequestSnapshot } from "./change-request-source.js";
import {
ChangeRequestRateLimitError,
createPerHostChangeRequestPoller,
parseCliHttpResponse,
parseRetryAfterMs,
} from "./change-request-poller.js";
const sampleSnapshot: ChangeRequestSnapshot = {
state: "open",
headSha: "abc123",
checksState: "passed",
checks: [],
reviewDecision: null,
activity: [],
};
afterEach(() => {
vi.useRealTimers();
});
describe("parseCliHttpResponse", () => {
it("parses status line, mixed line endings, redirect blocks, and JSON body", () => {
const raw = [
"HTTP/1.1 100 Continue\r\n\r\n",
"HTTP/2.0 200 OK\n",
"Content-Type: application/json\r\n",
"X-Next-Page: 2\r\n",
"Ratelimit-Remaining: 95\r\n",
"Ratelimit-Reset: 1700000120\r\n",
"\r\n",
'{"ok":true}',
].join("");
const parsed = parseCliHttpResponse(raw);
expect(parsed.status).toBe(200);
expect(parsed.headers.get("x-next-page")).toBe("2");
expect(parsed.headers.get("ratelimit-remaining")).toBe("95");
expect(parsed.body).toBe('{"ok":true}');
});
it("returns null status and raw body when headers are absent", () => {
const parsed = parseCliHttpResponse('{"ok":true}');
expect(parsed.status).toBeNull();
expect(parsed.headers.size).toBe(0);
expect(parsed.body).toBe('{"ok":true}');
});
});
describe("parseRetryAfterMs", () => {
it("parses Retry-After seconds and exhausted Ratelimit-Reset headers", () => {
const now = 1_700_000_000_000;
expect(parseRetryAfterMs(new Map([["retry-after", "45"]]), now)).toBe(now + 45_000);
expect(
parseRetryAfterMs(
new Map([
["ratelimit-remaining", "0"],
["ratelimit-reset", "1700000060"],
]),
now,
),
).toBe(1_700_000_060_000);
expect(
parseRetryAfterMs(
new Map([
["ratelimit-remaining", "50"],
["ratelimit-reset", "1700000060"],
]),
now,
),
).toBeNull();
});
});
describe("createPerHostChangeRequestPoller", () => {
it("bounds concurrent reads per host and drains waiting watches as slots free", async () => {
vi.useFakeTimers();
let active = 0;
let maxActive = 0;
const resolvers = new Map<string, () => void>();
const poller = createPerHostChangeRequestPoller({
hostOf: (url) => new URL(url).hostname,
maxConcurrencyPerHost: 2,
pollIntervalMs: 20_000,
async read({ url }) {
active += 1;
maxActive = Math.max(maxActive, active);
await new Promise<void>((resolve) => {
resolvers.set(url, resolve);
});
active -= 1;
return sampleSnapshot;
},
});
const received: string[] = [];
try {
for (const n of [1, 2, 3]) {
const url = `https://gitlab.com/org/repo/-/merge_requests/${n}`;
poller.observe(url, {
async snapshot() {
received.push(url);
},
error(error) {
throw error;
},
});
}
await vi.advanceTimersByTimeAsync(25);
expect(maxActive).toBe(2);
expect(resolvers.size).toBe(2);
resolvers.get("https://gitlab.com/org/repo/-/merge_requests/1")?.();
await vi.advanceTimersByTimeAsync(0);
expect(maxActive).toBe(2);
expect(resolvers.has("https://gitlab.com/org/repo/-/merge_requests/3")).toBe(true);
resolvers.get("https://gitlab.com/org/repo/-/merge_requests/2")?.();
resolvers.get("https://gitlab.com/org/repo/-/merge_requests/3")?.();
await vi.advanceTimersByTimeAsync(0);
expect(received).toHaveLength(3);
} finally {
poller.dispose();
}
});
it("backs off exponentially on transient errors and resets after a successful poll", async () => {
vi.useFakeTimers();
let calls = 0;
let shouldFail = true;
const poller = createPerHostChangeRequestPoller({
hostOf: (url) => new URL(url).hostname,
pollIntervalMs: 10_000,
maxErrorBackoffMs: 40_000,
async read() {
calls += 1;
if (shouldFail) throw new Error(`fail ${calls}`);
return sampleSnapshot;
},
});
const errors: unknown[] = [];
const snapshots: ChangeRequestSnapshot[] = [];
try {
poller.observe("https://gitlab.com/org/repo/-/merge_requests/1", {
async snapshot(s) {
snapshots.push(s);
},
error(err) {
errors.push(err);
},
});
await vi.advanceTimersByTimeAsync(25);
expect(calls).toBe(1);
expect(errors).toHaveLength(1);
// 1st failure -> 10s backoff
await vi.advanceTimersByTimeAsync(9_999);
expect(calls).toBe(1);
await vi.advanceTimersByTimeAsync(1);
expect(calls).toBe(2);
// 2nd failure -> 20s backoff
await vi.advanceTimersByTimeAsync(19_999);
expect(calls).toBe(2);
shouldFail = false;
await vi.advanceTimersByTimeAsync(1);
expect(calls).toBe(3);
expect(snapshots).toHaveLength(1);
// Reset to 10s base interval after success
await vi.advanceTimersByTimeAsync(10_000);
expect(calls).toBe(4);
} finally {
poller.dispose();
}
});
it("pauses all watches on a rate-limited host until resetAt and fast-fails new observers", async () => {
vi.useFakeTimers();
vi.setSystemTime(1_700_000_000_000);
let calls = 0;
const poller = createPerHostChangeRequestPoller({
hostOf: (url) => new URL(url).hostname,
pollIntervalMs: 10_000,
async read() {
calls += 1;
if (calls === 1) {
throw new ChangeRequestRateLimitError({
host: "gitlab.com",
resetAtMs: Date.now() + 60_000,
});
}
return sampleSnapshot;
},
});
const errors1: unknown[] = [];
const errors2: unknown[] = [];
const snapshots2: ChangeRequestSnapshot[] = [];
try {
poller.observe("https://gitlab.com/org/repo/-/merge_requests/1", {
async snapshot() {},
error(err) {
errors1.push(err);
},
});
await vi.advanceTimersByTimeAsync(25);
expect(calls).toBe(1);
expect(errors1[0]).toBeInstanceOf(ChangeRequestRateLimitError);
poller.observe("https://gitlab.com/org/repo/-/merge_requests/2", {
async snapshot(s) {
snapshots2.push(s);
},
error(err) {
errors2.push(err);
},
});
await vi.advanceTimersByTimeAsync(0);
expect(errors2[0]).toBeInstanceOf(ChangeRequestRateLimitError);
await vi.advanceTimersByTimeAsync(59_999);
expect(calls).toBe(1);
await vi.advanceTimersByTimeAsync(1);
expect(calls).toBe(3);
expect(snapshots2).toHaveLength(1);
} finally {
poller.dispose();
}
});
});
@@ -1,333 +0,0 @@
import type { ChangeRequestSnapshot, ChangeRequestSource } from "./change-request-source.js";
const DEFAULT_INITIAL_DELAY_MS = 25;
const DEFAULT_POLL_INTERVAL_MS = 20_000;
const DEFAULT_MAX_ERROR_BACKOFF_MS = 300_000;
const DEFAULT_MAX_CONCURRENCY_PER_HOST = 2;
const MIN_RATE_LIMIT_PAUSE_MS = 1_000;
const MAX_RATE_LIMIT_PAUSE_MS = 15 * 60_000;
export interface ParsedCliHttpResponse {
status: number | null;
headers: Map<string, string>;
body: string;
}
const HTTP_STATUS_PREFIX = /^HTTP\/\d(?:\.\d)?\s+(\d{3})[^\r\n]*\r?\n/;
const HEADER_BODY_SEPARATOR = /\r?\n\r?\n/;
/**
* Parse output from CLI API commands invoked with `-i` / `--include`.
* Consumes multiple leading HTTP response blocks (e.g. `100 Continue` or
* redirect headers) and returns the final status code, lowercased headers,
* and response body. Returns `status: null` when no HTTP header block is
* present.
*/
export function parseCliHttpResponse(raw: string): ParsedCliHttpResponse {
let remaining = raw.trimStart();
let status: number | null = null;
let headers = new Map<string, string>();
while (true) {
const statusMatch = HTTP_STATUS_PREFIX.exec(remaining);
if (!statusMatch) {
break;
}
const separatorMatch = HEADER_BODY_SEPARATOR.exec(remaining);
if (!separatorMatch) {
status = Number(statusMatch[1]);
headers = parseHeaderLines(remaining.slice(statusMatch[0].length));
remaining = "";
break;
}
status = Number(statusMatch[1]);
const headerBlock = remaining.slice(statusMatch[0].length, separatorMatch.index);
headers = parseHeaderLines(headerBlock);
remaining = remaining.slice(separatorMatch.index + separatorMatch[0].length);
}
return { status, headers, body: remaining.trim() };
}
function parseHeaderLines(block: string): Map<string, string> {
const headers = new Map<string, string>();
for (const line of block.split(/\r?\n/)) {
const colon = line.indexOf(":");
if (colon <= 0) continue;
const name = line.slice(0, colon).trim().toLowerCase();
const value = line.slice(colon + 1).trim();
if (!name) continue;
const existing = headers.get(name);
headers.set(name, existing ? `${existing}, ${value}` : value);
}
return headers;
}
function clampPauseUntil(targetMs: number, nowMs: number): number {
return Math.min(
Math.max(targetMs, nowMs + MIN_RATE_LIMIT_PAUSE_MS),
nowMs + MAX_RATE_LIMIT_PAUSE_MS,
);
}
/**
* Extract the timestamp (epoch ms) until which a host should pause polling
* based on `Retry-After` or exhausted `Ratelimit-Remaining` / `Ratelimit-Reset`
* headers. Returns null when no pause is signaled.
*/
export function parseRetryAfterMs(
headers: ReadonlyMap<string, string>,
nowMs: number,
options: { forceOnMissing?: boolean; defaultPauseMs?: number } = {},
): number | null {
const retryAfter = headers.get("retry-after");
if (retryAfter) {
const seconds = Number(retryAfter);
if (Number.isFinite(seconds) && seconds >= 0) {
return clampPauseUntil(nowMs + Math.ceil(seconds * 1_000), nowMs);
}
const parsedDate = Date.parse(retryAfter);
if (Number.isFinite(parsedDate)) {
return clampPauseUntil(parsedDate, nowMs);
}
}
const remainingRaw = headers.get("ratelimit-remaining") ?? headers.get("x-ratelimit-remaining");
const resetRaw = headers.get("ratelimit-reset") ?? headers.get("x-ratelimit-reset");
const remaining = remainingRaw !== undefined ? Number(remainingRaw) : Number.NaN;
const resetSec = resetRaw !== undefined ? Number(resetRaw) : Number.NaN;
if (
(options.forceOnMissing || (Number.isFinite(remaining) && remaining <= 1)) &&
Number.isFinite(resetSec) &&
resetSec > 0
) {
return clampPauseUntil(resetSec * 1_000, nowMs);
}
if (options.forceOnMissing) {
return clampPauseUntil(nowMs + (options.defaultPauseMs ?? 60_000), nowMs);
}
return null;
}
export class ChangeRequestRateLimitError extends Error {
readonly host: string;
readonly resetAtMs: number;
constructor(params: { host: string; resetAtMs: number; message?: string }) {
super(
params.message ??
`Change request polling for ${params.host} is rate-limited until ${new Date(params.resetAtMs).toISOString()}`,
);
this.name = "ChangeRequestRateLimitError";
this.host = params.host;
this.resetAtMs = params.resetAtMs;
}
}
export interface PerHostReadContext {
url: string;
host: string;
knownActivity(): ReadonlySet<string> | undefined;
isObserved(): boolean;
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 pausedUntilByHost = new Map<string, number>();
let timer: NodeJS.Timeout | null = null;
let disposed = false;
function clearTimer(): void {
if (timer) {
clearTimeout(timer);
timer = null;
}
}
function pauseHost(host: string, untilMs: number): void {
const current = pausedUntilByHost.get(host) ?? 0;
if (untilMs > current) {
pausedUntilByHost.set(host, untilMs);
}
}
function hostPauseUntil(host: string, nowMs: number): number {
const until = pausedUntilByHost.get(host) ?? 0;
if (until <= nowMs) {
pausedUntilByHost.delete(host);
return 0;
}
return until;
}
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) >= maxConcurrencyPerHost) 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 >= maxConcurrencyPerHost) 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;
void (async () => {
try {
const snapshot = await options.read({
url: watch.url,
host: watch.host,
knownActivity: () => watch.callbacks.knownActivity?.(),
isObserved,
pauseHost: (untilMs) => pauseHost(watch.host, untilMs),
});
if (!isObserved()) return;
watch.consecutiveErrors = 0;
await watch.callbacks.snapshot(snapshot);
if (!isObserved()) return;
const nowMs = now();
watch.nextDueAt = Math.max(nowMs + pollIntervalMs, hostPauseUntil(watch.host, nowMs));
} catch (error) {
if (!isObserved()) return;
options.onError?.(error, watch.host);
const nowMs = now();
if (error instanceof ChangeRequestRateLimitError) {
pauseHost(watch.host, error.resetAtMs);
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 {
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();
pausedUntilByHost.clear();
},
};
}
@@ -1,120 +0,0 @@
import { describe, expect, it, vi } from "vitest";
import { createChangeRequestRouter } from "./change-request-router.js";
import type { ChangeRequestSource } from "./change-request-source.js";
import { createForgeResolver } from "./forge-resolver.js";
import type { ForgeService } from "./forge-service.js";
function createFakeSource(
forge: string,
canonicalize: (url: string) => string,
): ChangeRequestSource {
return {
resolve: canonicalize,
describe: (url) => `${forge}:${url}`,
observe: () => () => {},
};
}
function createFakeForgeService(changeRequests?: ChangeRequestSource): ForgeService {
return {
...(changeRequests ? { changeRequests } : {}),
invalidate() {},
} as unknown as ForgeService;
}
describe("createChangeRequestRouter", () => {
it("routes cloud hosts without probing and delegates canonicalization to the matched forge", async () => {
const probeForge = vi.fn(async () => {
throw new Error("cloud host must not trigger a probe");
});
const githubSource = createFakeSource(
"github",
(url) => `https://github.com/canonical/${new URL(url).pathname.split("/").at(-1)}`,
);
const gitlabSource = createFakeSource(
"gitlab",
(url) => `https://gitlab.com/canonical/${new URL(url).pathname.split("/").at(-1)}`,
);
const resolver = createForgeResolver({
probeForge,
createService: (forge) => {
if (forge === "github") return createFakeForgeService(githubSource);
if (forge === "gitlab") return createFakeForgeService(gitlabSource);
return null;
},
});
const router = createChangeRequestRouter({ forgeResolver: resolver });
await expect(router.resolve("https://GitHub.com/Org/Repo/pull/7")).resolves.toEqual({
forge: "github",
url: "https://github.com/canonical/7",
});
await expect(
router.resolve("https://gitlab.com/org/sub/repo/-/merge_requests/12"),
).resolves.toEqual({
forge: "gitlab",
url: "https://gitlab.com/canonical/12",
});
expect(probeForge).not.toHaveBeenCalled();
expect(router.source("github")).toBe(githubSource);
expect(router.source("gitlab")).toBe(gitlabSource);
});
it("probes self-hosted hosts before parsing the URL path", async () => {
const probeForge = vi.fn(async (host: string) =>
host === "git.corp.internal" ? "gitlab" : null,
);
const gitlabResolve = vi.fn(() => "https://git.corp.internal/team/app/-/merge_requests/9");
const githubResolve = vi.fn(() => {
throw new Error("github must not parse a gitlab host");
});
const resolver = createForgeResolver({
probeForge,
createService: (forge) => {
if (forge === "github")
return createFakeForgeService(createFakeSource("github", githubResolve));
if (forge === "gitlab")
return createFakeForgeService(createFakeSource("gitlab", gitlabResolve));
return null;
},
});
const router = createChangeRequestRouter({ forgeResolver: resolver });
await expect(
router.resolve("https://git.corp.internal/team/app/-/merge_requests/9"),
).resolves.toEqual({
forge: "gitlab",
url: "https://git.corp.internal/team/app/-/merge_requests/9",
});
expect(probeForge).toHaveBeenCalledWith("git.corp.internal");
expect(gitlabResolve).toHaveBeenCalledTimes(1);
expect(githubResolve).not.toHaveBeenCalled();
});
it("rejects unrecognized hosts, credentials, non-http schemes, and forges without watch support", async () => {
const resolver = createForgeResolver({
probeForge: async () => null,
createService: (forge) => {
if (forge === "gitea") return createFakeForgeService();
return null;
},
});
const router = createChangeRequestRouter({ forgeResolver: resolver });
await expect(router.resolve("not a url")).rejects.toThrow(/change request URL/i);
await expect(router.resolve("ftp://github.com/org/repo/pull/1")).rejects.toThrow(
/change request URL/i,
);
await expect(router.resolve("https://user:pass@github.com/org/repo/pull/1")).rejects.toThrow(
/change request URL/i,
);
await expect(router.resolve("https://unknown.example.com/org/repo/pull/1")).rejects.toThrow(
/unknown\.example\.com/,
);
await expect(router.resolve("https://gitea.com/org/repo/pulls/1")).rejects.toThrow(
/not supported.*gitea/i,
);
expect(router.source("gitea")).toBeNull();
expect(router.source("unknown")).toBeNull();
});
});
@@ -1,78 +0,0 @@
import { normalizeHost } from "@getpaseo/protocol/git-remote";
import type { ChangeRequestSource } from "./change-request-source.js";
import type { ForgeResolver } from "./forge-resolver.js";
export interface ResolvedChangeRequest {
forge: string;
url: string;
}
export interface ChangeRequestRouter {
/** Route a user-supplied URL host-first through registered forges and canonicalize it. */
resolve(url: string): Promise<ResolvedChangeRequest>;
/** Return the watch source for a known forge id without probing the network. */
source(forge: string): ChangeRequestSource | null;
}
export interface CreateChangeRequestRouterOptions {
forgeResolver: Pick<ForgeResolver, "resolveHost" | "getService">;
}
function extractUrlHost(input: string): { trimmed: string; host: string } {
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 };
}
/**
* 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 } = extractUrlHost(input);
const resolution = await forgeResolver.resolveHost(host);
if (!resolution) {
throw new Error(
`Could not recognize a supported forge for host ${host}. Authenticate the forge CLI for this host first.`,
);
}
const source = resolution.service.changeRequests;
if (!source) {
throw new Error(`Change request watches are not supported for ${resolution.forge} yet.`);
}
return {
forge: resolution.forge,
url: source.resolve(trimmed),
};
},
source(forge: string): ChangeRequestSource | null {
return forgeResolver.getService(forge)?.changeRequests ?? null;
},
};
}
@@ -17,9 +17,8 @@ const changeRequestSnapshotSchema = changeRequestStatusSchema.extend({
activity: z.array(
z.object({
id: z.string(),
kind: z.enum(["comment", "inline comment", "review", "approval"]),
kind: z.enum(["comment", "inline comment", "review"]),
url: z.string(),
message: z.string().optional(),
}),
),
});
@@ -373,40 +373,4 @@ describe("createForgeResolver", () => {
expect(b).toMatchObject({ forge: "gitlab", host: "git.acme.internal" });
expect(probeForge).toHaveBeenCalledTimes(1);
});
it("resolves cloud and probed hosts directly via resolveHost and shares service instances", async () => {
const probeForge = vi.fn(async (host: string) =>
host === "git.acme.internal" ? "gitlab" : null,
);
const created: string[] = [];
const disposed: string[] = [];
const resolver = createForgeResolver({
probeForge,
createService: (forge) => {
created.push(forge);
const base = createForgeService(forge);
if (!base) return null;
return {
...base,
dispose: () => {
disposed.push(forge);
},
};
},
});
const cloud = await resolver.resolveHost("GitLab.com.");
expect(cloud).toMatchObject({ forge: "gitlab", host: "gitlab.com" });
expect(probeForge).not.toHaveBeenCalled();
const selfHosted = await resolver.resolveHost("GIT.ACME.INTERNAL");
expect(selfHosted).toMatchObject({ forge: "gitlab", host: "git.acme.internal" });
expect(selfHosted?.service).toBe(cloud?.service);
expect(probeForge).toHaveBeenCalledTimes(1);
expect(resolver.getService("gitlab")).toBe(cloud?.service);
expect(created).toEqual(["gitlab"]);
resolver.dispose();
expect(disposed).toEqual(["gitlab"]);
});
});
+11 -60
View File
@@ -1,9 +1,5 @@
import { LRUCache } from "lru-cache";
import {
normalizeHost,
parseGitRemoteLocation,
type GitRemoteLocation,
} from "@getpaseo/protocol/git-remote";
import { parseGitRemoteLocation, type GitRemoteLocation } from "@getpaseo/protocol/git-remote";
import { resolveSshHostname, type SshHostnameResolver } from "../utils/ssh-hostname.js";
import { defaultResolveRemoteUrl } from "./forge-cli-command.js";
import type { ForgeService } from "./forge-service.js";
@@ -28,7 +24,6 @@ export type ForgeHostProbe = (host: string) => Promise<string | null>;
export interface CreateForgeResolverOptions {
resolveRemoteUrl?: (cwd: string) => Promise<string | null>;
createService?: (forge: string) => ForgeService | null;
matchHost?: (host: string) => string | null;
probeForge?: ForgeHostProbe;
resolveSshHostname?: SshHostnameResolver;
now?: () => number;
@@ -41,18 +36,12 @@ export interface ForgeResolver {
resolveFromRemoteUrl(remoteUrl: string | null): ForgeResolution | null;
/** Resolve from a known origin remote URL, running the per-host probe when needed. */
resolveFromRemoteUrlAsync(remoteUrl: string | null): Promise<ForgeResolution | null>;
/** Resolve a forge directly by hostname (cloud match first, then cached async probe). */
resolveHost(host: string): Promise<ForgeResolution | null>;
/** Return the shared adapter instance for a known forge id without probing the network. */
getService(forge: string): ForgeService | null;
/**
* Invalidate every cached adapter's state for a cwd. Routed through the
* resolver so invalidation hits the same adapter instance the poller reads,
* regardless of which forge backs the workspace.
*/
invalidate(cwd: string): void;
/** Dispose all instantiated forge adapters owned by this resolver. */
dispose(): void;
}
// A positive probe (host IS a known forge) is cached permanently; a negative one
@@ -75,7 +64,6 @@ export function forgeForHost(host: string): string | null {
export function createForgeResolver(options: CreateForgeResolverOptions = {}): ForgeResolver {
const resolveRemoteUrl = options.resolveRemoteUrl ?? defaultResolveRemoteUrl;
const create = options.createService ?? createForgeService;
const matchHost = options.matchHost ?? forgeForHost;
const probeForge = options.probeForge ?? probeRegisteredForgeHost;
const resolveSsh = options.resolveSshHostname ?? resolveSshHostname;
const now = options.now ?? Date.now;
@@ -122,34 +110,22 @@ export function createForgeResolver(options: CreateForgeResolverOptions = {}): F
if (!entry) {
return undefined;
}
if (entry.expiresAt !== null && now() >= entry.expiresAt) {
if (entry.expiresAt !== null && Date.now() >= entry.expiresAt) {
probedForgeByHost.delete(host);
return undefined;
}
return entry.forge;
}
function getService(forge: string): ForgeService | null {
const normalized = forge.trim().toLowerCase();
if (!normalized) {
return null;
}
let service = services.get(normalized);
function buildResolution(forge: string, host: string): ForgeResolution | null {
let service = services.get(forge);
if (!service) {
const created = create(normalized);
const created = create(forge);
if (!created) {
return null;
}
service = created;
services.set(normalized, service);
}
return service;
}
function buildResolution(forge: string, host: string): ForgeResolution | null {
const service = getService(forge);
if (!service) {
return null;
services.set(forge, service);
}
return { forge, host, service };
}
@@ -175,7 +151,7 @@ export function createForgeResolver(options: CreateForgeResolverOptions = {}): F
}
probedForgeByHost.set(host, {
forge: probed,
expiresAt: probed === null ? now() + NEGATIVE_PROBE_TTL_MS : null,
expiresAt: probed === null ? Date.now() + NEGATIVE_PROBE_TTL_MS : null,
});
return probed;
} finally {
@@ -194,29 +170,13 @@ export function createForgeResolver(options: CreateForgeResolverOptions = {}): F
if (!host) {
return null;
}
const forge = matchHost(host) ?? readFreshProbe(host) ?? null;
const forge = forgeForHost(host) ?? readFreshProbe(host) ?? null;
if (!forge) {
return null;
}
return buildResolution(forge, host);
}
async function resolveHost(host: string): Promise<ForgeResolution | null> {
const normalized = normalizeHost(host);
if (!normalized) {
return null;
}
const directForge = matchHost(normalized);
if (directForge) {
return buildResolution(directForge, normalized);
}
const probed = await probeHostForge(normalized);
if (!probed) {
return null;
}
return buildResolution(probed, normalized);
}
async function resolveFromRemoteUrlAsync(
remoteUrl: string | null,
): Promise<ForgeResolution | null> {
@@ -227,7 +187,7 @@ export function createForgeResolver(options: CreateForgeResolverOptions = {}): F
if (!location) {
return null;
}
const directForge = matchHost(location.host);
const directForge = forgeForHost(location.host);
if (directForge) {
return buildResolution(directForge, location.host);
}
@@ -255,7 +215,7 @@ export function createForgeResolver(options: CreateForgeResolverOptions = {}): F
}
probedForgeByHost.set(aliasHost, {
forge,
expiresAt: forge === null ? now() + NEGATIVE_PROBE_TTL_MS : null,
expiresAt: forge === null ? Date.now() + NEGATIVE_PROBE_TTL_MS : null,
});
}
@@ -271,7 +231,7 @@ export function createForgeResolver(options: CreateForgeResolverOptions = {}): F
return { host: location.host };
}
const resolvedForge = matchHost(resolvedHost);
const resolvedForge = forgeForHost(resolvedHost);
if (resolvedForge) {
return { host: resolvedHost, forge: resolvedForge };
}
@@ -286,19 +246,10 @@ export function createForgeResolver(options: CreateForgeResolverOptions = {}): F
}
}
function dispose(): void {
for (const service of services.values()) {
service.dispose?.();
}
}
return {
resolveFromRemoteUrl,
resolveFromRemoteUrlAsync,
resolveHost,
getService,
invalidate,
dispose,
async resolve(cwd: string): Promise<ForgeResolution | null> {
return resolveFromRemoteUrlAsync(await resolveRemoteUrlCached(cwd));
},
@@ -1,5 +1,4 @@
import type { ForgeSearchKind } from "@getpaseo/protocol/messages";
import type { ChangeRequestSource } from "./change-request-source.js";
export type ForgeSearchRequestKind = ForgeSearchKind | "github-issue" | "github-pr" | "pr";
@@ -534,8 +533,6 @@ export interface ForgeService {
onError?: (error: unknown) => void;
},
): { unsubscribe: () => void };
/** Exact-URL change request observation adapter for watches, when supported by the forge. */
changeRequests?: ChangeRequestSource;
invalidate(options: { cwd: string }): void;
dispose?(): void;
}
@@ -1,716 +0,0 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import type { ChangeRequestSnapshot } from "./change-request-source.js";
import {
describeGitLabChangeRequest,
gitlabChangeRequestHost,
resolveGitLabChangeRequest,
} from "./gitlab-change-requests.js";
import { createGitLabService, type GlabCommandRunner } from "./gitlab-service.js";
function httpJson(
body: unknown,
headers: Record<string, string> = {},
status = "200 OK",
): { stdout: string; stderr: string } {
const lines = [`HTTP/2.0 ${status}`];
for (const [key, value] of Object.entries(headers)) {
lines.push(`${key}: ${value}`);
}
return {
stdout: `${lines.join("\r\n")}\r\n\r\n${JSON.stringify(body)}`,
stderr: "",
};
}
function createFakeGlabRunner(
handler: (
args: string[],
options: { cwd: string; envOverlay?: Record<string, string> },
) => Promise<{ stdout: string; stderr: string }> | { stdout: string; stderr: string },
) {
const calls: Array<{ args: string[]; cwd: string; envOverlay?: Record<string, string> }> = [];
const runner: GlabCommandRunner = async (args, options) => {
calls.push({ args: [...args], cwd: options.cwd, envOverlay: options.envOverlay });
return await handler(args, options);
};
return { runner, calls };
}
afterEach(() => {
vi.useRealTimers();
});
describe("GitLab change request URL resolution and description", () => {
it("canonicalizes standard, nested-group, legacy, tab, query, and hash URLs while preserving path casing", () => {
expect(
resolveGitLabChangeRequest(
"https://GitLab.com/MyOrg/SubGroup/MyRepo/-/merge_requests/042/diffs?view=inline#note_9",
),
).toBe("https://gitlab.com/MyOrg/SubGroup/MyRepo/-/merge_requests/42");
expect(
resolveGitLabChangeRequest("https://gitlab.com/Team/App/merge_requests/7/pipelines/"),
).toBe("https://gitlab.com/Team/App/-/merge_requests/7");
expect(
resolveGitLabChangeRequest(
"https://GitLab.Example.Internal:8443/Group/Sub/Repo/-/merge_requests/12/commits",
),
).toBe("https://gitlab.example.internal:8443/Group/Sub/Repo/-/merge_requests/12");
expect(resolveGitLabChangeRequest("http://gitlab.lan/Group/Repo/-/merge_requests/3")).toBe(
"http://gitlab.lan/Group/Repo/-/merge_requests/3",
);
});
it("describes cloud and self-hosted GitLab MRs with native !N numbering", () => {
expect(
describeGitLabChangeRequest("https://gitlab.com/MyOrg/SubGroup/MyRepo/-/merge_requests/42"),
).toBe("MyOrg/SubGroup/MyRepo !42");
expect(
describeGitLabChangeRequest(
"https://gitlab.example.internal:8443/Group/Repo/-/merge_requests/12",
),
).toBe("gitlab.example.internal:8443/Group/Repo !12");
expect(
gitlabChangeRequestHost(
"https://gitlab.example.internal:8443/Group/Repo/-/merge_requests/12",
),
).toBe("gitlab.example.internal:8443");
});
it("rejects invalid GitLab MR URLs", () => {
for (const invalid of [
"https://gitlab.com/only-one-segment/-/merge_requests/1",
"https://gitlab.com/org/repo/-/issues/1",
"https://gitlab.com/org/repo/-/merge_requests/0",
"https://gitlab.com/org/repo/-/merge_requests/abc",
"https://gitlab.com/org/../repo/-/merge_requests/1",
"https://gitlab.com/org/repo/-/merge_requests/1/unknown-tab",
"http://gitlab.com/org/repo/-/merge_requests/1",
"https://gitlab.com/org/repo/-/something/merge_requests/1",
]) {
expect(() => resolveGitLabChangeRequest(invalid), invalid).toThrow(
/GitLab merge request URL/i,
);
}
});
});
describe("GitLab ChangeRequestSource polling", () => {
it("uses cwd-free glab api --hostname, maps head-pipeline jobs, discussions, and approval transitions without reviewDecision", async () => {
vi.useFakeTimers();
let poll = 0;
const mrUrl = "https://gitlab.com/MyOrg/SubGroup/MyRepo/-/merge_requests/42";
const encodedProject = encodeURIComponent("MyOrg/SubGroup/MyRepo");
const { runner, calls } = createFakeGlabRunner((args) => {
const endpoint = args.at(-1) ?? "";
if (endpoint === `projects/${encodedProject}/merge_requests/42`) {
poll += 1;
return httpJson({
iid: 42,
state: "opened",
sha: "sha-1",
web_url: mrUrl,
target_project_id: 900,
head_pipeline: {
id: 500,
project_id: 901,
sha: "merge-sha-1",
status: poll === 1 ? "running" : "success",
web_url: "https://gitlab.com/MyOrg/SubGroup/MyRepo/-/pipelines/500",
},
});
}
if (endpoint.startsWith("projects/901/pipelines/500/jobs")) {
return httpJson(
[
{
id: 10,
name: "lint",
stage: "test",
status: "failed",
allow_failure: true,
web_url: "https://gitlab.com/MyOrg/SubGroup/MyRepo/-/jobs/10",
},
{
id: 11,
name: "unit",
stage: "test",
status: poll === 1 ? "running" : "success",
allow_failure: false,
web_url: "https://gitlab.com/MyOrg/SubGroup/MyRepo/-/jobs/11",
},
{
id: 12,
name: "deploy",
stage: "deploy",
status: "manual",
allow_failure: true,
web_url: "https://gitlab.com/MyOrg/SubGroup/MyRepo/-/jobs/12",
},
],
{ "X-Next-Page": "" },
);
}
if (endpoint.startsWith(`projects/${encodedProject}/merge_requests/42/discussions`)) {
const notes =
poll === 1
? [
{
id: 100,
system: false,
body: "Initial comment",
author: { username: "bob" },
},
{
id: 101,
system: false,
type: "DiffNote",
body: "Inline note",
position: { new_path: "src/app.ts", new_line: 10 },
author: { username: "bob" },
},
{
id: 102,
system: true,
body: "assigned to @bob",
author: { username: "bob" },
},
]
: [
{
id: 100,
system: false,
body: "Initial comment",
author: { username: "bob" },
},
{
id: 101,
system: false,
type: "DiffNote",
body: "Inline note",
position: { new_path: "src/app.ts", new_line: 10 },
author: { username: "bob" },
},
{
id: 103,
system: true,
body: "approved this merge request",
author: { username: "alice" },
},
];
return httpJson([{ id: "disc-1", notes }], { "X-Next-Page": "" });
}
if (endpoint === `projects/${encodedProject}/merge_requests/42/approvals`) {
return httpJson(
poll === 1
? { approvals_required: 1, approvals_left: 1, approved: false, approved_by: [] }
: {
approvals_required: 1,
approvals_left: 0,
approved: true,
approved_by: [
{ user: { id: 1, username: "alice" }, approved_at: "2026-11-20T06:00:00Z" },
],
},
);
}
throw new Error(`Unexpected glab args: ${args.join(" ")}`);
});
const service = createGitLabService({
runner,
resolveGlabPath: async () => "glab",
resolveRemoteUrl: async () => {
throw new Error("watch must not inspect local git remote");
},
watchPollMs: 10_000,
});
const snapshots: ChangeRequestSnapshot[] = [];
const errors: unknown[] = [];
const seen = new Set<string>();
try {
const release = service.changeRequests!.observe(mrUrl, {
knownActivity: () => seen,
async snapshot(s) {
snapshots.push(s);
for (const item of s.activity) seen.add(item.id);
},
error(err) {
errors.push(err);
},
});
await vi.advanceTimersByTimeAsync(25);
expect(errors).toEqual([]);
expect(snapshots).toHaveLength(1);
expect(snapshots[0]).toEqual({
state: "open",
headSha: "sha-1",
checksState: "pending",
checks: [
{
id: "job:10",
name: "lint",
state: "neutral",
url: "https://gitlab.com/MyOrg/SubGroup/MyRepo/-/jobs/10",
},
{
id: "job:11",
name: "unit",
state: "pending",
url: "https://gitlab.com/MyOrg/SubGroup/MyRepo/-/jobs/11",
},
{
id: "job:12",
name: "deploy",
state: "neutral",
url: "https://gitlab.com/MyOrg/SubGroup/MyRepo/-/jobs/12",
},
],
reviewDecision: null,
activity: [
{ id: "comment:100", kind: "comment", url: `${mrUrl}#note_100` },
{ id: "inline:101", kind: "inline comment", url: `${mrUrl}#note_101` },
],
});
// Every glab api call targets --hostname gitlab.com explicitly.
for (const call of calls) {
expect(call.args.slice(0, 4)).toEqual(["api", "--hostname", "gitlab.com", "-i"]);
}
await vi.advanceTimersByTimeAsync(10_000);
expect(errors).toEqual([]);
expect(snapshots).toHaveLength(2);
expect(snapshots[1]!.checksState).toBe("passed");
expect(snapshots[1]!.reviewDecision).toBeNull();
const approvalEvents = snapshots[1]!.activity.filter((a) => a.kind === "approval");
expect(approvalEvents).toEqual([
{
id: "approval-note:103",
kind: "approval",
url: `${mrUrl}#note_103`,
message: `Merge request approved by @alice (1/1 approvals): ${mrUrl}#note_103`,
},
]);
release();
} finally {
service.dispose?.();
}
});
it("reports unapproval and approval-reset system notes and ignores 429/rate-limit text inside 200 OK payloads", async () => {
vi.useFakeTimers();
let poll = 0;
const mrUrl = "https://gitlab.com/org/repo/-/merge_requests/429";
const encoded = encodeURIComponent("org/repo");
let approvalCalls = 0;
const { runner } = createFakeGlabRunner((args) => {
const endpoint = args.at(-1) ?? "";
if (endpoint === `projects/${encoded}/merge_requests/429`) {
poll += 1;
return httpJson({
iid: 429,
title: "Fix rate limit handling for HTTP 429 responses",
description: "Too many requests should trigger backoff",
state: "opened",
sha: "abc",
web_url: mrUrl,
head_pipeline: null,
});
}
if (endpoint.startsWith(`projects/${encoded}/merge_requests/429/discussions`)) {
const notes: Array<{
id: number;
system: boolean;
body: string;
author: { username: string };
}> = [
{
id: 1,
system: false,
body: "We hit HTTP 429 and rate limit errors in CI",
author: { username: "dev" },
},
];
if (poll >= 2) {
notes.push({
id: 2,
system: true,
body: "unapproved this merge request",
author: { username: "carol" },
});
}
if (poll >= 3) {
notes.push({
id: 3,
system: true,
body: "reset approvals from @carol by pushing to the branch",
author: { username: "dev" },
});
}
return httpJson([{ id: "d1", notes }], { "X-Next-Page": "" });
}
if (endpoint === `projects/${encoded}/merge_requests/429/approvals`) {
approvalCalls += 1;
return httpJson({ approvals_required: 1, approvals_left: 1, approved_by: [] });
}
throw new Error(`Unexpected: ${endpoint}`);
});
const service = createGitLabService({
runner,
resolveGlabPath: async () => "glab",
watchPollMs: 10_000,
});
const snapshots: ChangeRequestSnapshot[] = [];
const seen = new Set<string>();
try {
service.changeRequests!.observe(mrUrl, {
knownActivity: () => seen,
async snapshot(s) {
snapshots.push(s);
for (const item of s.activity) seen.add(item.id);
},
error(err) {
throw err;
},
});
await vi.advanceTimersByTimeAsync(25);
expect(snapshots).toHaveLength(1);
expect(approvalCalls).toBe(0);
expect(snapshots[0]!.activity).toEqual([
{ id: "comment:1", kind: "comment", url: `${mrUrl}#note_1` },
]);
await vi.advanceTimersByTimeAsync(10_000);
expect(approvalCalls).toBe(1);
expect(snapshots[1]!.activity).toContainEqual({
id: "approval-note:2",
kind: "approval",
url: `${mrUrl}#note_2`,
message: `Merge request approval removed by @carol (0/1 approvals): ${mrUrl}#note_2`,
});
await vi.advanceTimersByTimeAsync(10_000);
expect(approvalCalls).toBe(2);
expect(snapshots[2]!.activity).toContainEqual({
id: "approval-note:3",
kind: "approval",
url: `${mrUrl}#note_3`,
message: `Merge request approvals reset by @dev (0/1 approvals): ${mrUrl}#note_3`,
});
} finally {
service.dispose?.();
}
});
it("paginates jobs and discussions, rejects mid-pagination headSha changes, and treats partial errors as stale", async () => {
vi.useFakeTimers();
let mrReads = 0;
let discussionPage2Fails = true;
const mrUrl = "https://gitlab.com/org/repo/-/merge_requests/8";
const encoded = encodeURIComponent("org/repo");
const { runner } = createFakeGlabRunner((args) => {
const endpoint = args.at(-1) ?? "";
if (endpoint === `projects/${encoded}/merge_requests/8`) {
mrReads += 1;
// 1st poll: headSha changes mid-pagination (read 1 -> sha-1, recheck read 2 -> sha-2)
if (mrReads === 1) {
return httpJson({
iid: 8,
state: "opened",
sha: "sha-1",
web_url: mrUrl,
target_project_id: 1,
head_pipeline: { id: 20, project_id: 1, status: "running" },
});
}
return httpJson({
iid: 8,
state: "opened",
sha: "sha-2",
web_url: mrUrl,
target_project_id: 1,
head_pipeline: { id: 21, project_id: 1, status: "failed" },
});
}
if (endpoint.includes("/pipelines/20/jobs") && endpoint.endsWith("&page=1")) {
return httpJson(
[{ id: 1, name: "j1", stage: "test", status: "running", allow_failure: false }],
{ "X-Next-Page": "2" },
);
}
if (endpoint.includes("/pipelines/20/jobs") && endpoint.endsWith("&page=2")) {
return httpJson(
[{ id: 2, name: "j2", stage: "test", status: "success", allow_failure: false }],
{ "X-Next-Page": "" },
);
}
if (endpoint.includes("/pipelines/21/jobs")) {
return httpJson(
[{ id: 3, name: "j3", stage: "test", status: "failed", allow_failure: false }],
{ "X-Next-Page": "" },
);
}
if (endpoint.includes("/discussions") && endpoint.endsWith("&page=1")) {
return httpJson([{ id: "d1", notes: [{ id: 1, system: false, body: "p1" }] }], {
"X-Next-Page": "2",
});
}
if (endpoint.includes("/discussions") && endpoint.endsWith("&page=2")) {
if (discussionPage2Fails) {
discussionPage2Fails = false;
throw Object.assign(new Error("500"), { code: 1, stderr: "500 Internal Server Error" });
}
return httpJson([{ id: "d2", notes: [{ id: 2, system: false, body: "p2" }] }], {
"X-Next-Page": "",
});
}
if (endpoint.endsWith("/approvals")) {
return httpJson({ approvals_required: 0, approvals_left: 0, approved_by: [] });
}
throw new Error(`Unexpected: ${endpoint}`);
});
const service = createGitLabService({
runner,
resolveGlabPath: async () => "glab",
watchPollMs: 10_000,
});
const snapshots: ChangeRequestSnapshot[] = [];
const errors: Error[] = [];
try {
service.changeRequests!.observe(mrUrl, {
async snapshot(s) {
snapshots.push(s);
},
error(err) {
errors.push(err as Error);
},
});
// Poll 1 fails because headSha changed during multi-page job pagination
await vi.advanceTimersByTimeAsync(25);
expect(snapshots).toHaveLength(0);
expect(errors).toHaveLength(1);
expect(errors[0]!.message).toMatch(/changed during pagination/i);
// Poll 2 (after 10s backoff) fails because discussion page 2 returns 500 — must NOT emit partial snapshot
await vi.advanceTimersByTimeAsync(10_000);
expect(snapshots).toHaveLength(0);
expect(errors).toHaveLength(2);
// Poll 3 (after 20s exponential backoff) succeeds with complete paginated discussions and failed check
await vi.advanceTimersByTimeAsync(20_000);
expect(snapshots).toHaveLength(1);
expect(snapshots[0]).toMatchObject({
headSha: "sha-2",
checksState: "failed",
checks: [{ id: "job:3", name: "j3", state: "failed" }],
activity: [
{ id: "comment:1", kind: "comment", url: `${mrUrl}#note_1` },
{ id: "comment:2", kind: "comment", url: `${mrUrl}#note_2` },
],
});
} finally {
service.dispose?.();
}
});
it("verifies self-hosted auth once, honors 429 Retry-After, and skips remaining pages on release", async () => {
vi.useFakeTimers();
vi.setSystemTime(1_700_000_000_000);
const mrUrl = "https://git.corp.internal/team/app/-/merge_requests/3";
const encoded = encodeURIComponent("team/app");
let authChecks = 0;
let mrCalls = 0;
const { runner } = createFakeGlabRunner((args) => {
if (args[0] === "auth" && args[1] === "status") {
authChecks += 1;
return { stdout: "Logged in", stderr: "" };
}
const endpoint = args.at(-1) ?? "";
if (endpoint === `projects/${encoded}/merge_requests/3`) {
mrCalls += 1;
if (mrCalls === 1) {
throw Object.assign(new Error("429"), {
code: 1,
stdout:
'HTTP/2.0 429 Too Many Requests\r\nRetry-After: 45\r\n\r\n{"message":"Too many requests"}',
stderr: "429 Too Many Requests",
});
}
return httpJson({
iid: 3,
state: "opened",
sha: "xyz",
web_url: mrUrl,
head_pipeline: null,
});
}
if (endpoint.includes("/discussions")) {
return httpJson([], { "X-Next-Page": "" });
}
if (endpoint.endsWith("/approvals")) {
throw Object.assign(new Error("404"), { code: 1, stderr: "404 Not Found" });
}
throw new Error(`Unexpected: ${args.join(" ")}`);
});
const service = createGitLabService({
runner,
resolveGlabPath: async () => "glab",
watchPollMs: 10_000,
});
const snapshots: ChangeRequestSnapshot[] = [];
const errors: unknown[] = [];
try {
const release = service.changeRequests!.observe(mrUrl, {
async snapshot(s) {
snapshots.push(s);
},
error(err) {
errors.push(err);
},
});
await vi.advanceTimersByTimeAsync(25);
expect(authChecks).toBe(1);
expect(mrCalls).toBe(1);
expect(errors).toHaveLength(1);
// Still paused before 45s Retry-After expires
await vi.advanceTimersByTimeAsync(44_999);
expect(mrCalls).toBe(1);
// Resumes at 45s without re-running auth status, and tolerates 404 on /approvals (CE)
await vi.advanceTimersByTimeAsync(1);
expect(authChecks).toBe(1);
expect(mrCalls).toBe(2);
expect(snapshots).toHaveLength(1);
expect(snapshots[0]!.headSha).toBe("xyz");
release();
} finally {
service.dispose?.();
}
});
it("stops paginating immediately when released mid-read and surfaces failed bridge jobs", async () => {
vi.useFakeTimers();
const mrUrl = "https://gitlab.com/org/repo/-/merge_requests/15";
const encoded = encodeURIComponent("org/repo");
let releaseFirstPage!: () => void;
let discussionPage2Called = false;
const { runner } = createFakeGlabRunner(async (args) => {
const endpoint = args.at(-1) ?? "";
if (endpoint === `projects/${encoded}/merge_requests/15`) {
return httpJson({
iid: 15,
state: "opened",
sha: "sha-bridge",
web_url: mrUrl,
target_project_id: 7,
head_pipeline: {
id: 88,
project_id: 7,
status: "failed",
web_url: "https://gitlab.com/org/repo/-/pipelines/88",
},
});
}
if (endpoint.includes("/pipelines/88/jobs")) {
return httpJson(
[{ id: 1, name: "prepare", stage: "prep", status: "success", allow_failure: false }],
{ "X-Next-Page": "" },
);
}
if (endpoint.includes("/pipelines/88/bridges")) {
return httpJson(
[
{
id: 2,
name: "downstream-e2e",
stage: "trigger",
status: "failed",
allow_failure: false,
web_url: "https://gitlab.com/org/repo/-/jobs/2",
},
],
{ "X-Next-Page": "" },
);
}
if (endpoint.includes("/discussions") && endpoint.endsWith("&page=1")) {
await new Promise<void>((resolve) => {
releaseFirstPage = resolve;
});
return httpJson([{ id: "d1", notes: [{ id: 10, system: false, body: "hi" }] }], {
"X-Next-Page": "2",
});
}
if (endpoint.includes("/discussions") && endpoint.endsWith("&page=2")) {
discussionPage2Called = true;
return httpJson([], { "X-Next-Page": "" });
}
if (endpoint.endsWith("/approvals")) {
return httpJson({ approvals_required: 0, approvals_left: 0, approved_by: [] });
}
throw new Error(`Unexpected: ${endpoint}`);
});
const service = createGitLabService({
runner,
resolveGlabPath: async () => "glab",
watchPollMs: 10_000,
});
const snapshots: ChangeRequestSnapshot[] = [];
const errors: unknown[] = [];
try {
const release = service.changeRequests!.observe(mrUrl, {
async snapshot(s) {
snapshots.push(s);
},
error(err) {
errors.push(err);
},
});
await vi.advanceTimersByTimeAsync(25);
await vi.waitFor(() => expect(releaseFirstPage).toBeTypeOf("function"));
release();
releaseFirstPage();
await vi.advanceTimersByTimeAsync(0);
expect(discussionPage2Called).toBe(false);
expect(snapshots).toEqual([]);
expect(errors).toEqual([]);
// Re-observe without releasing early to verify failed bridge check is surfaced.
service.changeRequests!.observe(mrUrl, {
async snapshot(s) {
snapshots.push(s);
},
error(err) {
errors.push(err);
},
});
await vi.advanceTimersByTimeAsync(25);
await vi.waitFor(() => expect(releaseFirstPage).toBeTypeOf("function"));
releaseFirstPage();
await vi.advanceTimersByTimeAsync(0);
expect(discussionPage2Called).toBe(true);
expect(snapshots).toHaveLength(1);
expect(snapshots[0]!.checks).toContainEqual({
id: "bridge:2",
name: "downstream-e2e",
state: "failed",
url: "https://gitlab.com/org/repo/-/jobs/2",
});
} finally {
service.dispose?.();
}
});
});
@@ -1,855 +0,0 @@
import { z } from "zod";
import { normalizeHost } from "@getpaseo/protocol/git-remote";
import { GITLAB_ACTIVE_PIPELINE_STATUS_SET } from "@getpaseo/protocol/gitlab-pipeline";
import {
ChangeRequestRateLimitError,
createPerHostChangeRequestPoller,
parseCliHttpResponse,
parseRetryAfterMs,
} 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: z.string().optional(),
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(),
approved_by: z.array(z.unknown()).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();
if (state === "opened") 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 computeApprovalsGiven(approvals: GitLabWatchApprovals): number {
if (approvals.approved_by != null) {
return approvals.approved_by.length;
}
if (approvals.approvals_required != null && approvals.approvals_left != null) {
return Math.max(0, approvals.approvals_required - approvals.approvals_left);
}
return 0;
}
function summarizeApprovalCount(approvals: GitLabWatchApprovals): ApprovalCount {
return {
given: computeApprovalsGiven(approvals),
required: approvals.approvals_required ?? 0,
};
}
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 isApprovalsEndpointUnavailable(status: number | null, text: string): boolean {
if (status === 403 || status === 404 || status === 501) return true;
return /\b(403|404|501|not found|forbidden)\b/i.test(text);
}
function isNotFoundError(status: number | null, text: string): boolean {
if (status === 404) return true;
return /\b(404|not found)\b/i.test(text);
}
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;
const authenticatedWatchHosts = new Set<string>();
async function ensureHostAuthenticated(host: string): Promise<void> {
if (host === GITLAB_CLOUD_HOST || authenticatedWatchHosts.has(host)) {
return;
}
await options.runCommand(["auth", "status", "--hostname", host], {
cwd: process.cwd(),
envOverlay: { GITLAB_HOST: host },
});
authenticatedWatchHosts.add(host);
}
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;
}): 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) {
throw createRateLimitError(params.host, now(), params.headers);
}
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>;
pauseHost(untilMs: number): void;
}): Promise<{ data: T; headers: ReadonlyMap<string, string> }> {
const args = ["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) 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,
});
const proactivePause = parseRetryAfterMs(parsed.headers, now());
if (proactivePause !== null) {
params.pauseHost(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>;
isObserved(): boolean;
pauseHost(untilMs: number): void;
}): 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.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,
pauseHost: params.pauseHost,
});
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 extractCommandErrorStatus(error: unknown): { status: number | null; stderr: string } {
if (!options.isCommandError(error)) return { status: null, stderr: "" };
const status = error.stdout ? parseCliHttpResponse(error.stdout).status : null;
return { status, stderr: error.stderr };
}
async function readPipelineChecks(params: {
host: string;
mrEndpoint: string;
encodedProject: string;
mr: GitLabWatchMr;
headSha: string;
isObserved(): boolean;
pauseHost(untilMs: number): void;
}): Promise<ChangeRequestSnapshot["checks"]> {
const pipeline = params.mr.head_pipeline;
if (!pipeline) return [];
const pipelineProject = resolvePipelineProjectId(pipeline, params.mr, params.encodedProject);
const jobsResult = await apiGetAllPages({
host: params.host,
endpoint: `projects/${pipelineProject}/pipelines/${pipeline.id}/jobs`,
itemSchema: gitLabWatchJobSchema,
isObserved: params.isObserved,
pauseHost: params.pauseHost,
});
if (!params.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,
isObserved: params.isObserved,
pauseHost: params.pauseHost,
});
}
// Guard against headSha or head_pipeline shifting while paginating check pages.
if (jobsResult.pagesRead > 1 || fetchedBridges) {
const { data: recheck } = await apiGet({
host: params.host,
endpoint: params.mrEndpoint,
schema: gitLabWatchMrSchema,
pauseHost: params.pauseHost,
});
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"];
isObserved(): boolean;
pauseHost(untilMs: number): void;
}): Promise<void> {
try {
const bridgesResult = await apiGetAllPages({
host: params.host,
endpoint: `projects/${params.pipelineProject}/pipelines/${params.pipeline.id}/bridges`,
itemSchema: gitLabWatchJobSchema,
isObserved: params.isObserved,
pauseHost: params.pauseHost,
});
for (const bridge of bridgesResult.items) {
params.checks.push(toWatchCheck(bridge, "bridge"));
}
} catch (error) {
const { status, stderr } = extractCommandErrorStatus(error);
if (!isNotFoundError(status, stderr)) {
throw error;
}
}
if (!params.checks.some((check) => check.state === "failed")) {
const pipelineUrl = checkUrlSchema.safeParse(params.pipeline.web_url).data;
params.checks.push({
id: `pipeline:${params.pipeline.id}`,
name: `Pipeline #${params.pipeline.id}`,
state: "failed",
...(pipelineUrl ? { url: pipelineUrl } : {}),
});
}
}
async function readOptionalApprovalCount(params: {
host: string;
endpoint: string;
pauseHost(untilMs: number): void;
}): Promise<ApprovalCount | null> {
try {
const { data: approvals } = await apiGet({
host: params.host,
endpoint: params.endpoint,
schema: gitLabWatchApprovalsSchema,
pauseHost: params.pauseHost,
});
return summarizeApprovalCount(approvals);
} catch (error) {
if (options.isAuthError(error) || error instanceof ChangeRequestRateLimitError) {
throw error;
}
const { status, stderr } = extractCommandErrorStatus(error);
if (isApprovalsEndpointUnavailable(status, stderr)) {
return null;
}
throw error;
}
}
async function readMergeRequest(context: {
url: string;
host: string;
knownActivity(): ReadonlySet<string> | undefined;
isObserved(): boolean;
pauseHost(untilMs: number): void;
}): Promise<ChangeRequestSnapshot> {
const { hostWithPort, projectPath, iid } = parseGitLabMergeRequestUrl(context.url);
await ensureHostAuthenticated(hostWithPort);
const encodedProject = encodeURIComponent(projectPath);
const mrEndpoint = `projects/${encodedProject}/merge_requests/${iid}`;
const { data: mr } = await apiGet({
host: hostWithPort,
endpoint: mrEndpoint,
schema: gitLabWatchMrSchema,
pauseHost: context.pauseHost,
});
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 mrWebUrl = mr.web_url || context.url;
const checks = await readPipelineChecks({
host: hostWithPort,
mrEndpoint,
encodedProject,
mr,
headSha,
isObserved: context.isObserved,
pauseHost: context.pauseHost,
});
const discussionsResult = await apiGetAllPages({
host: hostWithPort,
endpoint: `projects/${encodedProject}/merge_requests/${iid}/discussions`,
itemSchema: gitLabWatchDiscussionSchema,
isObserved: context.isObserved,
pauseHost: context.pauseHost,
});
if (!context.isObserved()) {
throw new Error("Change request observation ended");
}
const { humanActivity, approvalNotes } = parseDiscussionItems(
discussionsResult.items,
mrWebUrl,
);
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: hostWithPort,
endpoint: `projects/${encodedProject}/merge_requests/${iid}/approvals`,
pauseHost: context.pauseHost,
})
: 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,
onError(error, host) {
if (options.isAuthError(error)) {
authenticatedWatchHosts.delete(host);
}
},
});
return {
resolve: resolveGitLabChangeRequest,
describe: describeGitLabChangeRequest,
observe(url, callbacks) {
return poller.observe(url, callbacks);
},
dispose() {
authenticatedWatchHosts.clear();
poller.dispose();
},
};
}
+3 -31
View File
@@ -60,7 +60,6 @@ import {
CHECK_TRAIT_WARNING,
} from "@getpaseo/protocol/check-traits";
import { GITLAB_ACTIVE_PIPELINE_STATUS_SET } from "@getpaseo/protocol/gitlab-pipeline";
import { createGitLabChangeRequestSource } from "./gitlab-change-requests.js";
import { isGitLabStatusFacts, type GitLabStatusFacts } from "./gitlab-facts.js";
const GLAB_ENV = {
@@ -113,9 +112,6 @@ export interface CreateGitLabServiceOptions {
runner?: GlabCommandRunner;
resolveGlabPath?: () => Promise<string | null>;
resolveRemoteUrl?: (cwd: string) => Promise<string | null>;
now?: () => number;
watchPollMs?: number;
watchInitialDelayMs?: number;
}
const GitLabPipelineSchema = z
@@ -929,37 +925,19 @@ export function createGitLabService(options: CreateGitLabServiceOptions = {}): F
const resolveGlab = createCachedCliPathResolver(options.resolveGlabPath ?? resolveGlabPath);
const resolveRemoteUrl = options.resolveRemoteUrl ?? defaultResolveRemoteUrl;
async function runRaw(
args: string[],
runOptions: GlabCommandRunnerOptions,
): Promise<GlabCommandResult> {
async function run(args: string[], runOptions: GlabCommandRunnerOptions): Promise<string> {
const glabPath = await resolveGlab();
if (!glabPath) {
throw new GlabCliMissingError();
}
try {
return await runner(args, runOptions);
const result = await runner(args, runOptions);
return result.stdout.trim();
} catch (error) {
throw glabCliRunner.normalizeError(error, { args, cwd: runOptions.cwd });
}
}
async function run(args: string[], runOptions: GlabCommandRunnerOptions): Promise<string> {
const result = await runRaw(args, runOptions);
return result.stdout.trim();
}
const changeRequests = createGitLabChangeRequestSource({
runCommand: runRaw,
isAuthError: (error) => error instanceof GlabAuthenticationError,
isCommandError: (error): error is GlabCommandError => error instanceof GlabCommandError,
createAuthError: (stderr) => new GlabAuthenticationError({ stderr }),
createCommandError: (params) => new GlabCommandError(params),
now: options.now,
pollIntervalMs: options.watchPollMs,
initialDelayMs: options.watchInitialDelayMs,
});
// Centralize parse + validate so a malformed or empty glab payload surfaces as
// a classified GlabCommandError (with args + cwd) instead of a raw
// SyntaxError/ZodError that bypasses the Glab* error classification.
@@ -1508,12 +1486,6 @@ export function createGitLabService(options: CreateGitLabServiceOptions = {}): F
return { success: true };
},
changeRequests,
invalidate(_input: { cwd: string }): void {},
dispose(): void {
changeRequests.dispose();
},
};
}
@@ -65,9 +65,46 @@ it("discovers the resolved account and maps the CLI's quota buckets", async () =
expect(await source.fetch(accounts[0]!.input)).toMatchObject({
status: "available",
windows: [
{ id: "gemini-5h", usedPct: 75, remainingPct: 25, resetsAt: "2026-11-19T14:25:08Z" },
{ id: "gemini-weekly", usedPct: expect.closeTo(30), summary: true },
{ id: "disabled", usedPct: null, remainingPct: null },
{
id: "gemini-5h",
shortLabel: "5h",
usedPct: 75,
remainingPct: 25,
resetsAt: "2026-11-19T14:25:08Z",
},
{ id: "gemini-weekly", shortLabel: "wk", usedPct: expect.closeTo(30), summary: true },
{ id: "disabled", shortLabel: "wk", usedPct: null, remainingPct: null },
],
});
});
it("uses compact group and period shorthands when multiple groups are reported", async () => {
const directory = await mkdtemp(path.join(tmpdir(), "paseo-antigravity-usage-"));
directories.push(directory);
const cli = path.join(directory, "cli.cjs");
await writeFile(
cli,
`
console.log(JSON.stringify({ status: 'SUCCESS', command: { name: 'usage', data: { groups: [
{ name: 'Gemini Models', buckets: [
{ id: 'gemini-weekly', name: 'Weekly Limit Remaining', window: 'weekly', remaining_fraction: 0.9 },
{ id: 'gemini-5h', name: 'Five Hour Limit Remaining', window: '5h', remaining_fraction: 0.8 }
] },
{ name: 'Claude and GPT models', buckets: [
{ id: '3p-weekly', name: 'Weekly Limit Remaining', window: 'weekly', remaining_fraction: 1 }
] }
] } } }));
`,
);
const launch = { command: process.execPath, args: [cli, "acp"], env: { HOME: directory } };
const source = new Usage().registration();
const [account] = await source.discover({ kind: "global", launch });
expect(await source.fetch(account!.input)).toMatchObject({
status: "available",
windows: [
{ id: "gemini-weekly", shortLabel: "Gemini wk" },
{ id: "gemini-5h", shortLabel: "Gemini 5h" },
{ id: "3p-weekly", shortLabel: "Claude and GPT wk" },
],
});
});
+26 -2
View File
@@ -48,6 +48,28 @@ function accountKey(env: ProviderLaunch["env"]): string {
);
}
function shortWindow(window: string): string {
const trimmed = window.trim();
const normalized = trimmed.toLowerCase();
if (normalized === "weekly") return "wk";
if (normalized === "monthly") return "mo";
return trimmed;
}
function shortGroupName(name: string): string {
return name
.trim()
.replace(/\s+models$/i, "")
.trim();
}
function formatShortLabel(groupName: string, window: string, includeGroup: boolean): string {
const period = shortWindow(window);
if (!includeGroup) return period;
const scope = shortGroupName(groupName);
return scope ? `${scope} ${period}` : period;
}
export class Usage {
private readonly launches = new Map<string, ProviderLaunch>();
@@ -94,7 +116,9 @@ export class Usage {
throw new Error(data.error || data.response || `agy usage returned ${data.status}`);
}
if (!data.command) throw new Error("agy did not return usage data");
const windows = data.command.data.groups.flatMap((group) =>
const groups = data.command.data.groups;
const includeGroup = groups.length > 1;
const windows = groups.flatMap((group) =>
group.buckets.flatMap((bucket) => {
if (!bucket.disabled && bucket.remaining_fraction == null) return [];
const used = bucket.disabled ? null : (1 - bucket.remaining_fraction!) * 100;
@@ -102,7 +126,7 @@ export class Usage {
windowFromUsedPct({
id: bucket.id,
label: `${group.name} · ${bucket.name}${bucket.disabled ? " · Disabled" : ""}`,
shortLabel: `${group.name} ${bucket.window}`,
shortLabel: formatShortLabel(group.name, bucket.window, includeGroup),
summary: !bucket.disabled && bucket.window === "weekly",
utilizationPct: used,
resetsAt: bucket.disabled ? null : bucket.reset_time,