mirror of
https://github.com/getpaseo/paseo.git
synced 2026-11-17 05:45:07 +00:00
Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
eabbd3d97c | ||
|
|
0bac18f359 | ||
|
|
3eedffc4ac | ||
|
|
e5352c9890 |
+1
-1
@@ -76,7 +76,7 @@ Dense toolbar rows, such as the composer's, are the exception to the 44pt contro
|
||||
|
||||
In the composer, the first glyph's ink starts on the text column's edge, and the trailing control is always a disc, so the row does not shift as it changes between voice mode, send and stop. The disc nests into the corner, as far from the right edge as from the bottom, and touch-sized the composer's corner radius is concentric with it (`packages/app/src/composer/input/toolbar-rails.ts`). Touch-sized the disc keeps a 6pt clearance from its neighbour, because it is always painted and a pressed neighbour would merge with it. The attach button sits 2pt closer to the picker than its highlight would put it: the plus is all thin arms, so the full gap reads wide. That offset is set by eye.
|
||||
|
||||
One gate, `resolveControlSizing`, picks touch or pointer sizing: touch when the layout is compact or the device has a touch screen. An iPad with the sidebar docked is wide and touch-sized; a desktop is pointer-sized; a phone is both compact and touch. The touch-screen fact is read once at startup (`hasTouchScreen` in `hooks/use-fine-pointer.ts`), so attaching a mouse or keyboard to a tablet never shrinks its controls. Stylesheets take sizes from `bySizing({ touch, pointer })`, which resolves to a breakpoint value, so a caller never sees which sizing it got. Rows, icon buttons and icon slots take theirs from `styles/density.ts`, which uses the same gate. An `{ xs, md }` literal for a hit target or glyph is wrong: on an iPad it yields the pointer size.
|
||||
One gate, `resolveControlSizing`, picks touch or pointer sizing: touch when the layout is compact or touch is the primary input. An iPad with the sidebar docked is wide and touch-sized; a desktop is pointer-sized; a phone is both compact and touch. The primary input comes from `(pointer: coarse)` (`hasTouchPrimaryPointer` in `hooks/pointer-capabilities.ts`), not from whether a touch screen exists: WebKit keeps touch primary on an iPad with a trackpad attached, and Chromium reports a fine primary pointer for a laptop with a touch screen that its trackpad drives. The fact is read once at startup: attaching a pointer to a tablet does not shrink its controls, and a 2-in-1 launched with a pointer keeps pointer sizes after it switches to tablet mode until the app reloads. Stylesheets take sizes from `bySizing({ touch, pointer })`, which resolves to a breakpoint value, so a caller never sees which sizing it got. Rows, icon buttons and icon slots take theirs from `styles/density.ts`, which uses the same gate. An `{ xs, md }` literal for a hit target or glyph is wrong: on an iPad it yields the pointer size.
|
||||
|
||||
Buttons are pills (`borderRadius.full`) with medium-weight labels; an icon-only button is a circle. `<Switch>` follows the same two sizes: a 34×20 track by default and in `sm`, 44×26 where controls are touch-sized, and it reserves its size's control height so a row holding one lines up with a row holding a button. Buttons, text fields, dropdown triggers, and `<SegmentedControl>` (`packages/app/src/components/ui/segmented-control.tsx`) share the size contract — the same size name means the same height and label size on every control kind, so controls in one row line up. Segments run tighter than a button, because the gap between segments already reads as padding. The selected segment is a `surface3` fill with `foreground` text, not an inverted one — inverting it inside thin chrome puts a white slab in the toolbar. A settings row sizes the controls in its trailing slot itself, default in a card and `sm` when nested (`packages/app/src/components/ui/control-size.tsx`), so don't pass a size to a button, dropdown or field placed in a row. Code that computes with a control's height outside a stylesheet uses `controlHeightForLayout`. Never shrink a control's font or padding locally to fit a context — if the context needs a smaller control, the size tier is missing or the wrong one is in use.
|
||||
|
||||
|
||||
+6
-19
@@ -97,25 +97,12 @@ Register the adapter in `defaultForgeRegistry` with:
|
||||
- `matchesHost` from manifest `cloudHosts`
|
||||
- `probeHost` when self-hosted/Enterprise detection is supported
|
||||
|
||||
Current change-request lookup prefers an open request for the branch and repository.
|
||||
A closed or merged request belongs to a workspace only when its checkout commit
|
||||
is in the forge's PR/MR commit list. Commits inherited from the base do not count.
|
||||
Display and auto-archive share this rule, preserving squash-merged requests and
|
||||
requests updated remotely while rejecting a fresh workspace on their base commit.
|
||||
A rewritten or newly advanced checkout no longer matches the terminal request.
|
||||
|
||||
Commit membership stays in the server snapshot; clients receive the selected
|
||||
request without its commit list. Archive uses that same evidence after refreshing
|
||||
the workspace. It still requires an observed open-to-merged transition and the
|
||||
workspace safety checks; being behind alone does not block it.
|
||||
|
||||
Containment spawns no Git commands and fetches no Git objects. GitHub loads only terminal
|
||||
commit IDs in a separate batch under the same rate budget, newest page first,
|
||||
and remembers pages by PR head. Open requests need no membership read. GitLab,
|
||||
Gitea, and legacy GitHub cache successful terminal commit lists by request head;
|
||||
failed reads stay retryable and reject the lookup, preserving its previous snapshot. A failed
|
||||
GitHub commit batch does not block workspaces whose status is already complete.
|
||||
Missing membership evidence leaves the workspace active.
|
||||
Current change-request lookup matches the branch and repository for both open and
|
||||
terminal requests. Prefer an open request, then a terminal request at the local
|
||||
HEAD, then the most recently updated terminal request. A reused branch can show
|
||||
its previous request until a new one opens. Auto-archive separately requires an
|
||||
observed open-to-merged transition and a fresh exact match between checkout HEAD
|
||||
and the PR head, along with the existing workspace safety checks.
|
||||
|
||||
Keep checkout HEAD in adapter cache and poll identities so checkout changes
|
||||
refresh the facts used by archive eligibility.
|
||||
|
||||
+1
-1
@@ -1 +1 @@
|
||||
sha256-alhf4ULeJ7n8sfgnxsX8Ugw40GB7jz0u9R/3/MOveIw=
|
||||
sha256-hN+Klz3jXugHs5MsVzIQIwIa/HGbpdJ04qolKvbsOuk=
|
||||
|
||||
Generated
+37
-37
@@ -130,22 +130,22 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@anthropic-ai/claude-agent-sdk": {
|
||||
"version": "0.3.246",
|
||||
"resolved": "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk/-/claude-agent-sdk-0.3.246.tgz",
|
||||
"integrity": "sha512-FtR0HoHHNqeqJWjZN8qLUAzZVFUI9ztXYNPPwv98Ecmv9qq2QTauI8IzkY26CC0mleWAqb9RQEW2C0OtiUliug==",
|
||||
"version": "0.3.326",
|
||||
"resolved": "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk/-/claude-agent-sdk-0.3.326.tgz",
|
||||
"integrity": "sha512-BUTSky/4YWfL/MxC+4kV0NDbJFjbJPoQMFEk/s9G6hV9LUfYPMbsWz94bFQ7ZIo2ubj2xwJ2c2NVxkNlQhVw+Q==",
|
||||
"license": "SEE LICENSE IN README.md",
|
||||
"engines": {
|
||||
"node": ">=18.0.0"
|
||||
"node": ">=18.14.0"
|
||||
},
|
||||
"optionalDependencies": {
|
||||
"@anthropic-ai/claude-agent-sdk-darwin-arm64": "0.3.246",
|
||||
"@anthropic-ai/claude-agent-sdk-darwin-x64": "0.3.246",
|
||||
"@anthropic-ai/claude-agent-sdk-linux-arm64": "0.3.246",
|
||||
"@anthropic-ai/claude-agent-sdk-linux-arm64-musl": "0.3.246",
|
||||
"@anthropic-ai/claude-agent-sdk-linux-x64": "0.3.246",
|
||||
"@anthropic-ai/claude-agent-sdk-linux-x64-musl": "0.3.246",
|
||||
"@anthropic-ai/claude-agent-sdk-win32-arm64": "0.3.246",
|
||||
"@anthropic-ai/claude-agent-sdk-win32-x64": "0.3.246"
|
||||
"@anthropic-ai/claude-agent-sdk-darwin-arm64": "0.3.326",
|
||||
"@anthropic-ai/claude-agent-sdk-darwin-x64": "0.3.326",
|
||||
"@anthropic-ai/claude-agent-sdk-linux-arm64": "0.3.326",
|
||||
"@anthropic-ai/claude-agent-sdk-linux-arm64-musl": "0.3.326",
|
||||
"@anthropic-ai/claude-agent-sdk-linux-x64": "0.3.326",
|
||||
"@anthropic-ai/claude-agent-sdk-linux-x64-musl": "0.3.326",
|
||||
"@anthropic-ai/claude-agent-sdk-win32-arm64": "0.3.326",
|
||||
"@anthropic-ai/claude-agent-sdk-win32-x64": "0.3.326"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@anthropic-ai/sdk": ">=0.93.0",
|
||||
@@ -154,9 +154,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@anthropic-ai/claude-agent-sdk-darwin-arm64": {
|
||||
"version": "0.3.246",
|
||||
"resolved": "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk-darwin-arm64/-/claude-agent-sdk-darwin-arm64-0.3.246.tgz",
|
||||
"integrity": "sha512-pYDv2RT+UVOvEapMEWKf7Gm5a87Si1Zf+XR23IMGYbG5mESatNJ8Gz2PmkrwfTezZknb0ljWZe8zgcTFITM3dA==",
|
||||
"version": "0.3.326",
|
||||
"resolved": "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk-darwin-arm64/-/claude-agent-sdk-darwin-arm64-0.3.326.tgz",
|
||||
"integrity": "sha512-D3ZbowCMdKNet0YPZlsJxdJUW1t1Q8KLy1BwNd+5eilf18TlCRtWZlm8DrewFLmu/gxBK7gcsq6uysrIVbPyQg==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
@@ -167,9 +167,9 @@
|
||||
]
|
||||
},
|
||||
"node_modules/@anthropic-ai/claude-agent-sdk-darwin-x64": {
|
||||
"version": "0.3.246",
|
||||
"resolved": "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk-darwin-x64/-/claude-agent-sdk-darwin-x64-0.3.246.tgz",
|
||||
"integrity": "sha512-yl+gMMFUQ8++SBaxUe2JxBqU0LOJO4HZTsWWTOrH5kRlTRhdQDF/lESsoNXCHgfF/+77YNKgef0h+rl/D12Jfg==",
|
||||
"version": "0.3.326",
|
||||
"resolved": "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk-darwin-x64/-/claude-agent-sdk-darwin-x64-0.3.326.tgz",
|
||||
"integrity": "sha512-m8K3Im2S8STdAVBrriuDZyJcnjsu/Vc3476wIOqTAefnCCdtdZ4AHcOcWxt+4KIHE5Vx1qT2qacTRrQBaVVweA==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
@@ -180,9 +180,9 @@
|
||||
]
|
||||
},
|
||||
"node_modules/@anthropic-ai/claude-agent-sdk-linux-arm64": {
|
||||
"version": "0.3.246",
|
||||
"resolved": "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk-linux-arm64/-/claude-agent-sdk-linux-arm64-0.3.246.tgz",
|
||||
"integrity": "sha512-t7AEewD7bcjZYMmrfFLjsUSxPo4z+5J5O5cC9V2zOvAhNkefdMeGWI2/1cdqZxuaOiFVt46byjlZuiNNunF+bQ==",
|
||||
"version": "0.3.326",
|
||||
"resolved": "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk-linux-arm64/-/claude-agent-sdk-linux-arm64-0.3.326.tgz",
|
||||
"integrity": "sha512-nYVN8jCcH490DCXIvby7rllzQFxLzKeKClfo2u/yv7mx3ipZQv344caULL/amwZ8w8GUzYyZ8hnS6pI9goSq+A==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
@@ -193,9 +193,9 @@
|
||||
]
|
||||
},
|
||||
"node_modules/@anthropic-ai/claude-agent-sdk-linux-arm64-musl": {
|
||||
"version": "0.3.246",
|
||||
"resolved": "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk-linux-arm64-musl/-/claude-agent-sdk-linux-arm64-musl-0.3.246.tgz",
|
||||
"integrity": "sha512-AeiDXveuA9dVRDouSRiQzL40P3dOuJPfZOlwwsFNbVUN0D+06WtwgmeWYnyRG4dxsM67Pf4lYcRZ0x9pfEZUwQ==",
|
||||
"version": "0.3.326",
|
||||
"resolved": "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk-linux-arm64-musl/-/claude-agent-sdk-linux-arm64-musl-0.3.326.tgz",
|
||||
"integrity": "sha512-baSsuP2/wuWujRpHjKT4WkJB5lhttqKq9jcTfY2KRtQpylbk8E5PWcct/pmwJfNCKIUoE8CD+JpmoWzsdd5Ajw==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
@@ -206,9 +206,9 @@
|
||||
]
|
||||
},
|
||||
"node_modules/@anthropic-ai/claude-agent-sdk-linux-x64": {
|
||||
"version": "0.3.246",
|
||||
"resolved": "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk-linux-x64/-/claude-agent-sdk-linux-x64-0.3.246.tgz",
|
||||
"integrity": "sha512-BIbBlJ6x7Cys6UFvahUfce26H+U+Q4tLWjKRD39AaV7JvRav8/vfdFytzWq6E+h9hT1OOWYuPYx2gMn5vDhZhQ==",
|
||||
"version": "0.3.326",
|
||||
"resolved": "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk-linux-x64/-/claude-agent-sdk-linux-x64-0.3.326.tgz",
|
||||
"integrity": "sha512-WMhDY07gk2O0E8FXTbrVYmPjSLFaYPDCPwsNueVxm6vZ7ek+lPaKuOMAxTb1K07TzSmTOexoWeX2Y9VrbVDMpw==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
@@ -219,9 +219,9 @@
|
||||
]
|
||||
},
|
||||
"node_modules/@anthropic-ai/claude-agent-sdk-linux-x64-musl": {
|
||||
"version": "0.3.246",
|
||||
"resolved": "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk-linux-x64-musl/-/claude-agent-sdk-linux-x64-musl-0.3.246.tgz",
|
||||
"integrity": "sha512-+3PrWX3qXgakO3tZImr7keKFry5XIkbHBEaUxgi3/RtPmxGwS+JdVAr0xxzOoC2F6Y66Kn0lUnztRnZHORBc+Q==",
|
||||
"version": "0.3.326",
|
||||
"resolved": "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk-linux-x64-musl/-/claude-agent-sdk-linux-x64-musl-0.3.326.tgz",
|
||||
"integrity": "sha512-kK9VO3uFqNd4wgeU0Cefluam5AdPu6mvF1nn6aboGy8TA5NoxlWTmA4/AwMhK39zK1S9Q2OjeX0JtAahYlIchw==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
@@ -232,9 +232,9 @@
|
||||
]
|
||||
},
|
||||
"node_modules/@anthropic-ai/claude-agent-sdk-win32-arm64": {
|
||||
"version": "0.3.246",
|
||||
"resolved": "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk-win32-arm64/-/claude-agent-sdk-win32-arm64-0.3.246.tgz",
|
||||
"integrity": "sha512-JV8b28OJ8d+EMVEVIWlN3aEkT8uSehO3ZN/PJzXFG7Jgn56oVYUew4aY9vK4jao/4E4mdfzvs358w4HcTBUzVw==",
|
||||
"version": "0.3.326",
|
||||
"resolved": "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk-win32-arm64/-/claude-agent-sdk-win32-arm64-0.3.326.tgz",
|
||||
"integrity": "sha512-S+Ai+HhGRVFfTDmYWRfTrdWF3b4KMsfLSThZCqRJ0WCOKOXrRShMKV1hqqHBljx/wkMDPCpY0V/9S/e6w57eGQ==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
@@ -245,9 +245,9 @@
|
||||
]
|
||||
},
|
||||
"node_modules/@anthropic-ai/claude-agent-sdk-win32-x64": {
|
||||
"version": "0.3.246",
|
||||
"resolved": "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk-win32-x64/-/claude-agent-sdk-win32-x64-0.3.246.tgz",
|
||||
"integrity": "sha512-omI65bYGynLpE1Ybijk56K1wBnt0H6WujNwlg1LzIdeHrYmpUxoqncK92xKH5kb9XWUz3byHqArbv7wsT+M/2A==",
|
||||
"version": "0.3.326",
|
||||
"resolved": "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk-win32-x64/-/claude-agent-sdk-win32-x64-0.3.326.tgz",
|
||||
"integrity": "sha512-Yn1gZXYFuHmjHz7SpHx4TqDcRDsC8TfwWcntJdYjFzMWm+caPAp6QRqr/aTvirjqVA1D+D8Rd29xhuytpE3xTQ==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
@@ -40521,7 +40521,7 @@
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@agentclientprotocol/sdk": "^0.17.1",
|
||||
"@anthropic-ai/claude-agent-sdk": "0.3.246",
|
||||
"@anthropic-ai/claude-agent-sdk": "0.3.326",
|
||||
"@anthropic-ai/sdk": "^0.104.2",
|
||||
"@getpaseo/client": "0.16.0",
|
||||
"@getpaseo/highlight": "0.16.0",
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
import { expect, test } from "../support/fixtures";
|
||||
import { gotoAppShell } from "../support/helpers/app";
|
||||
import {
|
||||
expectFooterActionsInline,
|
||||
seedDockedSidebarWidth,
|
||||
} from "../support/helpers/sidebar-footer-overflow";
|
||||
|
||||
// Chromium's pointer bitmasks expose both inputs while the mouse is primary.
|
||||
test.use({
|
||||
viewport: { width: 1280, height: 800 },
|
||||
launchOptions: {
|
||||
args: [
|
||||
"--blink-settings=primaryPointerType=4,availablePointerTypes=6,primaryHoverType=2,availableHoverTypes=3",
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
test("a touchscreen laptop keeps sidebar actions visible with a fine primary pointer", async ({
|
||||
page,
|
||||
}) => {
|
||||
await seedDockedSidebarWidth(page, 200);
|
||||
await gotoAppShell(page);
|
||||
expect(
|
||||
await page.evaluate(() => ({
|
||||
finePrimary: matchMedia("(pointer: fine)").matches,
|
||||
touchScreen: matchMedia("(any-pointer: coarse)").matches,
|
||||
})),
|
||||
).toEqual({ finePrimary: true, touchScreen: true });
|
||||
await expectFooterActionsInline(page, [
|
||||
"sidebar-add-project",
|
||||
"sidebar-usage-icon",
|
||||
"sidebar-hosts-trigger",
|
||||
"sidebar-help",
|
||||
"sidebar-settings",
|
||||
]);
|
||||
});
|
||||
@@ -60,14 +60,8 @@ export function footerOverflowMenu(page: Page): Locator {
|
||||
return page.getByTestId("sidebar-footer-overflow-menu");
|
||||
}
|
||||
|
||||
/**
|
||||
* The icon line shows exactly `testIDs`, in order, each `controlSize` square and wholly inside the
|
||||
* line's box, so no button is cut off by the sidebar's edge.
|
||||
*/
|
||||
export async function expectFooterLine(
|
||||
page: Page,
|
||||
input: { testIDs: string[]; controlSize: number },
|
||||
): Promise<void> {
|
||||
/** The icon line shows exactly `testIDs`, in order. */
|
||||
export async function expectFooterActionsInline(page: Page, testIDs: string[]): Promise<void> {
|
||||
const line = footerLine(page);
|
||||
await expect(line).toHaveCount(1);
|
||||
await expect
|
||||
@@ -76,7 +70,16 @@ export async function expectFooterLine(
|
||||
.locator(FOOTER_LINE_TEST_IDS.map((testID) => `[data-testid="${testID}"]`).join(","))
|
||||
.evaluateAll((elements) => elements.map((element) => element.getAttribute("data-testid"))),
|
||||
)
|
||||
.toEqual(input.testIDs);
|
||||
.toEqual(testIDs);
|
||||
}
|
||||
|
||||
/** The actions are square and fit inside the line. */
|
||||
export async function expectFooterLine(
|
||||
page: Page,
|
||||
input: { testIDs: string[]; controlSize: number },
|
||||
): Promise<void> {
|
||||
await expectFooterActionsInline(page, input.testIDs);
|
||||
const line = footerLine(page);
|
||||
const { row, buttons } = await line.evaluate((element, testIDs) => {
|
||||
const rect = (node: Element) => {
|
||||
const { x, width, height } = node.getBoundingClientRect();
|
||||
|
||||
@@ -68,24 +68,27 @@ const theme = {
|
||||
} as unknown as Theme;
|
||||
|
||||
describe("control sizing gate", () => {
|
||||
it("is touch-sized in the compact layout or on a touch screen, and pointer-sized otherwise", () => {
|
||||
expect(resolveControlSizing({ compactLayout: true, touchScreen: true })).toBe("touch");
|
||||
expect(resolveControlSizing({ compactLayout: true, touchScreen: false })).toBe("touch");
|
||||
expect(resolveControlSizing({ compactLayout: false, touchScreen: true })).toBe("touch");
|
||||
expect(resolveControlSizing({ compactLayout: false, touchScreen: false })).toBe("pointer");
|
||||
it("is touch-sized in the compact layout or where touch is the primary input, and pointer-sized otherwise", () => {
|
||||
expect(resolveControlSizing({ compactLayout: true, touchPrimaryPointer: true })).toBe("touch");
|
||||
expect(resolveControlSizing({ compactLayout: true, touchPrimaryPointer: false })).toBe("touch");
|
||||
expect(resolveControlSizing({ compactLayout: false, touchPrimaryPointer: true })).toBe("touch");
|
||||
expect(resolveControlSizing({ compactLayout: false, touchPrimaryPointer: false })).toBe(
|
||||
"pointer",
|
||||
);
|
||||
});
|
||||
|
||||
it("gives a touch screen its touch sizes at every width", () => {
|
||||
it("gives a touch primary pointer its touch sizes at every width", () => {
|
||||
const sizes = { touch: 44, pointer: 32 };
|
||||
|
||||
// An iPad: touch-sized in the docked desktop layout too.
|
||||
expect(bySizing(sizes, true)).toEqual({ xs: 44, md: 44 });
|
||||
// A mouse-driven window: touch-sized only once it narrows into the compact layout.
|
||||
// A mouse- or trackpad-driven window, touch screen or not: touch-sized only once it narrows
|
||||
// into the compact layout.
|
||||
expect(bySizing(sizes, false)).toEqual({ xs: 44, md: 32 });
|
||||
});
|
||||
|
||||
it("keeps a device without a touch screen on pointer sizes from md up", () => {
|
||||
// The unit runtime has no touch screen, which is the desktop that must not change.
|
||||
it("keeps a device without a touch primary pointer on pointer sizes from md up", () => {
|
||||
// The unit runtime has no touch primary pointer, which is the desktop that must not change.
|
||||
expect(controlSizingForLayout(false)).toBe("pointer");
|
||||
expect(controlSizingForLayout(true)).toBe("touch");
|
||||
expect(CONTROL_HEIGHTS.md).toEqual({ xs: 44, md: 32 });
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { hasTouchScreen } from "@/hooks/pointer-capabilities";
|
||||
import { hasTouchPrimaryPointer } from "@/hooks/pointer-capabilities";
|
||||
|
||||
// The sizing gate, apart from the control sizes so that low-level modules such as
|
||||
// `constants/layout` can size by it without loading the theme. Import it through
|
||||
@@ -14,28 +14,32 @@ export type ControlSizing = "touch" | "pointer";
|
||||
export interface ControlSizingFacts {
|
||||
/** The layout is below the `md` breakpoint. */
|
||||
compactLayout: boolean;
|
||||
/** The device has a touch screen; see `hasTouchScreen`. */
|
||||
touchScreen: boolean;
|
||||
/** Touch is the device's primary input; see `hasTouchPrimaryPointer`. */
|
||||
touchPrimaryPointer: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* The one sizing gate: touch-sized in the compact layout or on any device with a touch screen,
|
||||
* pointer-sized otherwise. A touch screen keeps touch sizing when a mouse or keyboard is attached.
|
||||
* The one sizing gate: touch-sized in the compact layout or where touch is the primary input,
|
||||
* pointer-sized otherwise. An iPad keeps touch sizing with a trackpad attached; a laptop with a
|
||||
* touch screen that its trackpad drives is pointer-sized.
|
||||
*/
|
||||
export function resolveControlSizing({
|
||||
compactLayout,
|
||||
touchScreen,
|
||||
touchPrimaryPointer,
|
||||
}: ControlSizingFacts): ControlSizing {
|
||||
if (compactLayout || touchScreen) return "touch";
|
||||
if (compactLayout || touchPrimaryPointer) return "touch";
|
||||
return "pointer";
|
||||
}
|
||||
|
||||
// Read once, so attaching a mouse or keyboard later never flips the sizing.
|
||||
const DEVICE_HAS_TOUCH_SCREEN = hasTouchScreen();
|
||||
const DEVICE_HAS_TOUCH_PRIMARY_POINTER = hasTouchPrimaryPointer();
|
||||
|
||||
/** The sizing on this device for a layout, for code that sizes outside a stylesheet. */
|
||||
export function controlSizingForLayout(compactLayout: boolean): ControlSizing {
|
||||
return resolveControlSizing({ compactLayout, touchScreen: DEVICE_HAS_TOUCH_SCREEN });
|
||||
return resolveControlSizing({
|
||||
compactLayout,
|
||||
touchPrimaryPointer: DEVICE_HAS_TOUCH_PRIMARY_POINTER,
|
||||
});
|
||||
}
|
||||
|
||||
/** A Unistyles breakpoint value: one number in the compact layout, another from `md` up. */
|
||||
@@ -51,11 +55,11 @@ export type SizingValue = Record<ControlSizing, number>;
|
||||
*/
|
||||
export function bySizing(
|
||||
sizes: SizingValue,
|
||||
touchScreen: boolean = DEVICE_HAS_TOUCH_SCREEN,
|
||||
touchPrimaryPointer: boolean = DEVICE_HAS_TOUCH_PRIMARY_POINTER,
|
||||
): LayoutValue {
|
||||
return {
|
||||
xs: sizes[resolveControlSizing({ compactLayout: true, touchScreen })],
|
||||
md: sizes[resolveControlSizing({ compactLayout: false, touchScreen })],
|
||||
xs: sizes[resolveControlSizing({ compactLayout: true, touchPrimaryPointer })],
|
||||
md: sizes[resolveControlSizing({ compactLayout: false, touchPrimaryPointer })],
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -23,10 +23,18 @@ class FakeMediaQueryList {
|
||||
}
|
||||
}
|
||||
|
||||
function createFakeDisplay(initial: { finePointer: boolean; touchScreen: boolean }) {
|
||||
function createFakeDisplay(initial: {
|
||||
finePointer: boolean;
|
||||
touchScreen: boolean;
|
||||
touchPrimaryPointer?: boolean;
|
||||
}) {
|
||||
const queries = {
|
||||
finePointer: new FakeMediaQueryList("(hover: hover) and (pointer: fine)", initial.finePointer),
|
||||
touchScreen: new FakeMediaQueryList("(any-pointer: coarse)", initial.touchScreen),
|
||||
touchPrimaryPointer: new FakeMediaQueryList(
|
||||
"(pointer: coarse)",
|
||||
initial.touchPrimaryPointer ?? false,
|
||||
),
|
||||
};
|
||||
const matchMedia = (query: string) => {
|
||||
const match = Object.values(queries).find((list) => list.media === query);
|
||||
@@ -75,3 +83,25 @@ describe("pointer capabilities", () => {
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("hasTouchPrimaryPointer", () => {
|
||||
it("is false on a touch-screen laptop driven by its trackpad", () => {
|
||||
const display = createFakeDisplay({ finePointer: true, touchScreen: true });
|
||||
expect(createPointerCapabilitiesSource(display.matchMedia).hasTouchPrimaryPointer()).toBe(
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
it("is true when the primary pointer is coarse", () => {
|
||||
const display = createFakeDisplay({
|
||||
finePointer: false,
|
||||
touchScreen: true,
|
||||
touchPrimaryPointer: true,
|
||||
});
|
||||
expect(createPointerCapabilitiesSource(display.matchMedia).hasTouchPrimaryPointer()).toBe(true);
|
||||
});
|
||||
|
||||
it("is false without media queries", () => {
|
||||
expect(createPointerCapabilitiesSource(null).hasTouchPrimaryPointer()).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -8,6 +8,7 @@ import { isWeb } from "@/constants/platform";
|
||||
// (detachable keyboards, tablet mode, devtools touch emulation).
|
||||
const FINE_POINTER_QUERY = "(hover: hover) and (pointer: fine)";
|
||||
const TOUCH_SCREEN_QUERY = "(any-pointer: coarse)";
|
||||
const TOUCH_PRIMARY_POINTER_QUERY = "(pointer: coarse)";
|
||||
|
||||
export interface PointerCapabilities {
|
||||
/** A mouse-like pointer drives the UI. */
|
||||
@@ -21,6 +22,7 @@ type MatchMedia = (query: string) => MediaQueryList;
|
||||
export interface PointerCapabilitiesSource {
|
||||
getSnapshot: () => PointerCapabilities;
|
||||
subscribe: (onChange: () => void) => () => void;
|
||||
hasTouchPrimaryPointer: () => boolean;
|
||||
}
|
||||
|
||||
export function createPointerCapabilitiesSource(
|
||||
@@ -28,9 +30,11 @@ export function createPointerCapabilitiesSource(
|
||||
): PointerCapabilitiesSource {
|
||||
const finePointerQuery = matchMedia?.(FINE_POINTER_QUERY) ?? null;
|
||||
const touchScreenQuery = matchMedia?.(TOUCH_SCREEN_QUERY) ?? null;
|
||||
const touchPrimaryPointerQuery = matchMedia?.(TOUCH_PRIMARY_POINTER_QUERY) ?? null;
|
||||
let snapshot: PointerCapabilities = { finePointer: false, touchScreen: false };
|
||||
|
||||
return {
|
||||
hasTouchPrimaryPointer: () => touchPrimaryPointerQuery?.matches ?? false,
|
||||
getSnapshot() {
|
||||
const finePointer = finePointerQuery?.matches ?? false;
|
||||
const touchScreen = touchScreenQuery?.matches ?? false;
|
||||
@@ -61,6 +65,7 @@ const NATIVE_POINTER_CAPABILITIES: PointerCapabilities = { finePointer: false, t
|
||||
const nativeSource: PointerCapabilitiesSource = {
|
||||
getSnapshot: () => NATIVE_POINTER_CAPABILITIES,
|
||||
subscribe: () => () => {},
|
||||
hasTouchPrimaryPointer: () => true,
|
||||
};
|
||||
|
||||
const source = isWeb ? createPointerCapabilitiesSource(browserMatchMedia()) : nativeSource;
|
||||
@@ -79,10 +84,11 @@ export function hasFinePointer(): boolean {
|
||||
return source.getSnapshot().finePointer;
|
||||
}
|
||||
|
||||
/** Touch sizing remains enabled on hybrid browsers that report touch points. */
|
||||
export function hasTouchScreen(): boolean {
|
||||
return (
|
||||
source.getSnapshot().touchScreen ||
|
||||
(isWeb && typeof window !== "undefined" && window.navigator.maxTouchPoints > 0)
|
||||
);
|
||||
/**
|
||||
* True when touch is the primary input, read at call time. iPadOS keeps touch primary with a
|
||||
* trackpad attached; a laptop with a touch screen that its trackpad drives reports a fine primary
|
||||
* pointer.
|
||||
*/
|
||||
export function hasTouchPrimaryPointer(): boolean {
|
||||
return source.hasTouchPrimaryPointer();
|
||||
}
|
||||
|
||||
@@ -107,7 +107,7 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@agentclientprotocol/sdk": "^0.17.1",
|
||||
"@anthropic-ai/claude-agent-sdk": "0.3.246",
|
||||
"@anthropic-ai/claude-agent-sdk": "0.3.326",
|
||||
"@anthropic-ai/sdk": "^0.104.2",
|
||||
"@getpaseo/client": "0.16.0",
|
||||
"@getpaseo/highlight": "0.16.0",
|
||||
|
||||
@@ -20,6 +20,10 @@ import {
|
||||
type ManagedAgent,
|
||||
} from "./agent-manager.js";
|
||||
import { AgentStorage, parseStoredAgentRecord } from "./agent-storage.js";
|
||||
import { AgentTurnStartCanceledError } from "./agent-sdk-types.js";
|
||||
import { ForegroundPromptStart } from "./agent-run-state.js";
|
||||
import { CodexAppServerAgentSession } from "./providers/codex-app-server-agent.js";
|
||||
import { createFakeCodexAppServer } from "./providers/codex/test-utils/fake-app-server.js";
|
||||
import { InMemoryAgentTimelineStore } from "./agent-timeline-store.js";
|
||||
import { limitAgentTimelineItemContent } from "./agent-timeline-content.js";
|
||||
import { buildStoredAgentPayload, toAgentPayload } from "./agent-projections.js";
|
||||
@@ -1210,7 +1214,7 @@ test("starts its own turn when the previous turn fails to start under a steer se
|
||||
);
|
||||
|
||||
startHeld.resolve();
|
||||
await expect(second).resolves.toEqual({ disposition: "turn_started" });
|
||||
await expect(second).resolves.toMatchObject({ disposition: "turn_started" });
|
||||
await vi.waitFor(() => expect(session.startPrompts).toEqual(["FIRST", "SECOND"]));
|
||||
expect(session.interruptCount).toBe(0);
|
||||
} finally {
|
||||
@@ -9749,6 +9753,464 @@ test("streamAgent clears pending run when startTurn fails before a turn id exist
|
||||
);
|
||||
});
|
||||
|
||||
test("canceling a pending Codex start settles as canceled without accepting its prompt", async () => {
|
||||
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-codex-cold-cancel-"));
|
||||
const threadLoaded = deferred<{ data: string[] }>();
|
||||
const appServer = createFakeCodexAppServer({ "thread/loaded/list": () => threadLoaded.promise });
|
||||
class ColdStartClient extends TestAgentClient {
|
||||
override async createSession(config: AgentSessionConfig): Promise<AgentSession> {
|
||||
return new CodexAppServerAgentSession(config, null, logger, async () => appServer.child);
|
||||
}
|
||||
}
|
||||
const manager = new AgentManager({
|
||||
clients: { codex: new ColdStartClient() },
|
||||
registry: new AgentStorage(join(workdir, "agents"), logger),
|
||||
logger,
|
||||
});
|
||||
const events: AgentStreamEvent[] = [];
|
||||
manager.subscribe((event) => {
|
||||
if (event.type === "agent_stream") events.push(event.event);
|
||||
});
|
||||
try {
|
||||
const agent = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, {
|
||||
workspaceId: undefined,
|
||||
});
|
||||
// Drain the stream: a fresh Codex agent has no session handle for runAgent before its first turn.
|
||||
const senderStart = new ForegroundPromptStart(agent.id);
|
||||
const firstRun = drainAsyncGenerator(
|
||||
manager.streamAgent(
|
||||
agent.id,
|
||||
"Canceled prompt",
|
||||
{ clientMessageId: "canceled-prompt" },
|
||||
senderStart,
|
||||
),
|
||||
);
|
||||
void firstRun.catch(() => undefined);
|
||||
await appServer.waitForRequest("thread/loaded/list");
|
||||
const senderRejection = expect(senderStart.started).rejects.toThrow(
|
||||
"its prompt was not delivered",
|
||||
);
|
||||
const cancel = manager.cancelAgentRun(agent.id);
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
threadLoaded.resolve({ data: ["thread-1"] });
|
||||
await expect(cancel).resolves.toEqual({ status: "settled" });
|
||||
await expect(firstRun).resolves.toBeUndefined();
|
||||
await senderRejection;
|
||||
expect(manager.getAgent(agent.id)).toMatchObject({ lifecycle: "idle", lastError: undefined });
|
||||
expect(manager.hasInFlightRun(agent.id)).toBe(false);
|
||||
expect(events.map((event) => event.type)).toEqual(["timeline", "turn_canceled"]);
|
||||
// The canceled attempt stays in history like a rejected one, without being delivered.
|
||||
expect(manager.getTimeline(agent.id)).toEqual([
|
||||
{
|
||||
type: "user_message",
|
||||
text: "Canceled prompt",
|
||||
clientMessageId: "canceled-prompt",
|
||||
messageId: "canceled-prompt",
|
||||
},
|
||||
]);
|
||||
expect(appServer.requests().some((request) => request.method === "turn/start")).toBe(false);
|
||||
|
||||
const nextRun = manager.runAgent(agent.id, "Next prompt", { clientMessageId: "next-prompt" });
|
||||
await appServer.waitForRequest("turn/start");
|
||||
appServer.startsTurn({ threadId: "thread-1", turnId: "next-turn" });
|
||||
appServer.completeTurn();
|
||||
await expect(nextRun).resolves.toMatchObject({ canceled: false });
|
||||
appServer.assertNoErrors();
|
||||
} finally {
|
||||
threadLoaded.resolve({ data: ["thread-1"] });
|
||||
manager.prepareForShutdown();
|
||||
await Promise.all(manager.listAgents().map((agent) => manager.closeAgent(agent.id)));
|
||||
await manager.flushForShutdown();
|
||||
rmSync(workdir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("stopping a Codex replacement of a stalled start clears replacement activity", async () => {
|
||||
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-codex-replacement-cancel-"));
|
||||
const firstLoaded = deferred<{ data: string[] }>();
|
||||
const firstInterruptRequested = deferred<void>();
|
||||
const replacementLoaded = deferred<{ data: string[] }>();
|
||||
const replacementEntered = deferred<void>();
|
||||
let loadCount = 0;
|
||||
const appServer = createFakeCodexAppServer({
|
||||
"thread/loaded/list": () => {
|
||||
loadCount += 1;
|
||||
if (loadCount === 1) return firstLoaded.promise;
|
||||
replacementEntered.resolve();
|
||||
return replacementLoaded.promise;
|
||||
},
|
||||
});
|
||||
class ColdStartSession extends CodexAppServerAgentSession {
|
||||
override async interrupt(): Promise<void> {
|
||||
const interruption = super.interrupt();
|
||||
firstInterruptRequested.resolve();
|
||||
await interruption;
|
||||
}
|
||||
}
|
||||
class ColdStartClient extends TestAgentClient {
|
||||
override async createSession(config: AgentSessionConfig): Promise<AgentSession> {
|
||||
return new ColdStartSession(config, null, logger, async () => appServer.child);
|
||||
}
|
||||
}
|
||||
const manager = new AgentManager({
|
||||
clients: { codex: new ColdStartClient() },
|
||||
registry: new AgentStorage(join(workdir, "agents"), logger),
|
||||
logger,
|
||||
rescueTimeouts: { interruptSessionMs: 10 },
|
||||
});
|
||||
try {
|
||||
const agent = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, {
|
||||
workspaceId: undefined,
|
||||
});
|
||||
const firstRun = drainAsyncGenerator(manager.streamAgent(agent.id, "Original prompt"));
|
||||
await appServer.waitForRequest("thread/loaded/list");
|
||||
const replacement = manager.replaceAgentRun(agent.id, "Replacement prompt");
|
||||
await firstInterruptRequested.promise;
|
||||
firstLoaded.resolve({ data: ["thread-1"] });
|
||||
const replacementStream = await replacement;
|
||||
await expect(firstRun).resolves.toBeUndefined();
|
||||
expect(manager.getAgent(agent.id)?.lifecycle).toBe("running");
|
||||
const replacementEvent = replacementStream.next();
|
||||
await replacementEntered.promise;
|
||||
const cancel = manager.cancelAgentRun(agent.id);
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
replacementLoaded.resolve({ data: ["thread-1"] });
|
||||
await expect(cancel).resolves.toEqual({ status: "settled" });
|
||||
await expect(replacementEvent).resolves.toMatchObject({
|
||||
value: { type: "turn_canceled" },
|
||||
});
|
||||
await expect(replacementStream.next()).resolves.toMatchObject({ done: true });
|
||||
expect(manager.hasInFlightRun(agent.id)).toBe(false);
|
||||
expect(manager.getAgent(agent.id)?.lifecycle).toBe("idle");
|
||||
expect(appServer.requests().some((request) => request.method === "turn/start")).toBe(false);
|
||||
appServer.assertNoErrors();
|
||||
} finally {
|
||||
firstLoaded.resolve({ data: ["thread-1"] });
|
||||
replacementLoaded.resolve({ data: ["thread-1"] });
|
||||
manager.prepareForShutdown();
|
||||
await Promise.all(manager.listAgents().map((agent) => manager.closeAgent(agent.id)));
|
||||
await manager.flushForShutdown();
|
||||
rmSync(workdir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("a stalled Codex start canceled by its replacement rejects its sender's start wait", async () => {
|
||||
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-codex-replaced-start-wait-"));
|
||||
const firstLoaded = deferred<{ data: string[] }>();
|
||||
const firstInterruptRequested = deferred<void>();
|
||||
let loadCount = 0;
|
||||
const appServer = createFakeCodexAppServer({
|
||||
"thread/loaded/list": () => {
|
||||
loadCount += 1;
|
||||
return loadCount === 1 ? firstLoaded.promise : { data: ["thread-1"] };
|
||||
},
|
||||
});
|
||||
class ColdStartSession extends CodexAppServerAgentSession {
|
||||
override async interrupt(): Promise<void> {
|
||||
const interruption = super.interrupt();
|
||||
firstInterruptRequested.resolve();
|
||||
await interruption;
|
||||
}
|
||||
}
|
||||
class ColdStartClient extends TestAgentClient {
|
||||
override async createSession(config: AgentSessionConfig): Promise<AgentSession> {
|
||||
return new ColdStartSession(config, null, logger, async () => appServer.child);
|
||||
}
|
||||
}
|
||||
const manager = new AgentManager({
|
||||
clients: { codex: new ColdStartClient() },
|
||||
registry: new AgentStorage(join(workdir, "agents"), logger),
|
||||
logger,
|
||||
rescueTimeouts: { interruptSessionMs: 10 },
|
||||
});
|
||||
try {
|
||||
const agent = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, {
|
||||
workspaceId: undefined,
|
||||
});
|
||||
const firstStart = new ForegroundPromptStart(agent.id);
|
||||
const secondStart = new ForegroundPromptStart(agent.id);
|
||||
const firstRun = drainAsyncGenerator(
|
||||
manager.streamAgent(agent.id, "First prompt", undefined, firstStart),
|
||||
);
|
||||
await appServer.waitForRequest("thread/loaded/list");
|
||||
const firstWait = firstStart.started;
|
||||
const replacement = manager.replaceAgentRun(agent.id, "Second prompt", undefined, secondStart);
|
||||
await firstInterruptRequested.promise;
|
||||
firstLoaded.resolve({ data: ["thread-1"] });
|
||||
const replacementStream = await replacement;
|
||||
await expect(firstRun).resolves.toBeUndefined();
|
||||
|
||||
const secondWait = secondStart.started;
|
||||
const replacementDrained = drainAsyncGenerator(replacementStream);
|
||||
await appServer.waitForRequest("turn/start");
|
||||
appServer.startsTurn({ threadId: "thread-1", turnId: "second-turn" });
|
||||
await expect(secondWait).resolves.toBeUndefined();
|
||||
await expect(firstWait).rejects.toThrow("its prompt was not delivered");
|
||||
appServer.completeTurn();
|
||||
await replacementDrained;
|
||||
expect(appServer.requests().filter((request) => request.method === "turn/start")).toEqual([
|
||||
expect.objectContaining({
|
||||
params: expect.objectContaining({
|
||||
input: [expect.objectContaining({ text: "Second prompt" })],
|
||||
}),
|
||||
}),
|
||||
]);
|
||||
appServer.assertNoErrors();
|
||||
} finally {
|
||||
firstLoaded.resolve({ data: ["thread-1"] });
|
||||
manager.prepareForShutdown();
|
||||
await Promise.all(manager.listAgents().map((agent) => manager.closeAgent(agent.id)));
|
||||
await manager.flushForShutdown();
|
||||
rmSync(workdir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("a sender's start wait follows its prompt across a stale-session retry", async () => {
|
||||
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-stale-start-wait-"));
|
||||
const releaseStart = deferred<void>();
|
||||
class StaleStartSession extends TestAgentSession {
|
||||
override async startTurn(): Promise<{ turnId: string }> {
|
||||
await releaseStart.promise;
|
||||
throw new StaleProviderSessionError("stale-bridge");
|
||||
}
|
||||
}
|
||||
class StaleStartClient extends ResumeTrackingTestAgentClient {
|
||||
override async createSession(config: AgentSessionConfig): Promise<AgentSession> {
|
||||
return new StaleStartSession(config);
|
||||
}
|
||||
}
|
||||
const client = new StaleStartClient();
|
||||
const storage = new AgentStorage(join(workdir, "agents"), logger);
|
||||
const manager = new AgentManager({ clients: { codex: client }, registry: storage, logger });
|
||||
const startedTurns: AgentStreamEvent[] = [];
|
||||
manager.subscribe((event) => {
|
||||
if (event.type === "agent_stream" && event.event.type === "turn_started") {
|
||||
startedTurns.push(event.event);
|
||||
}
|
||||
});
|
||||
try {
|
||||
const agent = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, {
|
||||
workspaceId: undefined,
|
||||
});
|
||||
const senderWait = dispatchStarted(
|
||||
await startAgentRun(manager, agent.id, "Retry this prompt", logger, {
|
||||
runOptions: { clientMessageId: "stale-start-wait" },
|
||||
}),
|
||||
);
|
||||
releaseStart.resolve();
|
||||
await client.waitForRetryStart();
|
||||
await manager.waitForAgentEvent(agent.id);
|
||||
expect(client.resumeOverrides).toHaveLength(1);
|
||||
expect(startedTurns).toHaveLength(1);
|
||||
expect(manager.getTimeline(agent.id).filter((item) => item.type === "user_message")).toEqual([
|
||||
expect.objectContaining({ text: "Retry this prompt", clientMessageId: "stale-start-wait" }),
|
||||
]);
|
||||
await expect(senderWait).resolves.toBeUndefined();
|
||||
} finally {
|
||||
releaseStart.resolve();
|
||||
manager.prepareForShutdown();
|
||||
await Promise.all(manager.listAgents().map((agent) => manager.closeAgent(agent.id)));
|
||||
await manager.flushForShutdown();
|
||||
rmSync(workdir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("a sender's start wait follows its prompt when the session is stale before the wait begins", async () => {
|
||||
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-immediate-stale-start-"));
|
||||
class StaleStartSession extends TestAgentSession {
|
||||
override async startTurn(): Promise<{ turnId: string }> {
|
||||
throw new StaleProviderSessionError("stale-bridge");
|
||||
}
|
||||
}
|
||||
class StaleStartClient extends ResumeTrackingTestAgentClient {
|
||||
override async createSession(config: AgentSessionConfig): Promise<AgentSession> {
|
||||
return new StaleStartSession(config);
|
||||
}
|
||||
}
|
||||
const client = new StaleStartClient();
|
||||
const storage = new AgentStorage(join(workdir, "agents"), logger);
|
||||
const manager = new AgentManager({ clients: { codex: client }, registry: storage, logger });
|
||||
try {
|
||||
const agent = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, {
|
||||
workspaceId: undefined,
|
||||
});
|
||||
const dispatch = await startAgentRun(manager, agent.id, "Retry this prompt", logger, {
|
||||
runOptions: { clientMessageId: "immediate-stale-start" },
|
||||
});
|
||||
// The stale start has failed and been cleared before the sender begins waiting.
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
expect(manager.hasInFlightRun(agent.id)).toBe(false);
|
||||
await expect(dispatchStarted(dispatch)).resolves.toBeUndefined();
|
||||
await client.waitForRetryStart();
|
||||
expect(manager.getTimeline(agent.id).filter((item) => item.type === "user_message")).toEqual([
|
||||
expect.objectContaining({
|
||||
text: "Retry this prompt",
|
||||
clientMessageId: "immediate-stale-start",
|
||||
}),
|
||||
]);
|
||||
} finally {
|
||||
manager.prepareForShutdown();
|
||||
await Promise.all(manager.listAgents().map((agent) => manager.closeAgent(agent.id)));
|
||||
await manager.flushForShutdown();
|
||||
rmSync(workdir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test.each(["reload", "retry", "stale retry"])(
|
||||
"a sender's start wait rejects when its stale-session %s fails",
|
||||
async (failure) => {
|
||||
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-stale-start-failure-"));
|
||||
const releaseStart = deferred<void>();
|
||||
class StaleStartSession extends TestAgentSession {
|
||||
override async startTurn(): Promise<{ turnId: string }> {
|
||||
await releaseStart.promise;
|
||||
throw new StaleProviderSessionError("stale-bridge");
|
||||
}
|
||||
}
|
||||
class FailedRetrySession extends TestAgentSession {
|
||||
override async startTurn(): Promise<{ turnId: string }> {
|
||||
if (failure === "stale retry") throw new StaleProviderSessionError("retry-bridge");
|
||||
throw new Error("retry failed");
|
||||
}
|
||||
}
|
||||
class FailedRetryClient extends TestAgentClient {
|
||||
override async createSession(config: AgentSessionConfig): Promise<AgentSession> {
|
||||
return new StaleStartSession(config);
|
||||
}
|
||||
override async resumeSession(): Promise<AgentSession> {
|
||||
if (failure === "reload") throw new Error("reload failed");
|
||||
return new FailedRetrySession({ provider: "codex", cwd: workdir });
|
||||
}
|
||||
}
|
||||
const manager = new AgentManager({ clients: { codex: new FailedRetryClient() }, logger });
|
||||
try {
|
||||
const agent = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, {
|
||||
workspaceId: undefined,
|
||||
});
|
||||
const senderWait = dispatchStarted(
|
||||
await startAgentRun(manager, agent.id, "Retry this prompt", logger),
|
||||
);
|
||||
const rejection = expect(senderWait).rejects.toThrow(
|
||||
failure === "retry" ? "retry failed" : "is stale after its plugin reloaded",
|
||||
);
|
||||
releaseStart.resolve();
|
||||
await rejection;
|
||||
} finally {
|
||||
releaseStart.resolve();
|
||||
manager.prepareForShutdown();
|
||||
await Promise.all(manager.listAgents().map((agent) => manager.closeAgent(agent.id)));
|
||||
await manager.flushForShutdown();
|
||||
rmSync(workdir, { recursive: true, force: true });
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
test("a sender's start wait rejects when Stop cancels its pending stale-session retry", async () => {
|
||||
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-stale-retry-stop-"));
|
||||
const releaseStart = deferred<void>();
|
||||
const retryEntered = deferred<void>();
|
||||
const retryCanceled = deferred<void>();
|
||||
class StaleStartSession extends TestAgentSession {
|
||||
override async startTurn(): Promise<{ turnId: string }> {
|
||||
await releaseStart.promise;
|
||||
throw new StaleProviderSessionError("stale-bridge");
|
||||
}
|
||||
}
|
||||
class CanceledRetrySession extends TestAgentSession {
|
||||
override async startTurn(): Promise<{ turnId: string }> {
|
||||
retryEntered.resolve();
|
||||
await retryCanceled.promise;
|
||||
throw new AgentTurnStartCanceledError();
|
||||
}
|
||||
override async interrupt(): Promise<void> {
|
||||
retryCanceled.resolve();
|
||||
}
|
||||
}
|
||||
class RetryClient extends TestAgentClient {
|
||||
override async createSession(config: AgentSessionConfig): Promise<AgentSession> {
|
||||
return new StaleStartSession(config);
|
||||
}
|
||||
override async resumeSession(): Promise<AgentSession> {
|
||||
return new CanceledRetrySession({ provider: "codex", cwd: workdir });
|
||||
}
|
||||
}
|
||||
const manager = new AgentManager({ clients: { codex: new RetryClient() }, logger });
|
||||
try {
|
||||
const agent = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, {
|
||||
workspaceId: undefined,
|
||||
});
|
||||
const senderWait = dispatchStarted(
|
||||
await startAgentRun(manager, agent.id, "Retry this prompt", logger),
|
||||
);
|
||||
const rejection = expect(senderWait).rejects.toThrow("its prompt was not delivered");
|
||||
releaseStart.resolve();
|
||||
await retryEntered.promise;
|
||||
await expect(manager.cancelAgentRun(agent.id)).resolves.toEqual({ status: "settled" });
|
||||
await rejection;
|
||||
expect(manager.getAgent(agent.id)?.lifecycle).toBe("idle");
|
||||
expect(manager.getTimeline(agent.id)).toEqual([]);
|
||||
} finally {
|
||||
releaseStart.resolve();
|
||||
retryCanceled.resolve();
|
||||
manager.prepareForShutdown();
|
||||
await Promise.all(manager.listAgents().map((agent) => manager.closeAgent(agent.id)));
|
||||
await manager.flushForShutdown();
|
||||
rmSync(workdir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("a sender's start wait never adopts an unlinked run after a stale start", async () => {
|
||||
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-unlinked-start-"));
|
||||
const releaseStart = deferred<void>();
|
||||
const staleError = new StaleProviderSessionError("stale-bridge");
|
||||
class StaleStartSession extends TestAgentSession {
|
||||
override async startTurn(): Promise<{ turnId: string }> {
|
||||
await releaseStart.promise;
|
||||
throw staleError;
|
||||
}
|
||||
}
|
||||
class RetryClient extends TestAgentClient {
|
||||
override async createSession(config: AgentSessionConfig): Promise<AgentSession> {
|
||||
return new StaleStartSession(config);
|
||||
}
|
||||
}
|
||||
const manager = new AgentManager({ clients: { codex: new RetryClient() }, logger });
|
||||
try {
|
||||
const agent = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, {
|
||||
workspaceId: undefined,
|
||||
});
|
||||
const senderStart = new ForegroundPromptStart(agent.id);
|
||||
const firstRun = drainAsyncGenerator(
|
||||
manager.streamAgent(agent.id, "First prompt", undefined, senderStart),
|
||||
);
|
||||
const firstFailure = expect(firstRun).rejects.toBe(staleError);
|
||||
const rejection = expect(senderStart.started).rejects.toThrow(staleError.message);
|
||||
releaseStart.resolve();
|
||||
await firstFailure;
|
||||
try {
|
||||
await manager.reloadAgentSession(agent.id);
|
||||
const otherStart = new ForegroundPromptStart(agent.id);
|
||||
const otherRun = drainAsyncGenerator(
|
||||
manager.streamAgent(agent.id, "Another sender", undefined, otherStart),
|
||||
);
|
||||
await expect(otherStart.started).resolves.toBeUndefined();
|
||||
await otherRun;
|
||||
} finally {
|
||||
senderStart.end();
|
||||
}
|
||||
await rejection;
|
||||
expect(manager.getTimeline(agent.id).filter((item) => item.type === "user_message")).toEqual(
|
||||
[],
|
||||
);
|
||||
} finally {
|
||||
releaseStart.resolve();
|
||||
manager.prepareForShutdown();
|
||||
await Promise.all(manager.listAgents().map((agent) => manager.closeAgent(agent.id)));
|
||||
await manager.flushForShutdown();
|
||||
rmSync(workdir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("acknowledged cancellation settles a pending run before it has a turn id", async () => {
|
||||
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-cancel-pending-start-"));
|
||||
const startEntered = deferred<void>();
|
||||
@@ -15071,3 +15533,11 @@ test("plugin instructions are recomputed for each launch without changing saved
|
||||
expect(client.resumeOverrides.at(-1)?.daemonAppendSystemPrompt).toBe("Daemon");
|
||||
expect((await storage.get(snapshot.id))?.config?.systemPrompt).toBe("Saved");
|
||||
});
|
||||
|
||||
function dispatchStarted(dispatch: Awaited<ReturnType<typeof startAgentRun>>): Promise<void> {
|
||||
if (dispatch.disposition !== "turn_started") {
|
||||
throw new Error(`Expected a started turn, got ${dispatch.disposition}`);
|
||||
}
|
||||
void dispatch.started.catch(() => undefined);
|
||||
return dispatch.started;
|
||||
}
|
||||
|
||||
@@ -29,6 +29,7 @@ import { z } from "zod";
|
||||
import type { TerminalManager } from "../../terminal/terminal-manager.js";
|
||||
|
||||
import {
|
||||
AgentTurnStartCanceledError,
|
||||
getAgentStreamEventTurnId,
|
||||
type AgentCapabilityFlags,
|
||||
type AgentClient,
|
||||
@@ -92,6 +93,7 @@ import {
|
||||
import { limitAgentTimelineItemContent } from "./agent-timeline-content.js";
|
||||
import {
|
||||
AgentRunState,
|
||||
type ForegroundPromptStart,
|
||||
type ForegroundTurnWaiter,
|
||||
type PendingForegroundRun,
|
||||
} from "./agent-run-state.js";
|
||||
@@ -3143,7 +3145,7 @@ export class AgentManager {
|
||||
pendingRun: PendingForegroundRun;
|
||||
prompt: AgentPromptInput;
|
||||
options?: AgentRunOptions;
|
||||
}): Promise<string> {
|
||||
}): Promise<string | null> {
|
||||
const { agent, agentId, pendingRun, prompt, options } = params;
|
||||
try {
|
||||
const result = await agent.session.startTurn(prompt, options);
|
||||
@@ -3152,11 +3154,32 @@ export class AgentManager {
|
||||
}
|
||||
return result.turnId;
|
||||
} catch (error) {
|
||||
if (error instanceof AgentTurnStartCanceledError) {
|
||||
if (!pendingRun.settled) {
|
||||
if (options?.clientMessageId) {
|
||||
this.recordSubmittedPrompt(agent, prompt, options.clientMessageId, "rejected", {
|
||||
messageId: options.clientMessageId,
|
||||
});
|
||||
}
|
||||
await this.handleStreamEvent(agent, {
|
||||
type: "turn_canceled",
|
||||
provider: agent.provider,
|
||||
reason: "interrupted",
|
||||
});
|
||||
this.finalizeForegroundTurn(agent);
|
||||
this.runs.settleForegroundRun(agentId, pendingRun.token);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
if (pendingRun.settled) {
|
||||
throw error;
|
||||
}
|
||||
if (isStaleProviderSessionError(error)) {
|
||||
this.runs.settleForegroundStart(pendingRun, { status: "failed", error: error.message });
|
||||
this.runs.settleForegroundStart(pendingRun, {
|
||||
status: "failed",
|
||||
error: error.message,
|
||||
stale: true,
|
||||
});
|
||||
agent.pendingReplacement = false;
|
||||
if (!agent.activeForegroundTurnId) agent.lifecycle = "idle";
|
||||
this.runs.settleForegroundRun(agentId, pendingRun.token);
|
||||
@@ -3212,15 +3235,17 @@ export class AgentManager {
|
||||
agentId: string,
|
||||
prompt: AgentPromptInput,
|
||||
options?: AgentRunOptions,
|
||||
promptStart?: ForegroundPromptStart,
|
||||
): AsyncGenerator<AgentStreamEvent> {
|
||||
await this.ensureInteractiveSession(agentId);
|
||||
yield* this.streamAgent(agentId, prompt, options);
|
||||
yield* this.streamAgent(agentId, prompt, options, promptStart);
|
||||
}
|
||||
|
||||
private async *streamAfterRuntimeCollection(
|
||||
agentId: string,
|
||||
prompt: AgentPromptInput,
|
||||
options?: AgentRunOptions,
|
||||
promptStart?: ForegroundPromptStart,
|
||||
): AsyncGenerator<AgentStreamEvent> {
|
||||
await this.waitForAgentClose(agentId);
|
||||
await ensureAgentLoaded(agentId, {
|
||||
@@ -3228,19 +3253,20 @@ export class AgentManager {
|
||||
agentStorage: this.requireRegistry(),
|
||||
logger: this.logger,
|
||||
});
|
||||
yield* this.streamAgent(agentId, prompt, options);
|
||||
yield* this.streamAgent(agentId, prompt, options, promptStart);
|
||||
}
|
||||
|
||||
streamAgent(
|
||||
agentId: string,
|
||||
prompt: AgentPromptInput,
|
||||
options?: AgentRunOptions,
|
||||
promptStart?: ForegroundPromptStart,
|
||||
): AsyncGenerator<AgentStreamEvent> {
|
||||
if (this.collectingRuntimes.has(agentId) || (!this.agents.has(agentId) && this.registry))
|
||||
return this.streamAfterRuntimeCollection(agentId, prompt, options);
|
||||
return this.streamAfterRuntimeCollection(agentId, prompt, options, promptStart);
|
||||
const existingAgent = this.requireSessionAgent(agentId);
|
||||
if (this.historySessions.has(existingAgent.session))
|
||||
return this.streamAfterHistoryLoad(agentId, prompt, options);
|
||||
return this.streamAfterHistoryLoad(agentId, prompt, options, promptStart);
|
||||
this.logger.trace(
|
||||
{
|
||||
agentId,
|
||||
@@ -3275,9 +3301,10 @@ export class AgentManager {
|
||||
agent.lastError = undefined;
|
||||
|
||||
const pendingRun = this.runs.createPendingRun(agentId);
|
||||
promptStart?.bind(pendingRun);
|
||||
|
||||
const streamForwarder = async function* streamForwarder(this: AgentManager) {
|
||||
let turnId: string;
|
||||
let turnId: string | null;
|
||||
let turnStream: ReturnType<AgentRunState["createTurnStream"]> | null = null;
|
||||
turnId = await this.startPendingForegroundTurn({
|
||||
agent,
|
||||
@@ -3286,6 +3313,15 @@ export class AgentManager {
|
||||
prompt,
|
||||
options,
|
||||
});
|
||||
if (turnId === null) {
|
||||
const canceledEvent: AgentStreamEvent = {
|
||||
type: "turn_canceled",
|
||||
provider: agent.provider,
|
||||
reason: "interrupted",
|
||||
};
|
||||
yield canceledEvent;
|
||||
return;
|
||||
}
|
||||
|
||||
if (isReplacement) {
|
||||
agent.pendingReplacement = false;
|
||||
@@ -3440,9 +3476,10 @@ export class AgentManager {
|
||||
agentId: string,
|
||||
prompt: AgentPromptInput,
|
||||
options?: AgentRunOptions,
|
||||
promptStart?: ForegroundPromptStart,
|
||||
): Promise<AsyncGenerator<AgentStreamEvent>> {
|
||||
this.requireSessionAgent(agentId);
|
||||
return this.replaceRunInForegroundLane(agentId, prompt, options);
|
||||
return this.replaceRunInForegroundLane(agentId, prompt, options, promptStart);
|
||||
}
|
||||
|
||||
async steerAgentRun(
|
||||
@@ -3483,6 +3520,7 @@ export class AgentManager {
|
||||
agentId: string,
|
||||
prompt: AgentPromptInput,
|
||||
options?: AgentSteerOptions,
|
||||
promptStart?: ForegroundPromptStart,
|
||||
): Promise<ActiveTurnSteerDispatchResult> {
|
||||
// A turn that is still starting has no id to steer yet. Replacing it would drop its
|
||||
// prompt, so wait until it is accepted (or fails) and steer the turn it became.
|
||||
@@ -3530,6 +3568,7 @@ export class AgentManager {
|
||||
expectedTurnId,
|
||||
prompt,
|
||||
stripSteerOptions(options),
|
||||
promptStart,
|
||||
),
|
||||
};
|
||||
}
|
||||
@@ -3595,9 +3634,10 @@ export class AgentManager {
|
||||
expectedTurnId: string,
|
||||
prompt: AgentPromptInput,
|
||||
options?: AgentRunOptions,
|
||||
promptStart?: ForegroundPromptStart,
|
||||
): Promise<AsyncGenerator<AgentStreamEvent>> {
|
||||
this.assertSteerAdmissionOwnsTurn(agent, expectedTurnId);
|
||||
return this.replaceRunInForegroundLane(agent.id, prompt, options, (live) =>
|
||||
return this.replaceRunInForegroundLane(agent.id, prompt, options, promptStart, (live) =>
|
||||
this.assertSteerAdmissionOwnsTurn(live, expectedTurnId),
|
||||
);
|
||||
}
|
||||
@@ -3610,12 +3650,13 @@ export class AgentManager {
|
||||
agentId: string,
|
||||
prompt: AgentPromptInput,
|
||||
options: AgentRunOptions | undefined,
|
||||
promptStart?: ForegroundPromptStart,
|
||||
assertAdmission?: (agent: ActiveManagedAgent) => void,
|
||||
): Promise<AsyncGenerator<AgentStreamEvent>> {
|
||||
// Replacements queue in arrival order; each one holds the foreground lane only while
|
||||
// it cancels and reserves, so Stop is never stuck behind a replacement that is waiting.
|
||||
return this.runQueuedMutation(this.replacementMutationTails, agentId, () =>
|
||||
this.replaceRunWhenAdmitted(agentId, prompt, options, assertAdmission),
|
||||
this.replaceRunWhenAdmitted(agentId, prompt, options, promptStart, assertAdmission),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -3623,6 +3664,7 @@ export class AgentManager {
|
||||
agentId: string,
|
||||
prompt: AgentPromptInput,
|
||||
options: AgentRunOptions | undefined,
|
||||
promptStart?: ForegroundPromptStart,
|
||||
assertAdmission?: (agent: ActiveManagedAgent) => void,
|
||||
): Promise<AsyncGenerator<AgentStreamEvent>> {
|
||||
let stalledStart: PendingForegroundRun | null = null;
|
||||
@@ -3641,7 +3683,7 @@ export class AgentManager {
|
||||
if (!this.hasInFlightRun(agent.id)) {
|
||||
return {
|
||||
status: "reserved" as const,
|
||||
iterator: this.streamAgent(agent.id, prompt, options),
|
||||
iterator: this.streamAgent(agent.id, prompt, options, promptStart),
|
||||
};
|
||||
}
|
||||
agent.pendingReplacement = true;
|
||||
@@ -3655,7 +3697,7 @@ export class AgentManager {
|
||||
}
|
||||
return {
|
||||
status: "reserved" as const,
|
||||
iterator: this.streamAgent(agent.id, prompt, options),
|
||||
iterator: this.streamAgent(agent.id, prompt, options, promptStart),
|
||||
};
|
||||
} catch (error) {
|
||||
agent.pendingReplacement = false;
|
||||
@@ -3846,7 +3888,10 @@ export class AgentManager {
|
||||
}
|
||||
|
||||
async cancelAgentRun(agentId: string): Promise<AgentRunCancellationResult> {
|
||||
return this.runForegroundMutation(agentId, () => this.cancelAgentRunNow(agentId));
|
||||
return this.runForegroundMutation(agentId, () => {
|
||||
this.requireSessionAgent(agentId).pendingReplacement = false;
|
||||
return this.cancelAgentRunNow(agentId);
|
||||
});
|
||||
}
|
||||
|
||||
private async cancelAgentRunNow(agentId: string): Promise<AgentRunCancellationResult> {
|
||||
|
||||
@@ -15,6 +15,7 @@ import { join } from "node:path";
|
||||
import { createTestLogger } from "../../test-utils/test-logger.js";
|
||||
import { AgentManager } from "./agent-manager.js";
|
||||
import { waitForAgentRunStartWithTimeout } from "./agent-prompt.js";
|
||||
import { ForegroundPromptStart } from "./agent-run-state.js";
|
||||
import type {
|
||||
AgentClient,
|
||||
AgentRunResult,
|
||||
@@ -161,7 +162,7 @@ class SlowStartAgentClient implements AgentClient {
|
||||
async function createRunStartScenario(startDelayMs: number | null): Promise<{
|
||||
agentManager: AgentManager;
|
||||
agentId: string;
|
||||
startRun: () => Promise<void>;
|
||||
startRun: () => Promise<{ started: Promise<void> }>;
|
||||
cleanup: () => Promise<void>;
|
||||
}> {
|
||||
const workdir = mkdtempSync(join(tmpdir(), "agent-run-start-budget-"));
|
||||
@@ -178,14 +179,16 @@ async function createRunStartScenario(startDelayMs: number | null): Promise<{
|
||||
return {
|
||||
agentManager,
|
||||
agentId: snapshot.id,
|
||||
// streamAgent registers the pending run synchronously, so the wait always observes it.
|
||||
// Returns the sender's start, bound to the run streamAgent registers.
|
||||
startRun: async () => {
|
||||
const run = agentManager.streamAgent(snapshot.id, "start the run");
|
||||
const start = new ForegroundPromptStart(snapshot.id);
|
||||
const run = agentManager.streamAgent(snapshot.id, "start the run", undefined, start);
|
||||
drained = (async () => {
|
||||
for await (const _event of run) {
|
||||
// Drain whatever the turn produces.
|
||||
}
|
||||
})().catch(() => undefined);
|
||||
return { started: start.started };
|
||||
},
|
||||
cleanup: async () => {
|
||||
// Release any turn still held open, then close. The drain is deliberately not
|
||||
@@ -207,8 +210,8 @@ test("waiting for a run start outlasts the slowest provider startup budget", asy
|
||||
vi.useFakeTimers();
|
||||
|
||||
try {
|
||||
await scenario.startRun();
|
||||
const wait = waitForAgentRunStartWithTimeout(scenario.agentManager, scenario.agentId);
|
||||
const { started } = await scenario.startRun();
|
||||
const wait = waitForAgentRunStartWithTimeout(scenario.agentManager, scenario.agentId, started);
|
||||
let settled = false;
|
||||
const markSettled = () => {
|
||||
settled = true;
|
||||
@@ -233,8 +236,8 @@ test("waiting for a run start still gives up at the run start budget", async ()
|
||||
vi.useFakeTimers();
|
||||
|
||||
try {
|
||||
await scenario.startRun();
|
||||
const wait = waitForAgentRunStartWithTimeout(scenario.agentManager, scenario.agentId);
|
||||
const { started } = await scenario.startRun();
|
||||
const wait = waitForAgentRunStartWithTimeout(scenario.agentManager, scenario.agentId, started);
|
||||
const rejection = expect(wait).rejects.toThrow(
|
||||
"codex run did not start within 60 seconds (phase: run start)",
|
||||
);
|
||||
|
||||
@@ -3,6 +3,7 @@ import type { Logger } from "pino";
|
||||
|
||||
import type { AgentPromptInput, AgentRunOptions } from "./agent-sdk-types.js";
|
||||
import type { AgentManager, ManagedAgent } from "./agent-manager.js";
|
||||
import { ForegroundPromptStart } from "./agent-run-state.js";
|
||||
import type { AgentStorage } from "./agent-storage.js";
|
||||
import { ensureAgentLoaded } from "./agent-loading.js";
|
||||
import { isStaleProviderSessionError } from "./stale-provider-session-error.js";
|
||||
@@ -38,11 +39,17 @@ export interface StartAgentRunOptions {
|
||||
|
||||
export type PromptDispatchDisposition = "out_of_band" | "steered" | "turn_started";
|
||||
|
||||
/** A dispatched prompt. A started turn carries its sender's start outcome. */
|
||||
export type PromptDispatchResult =
|
||||
| { disposition: "turn_started"; started: Promise<void> }
|
||||
| { disposition: Exclude<PromptDispatchDisposition, "turn_started"> };
|
||||
|
||||
async function steerOrReplaceActiveRun(
|
||||
agentManager: AgentRunController,
|
||||
agentId: string,
|
||||
prompt: AgentPromptInput,
|
||||
options: StartAgentRunOptions | undefined,
|
||||
promptStart: ForegroundPromptStart,
|
||||
): Promise<
|
||||
| { disposition: "steered" }
|
||||
| {
|
||||
@@ -57,7 +64,12 @@ async function steerOrReplaceActiveRun(
|
||||
const steerOptions = options.clearPendingPermissions
|
||||
? { ...options.runOptions, clearPendingPermissions: true }
|
||||
: options.runOptions;
|
||||
const result = await agentManager.steerOrReplaceActiveTurn(agentId, prompt, steerOptions);
|
||||
const result = await agentManager.steerOrReplaceActiveTurn(
|
||||
agentId,
|
||||
prompt,
|
||||
steerOptions,
|
||||
promptStart,
|
||||
);
|
||||
if (result.status === "steered") {
|
||||
return { disposition: "steered" };
|
||||
}
|
||||
@@ -72,14 +84,15 @@ async function startOrReplaceRun(
|
||||
agentId: string,
|
||||
prompt: AgentPromptInput,
|
||||
options: StartAgentRunOptions | undefined,
|
||||
promptStart: ForegroundPromptStart,
|
||||
): Promise<{
|
||||
iterator: AsyncGenerator<import("./agent-sdk-types.js").AgentStreamEvent>;
|
||||
replaced: boolean;
|
||||
}> {
|
||||
const replaced = Boolean(options?.replaceRunning && agentManager.hasInFlightRun(agentId));
|
||||
const iterator = replaced
|
||||
? await agentManager.replaceAgentRun(agentId, prompt, options?.runOptions)
|
||||
: agentManager.streamAgent(agentId, prompt, options?.runOptions);
|
||||
? await agentManager.replaceAgentRun(agentId, prompt, options?.runOptions, promptStart)
|
||||
: agentManager.streamAgent(agentId, prompt, options?.runOptions, promptStart);
|
||||
return { iterator, replaced };
|
||||
}
|
||||
|
||||
@@ -97,7 +110,7 @@ export async function startAgentRun(
|
||||
prompt: AgentPromptInput,
|
||||
logger: Logger,
|
||||
options?: StartAgentRunOptions,
|
||||
): Promise<{ disposition: PromptDispatchDisposition }> {
|
||||
): Promise<PromptDispatchResult> {
|
||||
const snapshot = agentManager.getAgent(agentId);
|
||||
logger.trace(
|
||||
{
|
||||
@@ -118,16 +131,25 @@ export async function startAgentRun(
|
||||
options?.onDispatch?.("out_of_band");
|
||||
return { disposition: "out_of_band" };
|
||||
}
|
||||
const promptStart = new ForegroundPromptStart(agentId);
|
||||
try {
|
||||
await agentManager.reloadStalePluginSession(agentId);
|
||||
return await startAgentRunInner(agentManager, agentId, prompt, logger, options);
|
||||
try {
|
||||
await agentManager.reloadStalePluginSession(agentId);
|
||||
return await startAgentRunInner(agentManager, agentId, prompt, logger, options, promptStart);
|
||||
} catch (error) {
|
||||
if (!isStaleProviderSessionError(error)) throw error;
|
||||
logger.info(
|
||||
{ agentId, err: error },
|
||||
"Provider session went stale; reopening from persistence",
|
||||
);
|
||||
// The live session belongs to a retired plugin runtime. Reload swaps in a
|
||||
// fresh session on the current runtime while preserving history and labels.
|
||||
await agentManager.reloadAgentSession(agentId);
|
||||
return await startAgentRunInner(agentManager, agentId, prompt, logger, options, promptStart);
|
||||
}
|
||||
} catch (error) {
|
||||
if (!isStaleProviderSessionError(error)) throw error;
|
||||
logger.info({ agentId, err: error }, "Provider session went stale; reopening from persistence");
|
||||
// The live session belongs to a retired plugin runtime. Reload swaps in a
|
||||
// fresh session on the current runtime while preserving history and labels.
|
||||
await agentManager.reloadAgentSession(agentId);
|
||||
return await startAgentRunInner(agentManager, agentId, prompt, logger, options);
|
||||
promptStart.end();
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -136,12 +158,13 @@ async function startAgentRunInner(
|
||||
agentId: string,
|
||||
prompt: AgentPromptInput,
|
||||
logger: Logger,
|
||||
options?: StartAgentRunOptions,
|
||||
): Promise<{ disposition: PromptDispatchDisposition }> {
|
||||
options: StartAgentRunOptions | undefined,
|
||||
promptStart: ForegroundPromptStart,
|
||||
): Promise<PromptDispatchResult> {
|
||||
const snapshot = agentManager.getAgent(agentId);
|
||||
const steered = options?.idleOnly
|
||||
? null
|
||||
: await steerOrReplaceActiveRun(agentManager, agentId, prompt, options);
|
||||
: await steerOrReplaceActiveRun(agentManager, agentId, prompt, options, promptStart);
|
||||
if (options?.idleOnly && agentManager.hasInFlightRun(agentId)) {
|
||||
throw new AgentTurnBusyError(`Agent ${agentId} is running`);
|
||||
}
|
||||
@@ -151,7 +174,7 @@ async function startAgentRunInner(
|
||||
}
|
||||
const { iterator, replaced } = steered
|
||||
? { iterator: steered.iterator, replaced: true }
|
||||
: await startOrReplaceRun(agentManager, agentId, prompt, options);
|
||||
: await startOrReplaceRun(agentManager, agentId, prompt, options, promptStart);
|
||||
logger.trace(
|
||||
{
|
||||
agentId,
|
||||
@@ -173,7 +196,7 @@ async function startAgentRunInner(
|
||||
"Provider session went stale; reopening from persistence",
|
||||
);
|
||||
await agentManager.reloadAgentSession(agentId);
|
||||
const retry = await startOrReplaceRun(agentManager, agentId, prompt, options);
|
||||
const retry = await startOrReplaceRun(agentManager, agentId, prompt, options, promptStart);
|
||||
await drainAgentRunIterator(retry.iterator);
|
||||
}
|
||||
logger.trace(
|
||||
@@ -195,9 +218,11 @@ async function startAgentRunInner(
|
||||
"agent.session.iterator.error",
|
||||
);
|
||||
logger.error({ err: error, agentId }, "Agent stream failed");
|
||||
} finally {
|
||||
promptStart.end();
|
||||
}
|
||||
})();
|
||||
return { disposition: "turn_started" };
|
||||
return { disposition: "turn_started", started: promptStart.started };
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -270,8 +295,9 @@ export interface StartCreatedAgentInitialPromptParams {
|
||||
const AGENT_RUN_START_TIMEOUT_MS = 60_000;
|
||||
|
||||
export async function waitForAgentRunStartWithTimeout(
|
||||
agentManager: AgentManager,
|
||||
agentManager: Pick<AgentManager, "getAgent">,
|
||||
agentId: string,
|
||||
started: Promise<void>,
|
||||
signal?: AbortSignal,
|
||||
): Promise<void> {
|
||||
const provider = agentManager.getAgent(agentId)?.provider ?? "provider";
|
||||
@@ -286,15 +312,28 @@ export async function waitForAgentRunStartWithTimeout(
|
||||
AGENT_RUN_START_TIMEOUT_MS,
|
||||
);
|
||||
|
||||
const abortSignal = signal ? AbortSignal.any([startAbort.signal, signal]) : startAbort.signal;
|
||||
let onAbort: (() => void) | null = null;
|
||||
const aborted = new Promise<never>((_, reject) => {
|
||||
onAbort = () => reject(createStartAbortError(abortSignal.reason));
|
||||
if (abortSignal.aborted) onAbort();
|
||||
else abortSignal.addEventListener("abort", onAbort, { once: true });
|
||||
});
|
||||
try {
|
||||
await agentManager.waitForAgentRunStart(agentId, {
|
||||
signal: signal ? AbortSignal.any([startAbort.signal, signal]) : startAbort.signal,
|
||||
});
|
||||
await Promise.race([started, aborted]);
|
||||
} finally {
|
||||
clearTimeout(startTimeout);
|
||||
if (onAbort) abortSignal.removeEventListener("abort", onAbort);
|
||||
}
|
||||
}
|
||||
|
||||
function createStartAbortError(reason: unknown): Error {
|
||||
let message = "wait_for_agent_start aborted";
|
||||
if (typeof reason === "string") message = reason;
|
||||
else if (reason instanceof Error) message = reason.message;
|
||||
return Object.assign(new Error(message), { name: "AbortError" });
|
||||
}
|
||||
|
||||
async function resolvePromptSource(
|
||||
source: AgentPromptSource | undefined,
|
||||
manager: Pick<AgentManager, "getAgent">,
|
||||
@@ -320,7 +359,7 @@ async function resolvePromptSource(
|
||||
*/
|
||||
export async function sendPromptToAgent(
|
||||
params: SendPromptToAgentParams,
|
||||
): Promise<{ disposition: PromptDispatchDisposition }> {
|
||||
): Promise<PromptDispatchResult> {
|
||||
const source = await resolvePromptSource(params.source, params.agentManager, params.agentStorage);
|
||||
const delivery = prepareAgentMessage(params.prompt, source, params.messageId);
|
||||
return sendPreparedPromptToAgent({
|
||||
@@ -335,14 +374,14 @@ export async function sendPromptToAgent(
|
||||
/** Dispatch daemon-prepared context without reclassifying it as human input. */
|
||||
export async function sendPreparedPromptToAgent(
|
||||
params: Omit<SendPromptToAgentParams, "source" | "messageId">,
|
||||
): Promise<{ disposition: PromptDispatchDisposition }> {
|
||||
): Promise<PromptDispatchResult> {
|
||||
const unarchive = params.unarchive ?? true;
|
||||
|
||||
const record = await params.agentStorage.get(params.agentId);
|
||||
let archivedAtToRestore: string | null = null;
|
||||
if (record?.archivedAt) {
|
||||
if (!unarchive) {
|
||||
return { disposition: "turn_started" };
|
||||
return { disposition: "turn_started", started: Promise.resolve() };
|
||||
}
|
||||
if (await unarchiveAgentState(params.agentStorage, params.agentManager, params.agentId)) {
|
||||
archivedAtToRestore = record.archivedAt;
|
||||
@@ -408,7 +447,11 @@ export async function startCreatedAgentInitialPrompt(
|
||||
);
|
||||
|
||||
if (dispatchResult.disposition === "turn_started") {
|
||||
await waitForAgentRunStartWithTimeout(params.agentManager, params.agentId);
|
||||
await waitForAgentRunStartWithTimeout(
|
||||
params.agentManager,
|
||||
params.agentId,
|
||||
dispatchResult.started,
|
||||
);
|
||||
}
|
||||
|
||||
const refreshedSnapshot = params.agentManager.getAgent(params.agentId) ?? params.snapshot ?? null;
|
||||
|
||||
@@ -13,7 +13,7 @@ export interface ForegroundTurnWaiter {
|
||||
type ForegroundRunStart =
|
||||
| { status: "pending" }
|
||||
| { status: "started"; turnId: string }
|
||||
| { status: "failed"; error: string };
|
||||
| { status: "failed"; error: string; stale?: true };
|
||||
|
||||
export interface PendingForegroundRun {
|
||||
token: string;
|
||||
@@ -343,3 +343,59 @@ function settleTrackedRun(run: TrackedAgentRun): void {
|
||||
run.settled = true;
|
||||
run.resolveSettled();
|
||||
}
|
||||
|
||||
/**
|
||||
* Follows one sender's prompt to the foreground run that starts it. Each run created for the
|
||||
* prompt, including a stale-session retry, is bound here, so `started` settles for this
|
||||
* sender's prompt and never for another run the agent tracks.
|
||||
*/
|
||||
export class ForegroundPromptStart {
|
||||
readonly started: Promise<void>;
|
||||
private resolveStarted!: () => void;
|
||||
private rejectStarted!: (error: Error) => void;
|
||||
private run: PendingForegroundRun | null = null;
|
||||
private done = false;
|
||||
|
||||
constructor(private readonly agentId: string) {
|
||||
this.started = new Promise<void>((resolve, reject) => {
|
||||
this.resolveStarted = resolve;
|
||||
this.rejectStarted = reject;
|
||||
});
|
||||
// Steered and fire-and-forget dispatches never wait on the start.
|
||||
this.started.catch(() => undefined);
|
||||
}
|
||||
|
||||
/** A run was created for this prompt. */
|
||||
bind(run: PendingForegroundRun): void {
|
||||
this.run = run;
|
||||
void Promise.race([run.turnStartedPromise, run.settledPromise]).then(() =>
|
||||
this.settle(run, { ended: false }),
|
||||
);
|
||||
}
|
||||
|
||||
/** The prompt's dispatch is over; no further run will be created for it. */
|
||||
end(): void {
|
||||
this.settle(this.run, { ended: true });
|
||||
}
|
||||
|
||||
private settle(run: PendingForegroundRun | null, { ended }: { ended: boolean }): void {
|
||||
if (this.done || run !== this.run) return;
|
||||
if (run?.start.status === "started") {
|
||||
this.done = true;
|
||||
this.resolveStarted();
|
||||
return;
|
||||
}
|
||||
// A stale-session failure is retried with a new run; wait for it unless dispatch ended.
|
||||
if (run?.start.status === "failed" && run.start.stale && !ended) return;
|
||||
this.done = true;
|
||||
this.rejectStarted(new Error(this.describeUnstarted(run)));
|
||||
}
|
||||
|
||||
private describeUnstarted(run: PendingForegroundRun | null): string {
|
||||
if (run?.start.status === "failed") return run.start.error;
|
||||
if (run?.settled) {
|
||||
return `Agent ${this.agentId} run was canceled before its turn started; its prompt was not delivered`;
|
||||
}
|
||||
return `Agent ${this.agentId} run finished before starting`;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -528,6 +528,14 @@ export type AgentPermissionResponse =
|
||||
interrupt?: boolean;
|
||||
};
|
||||
|
||||
/** A requested turn was canceled before the provider accepted it. */
|
||||
export class AgentTurnStartCanceledError extends Error {
|
||||
constructor() {
|
||||
super("Turn was canceled before starting");
|
||||
this.name = "AgentTurnStartCanceledError";
|
||||
}
|
||||
}
|
||||
|
||||
export interface AgentRunResult {
|
||||
sessionId: string;
|
||||
finalText: string;
|
||||
|
||||
@@ -10,6 +10,7 @@ import { AgentManager } from "../agent-manager.js";
|
||||
import { AgentStorage } from "../agent-storage.js";
|
||||
import type { CreatePaseoWorktreeWorkflowResult } from "../../worktree-session.js";
|
||||
import { createAgentCommand } from "./create.js";
|
||||
import { ForegroundPromptStart } from "../agent-run-state.js";
|
||||
import type { ManagedAgent } from "../agent-manager.js";
|
||||
|
||||
const logger = createTestLogger();
|
||||
@@ -89,9 +90,12 @@ test("session create forwards clientMessageId to the initial prompt run options"
|
||||
firstAgentContext: { attachments: [] },
|
||||
});
|
||||
|
||||
expect(streamAgent).toHaveBeenCalledWith("agent-1", "hello from create", {
|
||||
clientMessageId: "msg-create-1",
|
||||
});
|
||||
expect(streamAgent).toHaveBeenCalledWith(
|
||||
"agent-1",
|
||||
"hello from create",
|
||||
{ clientMessageId: "msg-create-1" },
|
||||
expect.any(ForegroundPromptStart),
|
||||
);
|
||||
});
|
||||
|
||||
test("session create validates the requested mode against the provider's modes", async () => {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { AgentRunState, ForegroundPromptStart } from "./agent-run-state.js";
|
||||
import {
|
||||
createFinishSubscriptions,
|
||||
createFinishObservation,
|
||||
@@ -279,8 +280,15 @@ function buildAgentManagerSpies() {
|
||||
steerOrReplaceActiveTurn: async () => ({ status: "inactive" as const }),
|
||||
tryRunOutOfBand: vi.fn().mockReturnValue(false),
|
||||
subscribe: vi.fn().mockReturnValue(() => {}),
|
||||
streamAgent: vi.fn(() => (async function* noop() {})()),
|
||||
waitForAgentRunStart: vi.fn().mockResolvedValue(undefined),
|
||||
streamAgent: vi.fn(
|
||||
(agentId: string, _prompt: unknown, _options: unknown, start?: ForegroundPromptStart) => {
|
||||
const runs = new AgentRunState();
|
||||
const run = runs.createPendingRun(agentId);
|
||||
runs.settleForegroundStart(run, { status: "started", turnId: `${agentId}-turn` });
|
||||
start?.bind(run);
|
||||
return (async function* noop() {})();
|
||||
},
|
||||
),
|
||||
respondToPermission: vi.fn(),
|
||||
cancelAgentRun: vi.fn(),
|
||||
getPendingPermissions: vi.fn(),
|
||||
|
||||
@@ -91,7 +91,7 @@ test.each([
|
||||
}
|
||||
});
|
||||
|
||||
test("bypass allows execution without publishing permission events and follows live mode changes", async () => {
|
||||
async function createBypassSession() {
|
||||
let requestPermission: CanUseTool | undefined;
|
||||
const query = Object.assign((async function* () {})(), {
|
||||
async setPermissionMode(_mode: PermissionMode) {},
|
||||
@@ -112,17 +112,25 @@ test("bypass allows execution without publishing permission events and follows l
|
||||
});
|
||||
const events: AgentStreamEvent[] = [];
|
||||
session.subscribe((event) => events.push(event));
|
||||
await session.setMode("bypassPermissions");
|
||||
if (!requestPermission) throw new Error("SDK permission callback was not installed");
|
||||
return { session, events, requestPermission };
|
||||
}
|
||||
|
||||
test("bypass approves Claude's own checks without publishing permission events and follows live mode changes", async () => {
|
||||
const { session, events, requestPermission } = await createBypassSession();
|
||||
try {
|
||||
await session.setMode("bypassPermissions");
|
||||
if (!requestPermission) throw new Error("SDK permission callback was not installed");
|
||||
const controller = new AbortController();
|
||||
const input = { command: "echo hello" };
|
||||
const result = requestPermission("Bash", input, {
|
||||
const input = { command: "rm -rf build" };
|
||||
// Claude Code sends these fields, but this SDK version does not declare them on CanUseTool.
|
||||
const ownCheck = {
|
||||
signal: controller.signal,
|
||||
toolUseID: "execution",
|
||||
decisionReason: "Explicit ask rule",
|
||||
});
|
||||
// Abort also settles the pre-fix callback, so this repro never hangs.
|
||||
decisionReason: "Dangerous rm command",
|
||||
decisionReasonType: "safetyCheck",
|
||||
};
|
||||
const result = requestPermission("Bash", input, ownCheck);
|
||||
// Abort also settles a prompting callback, so this test never hangs.
|
||||
controller.abort();
|
||||
await expect(result).resolves.toMatchObject({ behavior: "allow", updatedInput: input });
|
||||
expect(events.filter((event) => event.type.startsWith("permission_"))).toEqual([]);
|
||||
@@ -135,6 +143,7 @@ test("bypass allows execution without publishing permission events and follows l
|
||||
] as const) {
|
||||
await session.setMode(mode);
|
||||
const resolution = requestPermission(tool, toolInput, {
|
||||
...ownCheck,
|
||||
signal: new AbortController().signal,
|
||||
toolUseID: tool,
|
||||
});
|
||||
@@ -149,3 +158,44 @@ test("bypass allows execution without publishing permission events and follows l
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
|
||||
test.each([
|
||||
["an ask rule", { decisionReasonType: "rule" }],
|
||||
["a hook", { decisionReasonType: "hook", decisionReason: "Confirm before posting" }],
|
||||
[
|
||||
"an ask rule on Claude's own check",
|
||||
{
|
||||
decisionReasonType: "safetyCheck",
|
||||
matchedAskRule: { source: "policySettings", toolName: "Bash", ruleContent: "rm *" },
|
||||
},
|
||||
],
|
||||
[
|
||||
"a tool the user answers on the card",
|
||||
{ decisionReasonType: "other", requiresUserInteraction: true },
|
||||
],
|
||||
["a compound command with an ask rule in one part", { decisionReasonType: "subcommandResults" }],
|
||||
[
|
||||
"a read the user blocked outside the working directories",
|
||||
{ decisionReasonType: "safetyCheck", decisionReasonCode: "outside_reads_blocked" },
|
||||
],
|
||||
[
|
||||
"an organization's ask limit",
|
||||
{ decisionReasonType: "workingDir", decisionReasonCode: "org_ask_ceiling" },
|
||||
],
|
||||
["a sandbox override the user's read block raised", { decisionReasonType: "sandboxOverride" }],
|
||||
["a Claude Code that does not say why it asks", {}],
|
||||
])("bypass still asks the user about %s", async (_source, why) => {
|
||||
const { session, events, requestPermission } = await createBypassSession();
|
||||
try {
|
||||
const ask = { signal: new AbortController().signal, toolUseID: "execution", ...why };
|
||||
const resolution = requestPermission("Bash", { command: "gh pr comment 1" }, ask);
|
||||
const requestEvent = events.at(-1);
|
||||
expect(requestEvent?.type).toBe("permission_requested");
|
||||
if (requestEvent?.type !== "permission_requested")
|
||||
throw new Error("Missing permission request");
|
||||
await session.respondToPermission(requestEvent.request.id, { behavior: "deny" });
|
||||
await expect(resolution).resolves.toMatchObject({ behavior: "deny" });
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
|
||||
@@ -11,6 +11,7 @@ import path from "node:path";
|
||||
import { LRUCache } from "lru-cache";
|
||||
import stripAnsi from "strip-ansi";
|
||||
import { createImportDescriptorScheduler } from "./import-descriptor-scheduler.js";
|
||||
import { bypassApprovesAsk } from "./bypass-approval.js";
|
||||
import {
|
||||
type AgentDefinition,
|
||||
type CanUseTool,
|
||||
@@ -5319,10 +5320,8 @@ class ClaudeAgentSession implements AgentSession {
|
||||
input,
|
||||
options,
|
||||
): Promise<PermissionResult> => {
|
||||
// Decide before publishing anything: bypassed tools never enter the permission UI.
|
||||
// Claude also routes questions and plan review through this callback.
|
||||
const needsUserAnswer = toolName === "AskUserQuestion" || toolName === "ExitPlanMode";
|
||||
if (this.currentMode === "bypassPermissions" && !needsUserAnswer) {
|
||||
// Decide before publishing anything: bypassed asks never enter the permission UI.
|
||||
if (this.currentMode === "bypassPermissions" && bypassApprovesAsk(toolName, options)) {
|
||||
return { behavior: "allow", updatedInput: input, toolUseID: options.toolUseID };
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
import type { CanUseTool } from "@anthropic-ai/claude-agent-sdk";
|
||||
|
||||
type PermissionOptions = Parameters<CanUseTool>[2];
|
||||
|
||||
// In bypassPermissions, Claude Code still forwards an ask when the user configured one
|
||||
// (a permissions.ask rule, including managed policy, or a PreToolUse hook), when the tool
|
||||
// needs an answer, or when one of its own checks fires. Bypass approves only Claude's own
|
||||
// checks. A missing or unknown reason type stays with the user.
|
||||
// `subcommandResults` is left out: a compound or piped command uses it as a container,
|
||||
// including when a user's ask rule matched one of its parts. `sandboxOverride` is left
|
||||
// out: in Bypass, Claude Code forwards it only when the user's read block or hook raised it.
|
||||
const CLAUDE_OWN_CHECK_TYPES: ReadonlySet<string> = new Set([
|
||||
"safetyCheck",
|
||||
"workingDir",
|
||||
"mode",
|
||||
"classifier",
|
||||
"asyncAgent",
|
||||
]);
|
||||
|
||||
// Settings the user or organization chose, which Claude Code reports under its own types:
|
||||
// permissions.blockReadsOutsideWorkingDirectories, and an organization's ask limit.
|
||||
const CONFIGURED_ASK_CODES: ReadonlySet<string> = new Set([
|
||||
"outside_reads_blocked",
|
||||
"org_ask_ceiling",
|
||||
]);
|
||||
|
||||
const QUESTION_TOOLS: ReadonlySet<string> = new Set(["AskUserQuestion", "ExitPlanMode"]);
|
||||
|
||||
export function bypassApprovesAsk(toolName: string, options: PermissionOptions): boolean {
|
||||
if (QUESTION_TOOLS.has(toolName) || options.matchedAskRule) {
|
||||
return false;
|
||||
}
|
||||
// The SDK forwards these from Claude Code without declaring them on CanUseTool.
|
||||
if ("requiresUserInteraction" in options && options.requiresUserInteraction === true) {
|
||||
return false;
|
||||
}
|
||||
const reasonCode = "decisionReasonCode" in options ? options.decisionReasonCode : undefined;
|
||||
if (typeof reasonCode === "string" && CONFIGURED_ASK_CODES.has(reasonCode)) {
|
||||
return false;
|
||||
}
|
||||
const reasonType = "decisionReasonType" in options ? options.decisionReasonType : undefined;
|
||||
return typeof reasonType === "string" && CLAUDE_OWN_CHECK_TYPES.has(reasonType);
|
||||
}
|
||||
@@ -5428,7 +5428,7 @@ describe("Codex app-server provider", () => {
|
||||
|
||||
threadStart.resolve({ thread: { id: "thread-1" } });
|
||||
await expect(interruptPromise).resolves.toBeUndefined();
|
||||
await expect(resultPromise).rejects.toThrow("interrupted before reaching Codex");
|
||||
await expect(resultPromise).resolves.toMatchObject({ canceled: true, timeline: [] });
|
||||
expect(appServer.requests()).not.toContainEqual(
|
||||
expect.objectContaining({ method: "turn/start" }),
|
||||
);
|
||||
|
||||
@@ -3,6 +3,7 @@ import { applyProviderOptionsPatch } from "../option-controls.js";
|
||||
import { assertChangesAreLive, validateProviderOptions } from "../provider-options.js";
|
||||
import { CodexBackgroundInventory } from "./codex/background-inventory.js";
|
||||
import {
|
||||
AgentTurnStartCanceledError,
|
||||
getAgentStreamEventTurnId,
|
||||
type AgentPermissionAction,
|
||||
type AgentCapabilityFlags,
|
||||
@@ -4696,7 +4697,7 @@ export class CodexAppServerAgentSession implements AgentSession {
|
||||
// outlives it into the new turn.
|
||||
await this.waitForInterruptedTurnCleanup();
|
||||
if (pendingStart.cancelRequested) {
|
||||
throw new Error("Codex turn start was interrupted before reaching Codex");
|
||||
throw new AgentTurnStartCanceledError();
|
||||
}
|
||||
await this.client.request("turn/start", turnStart.params, TURN_START_TIMEOUT_MS);
|
||||
return { turnId };
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import {
|
||||
AgentTurnStartCanceledError,
|
||||
getAgentStreamEventTurnId,
|
||||
type AgentPromptInput,
|
||||
type AgentRunOptions,
|
||||
@@ -90,6 +91,9 @@ export async function runProviderTurn({
|
||||
processEvent(event);
|
||||
}
|
||||
await completion;
|
||||
} catch (error) {
|
||||
if (!(error instanceof AgentTurnStartCanceledError)) throw error;
|
||||
return { sessionId: await getSessionId(), finalText: "", timeline: [], canceled: true };
|
||||
} finally {
|
||||
unsubscribe();
|
||||
}
|
||||
|
||||
@@ -2051,7 +2051,7 @@ function createToolCatalog(
|
||||
};
|
||||
}
|
||||
|
||||
const { disposition } = await sendPromptToAgent({
|
||||
const dispatch = await sendPromptToAgent({
|
||||
agentManager,
|
||||
agentStorage,
|
||||
agentId,
|
||||
@@ -2070,11 +2070,14 @@ function createToolCatalog(
|
||||
});
|
||||
|
||||
// Return once the provider has accepted the turn, so the status reports it running.
|
||||
if (disposition === "turn_started") {
|
||||
await waitForAgentRunStartWithTimeout(agentManager, agentId).catch((error) => {
|
||||
rejectNotification();
|
||||
throw error;
|
||||
});
|
||||
const { disposition } = dispatch;
|
||||
if (dispatch.disposition === "turn_started") {
|
||||
await waitForAgentRunStartWithTimeout(agentManager, agentId, dispatch.started).catch(
|
||||
(error) => {
|
||||
rejectNotification();
|
||||
throw error;
|
||||
},
|
||||
);
|
||||
}
|
||||
const currentSnapshot = agentManager.getAgent(agentId);
|
||||
|
||||
|
||||
@@ -31,7 +31,6 @@ function createPullRequest(
|
||||
baseRefName: "main",
|
||||
headRefName: "feature",
|
||||
headSha: "same-head",
|
||||
commitOids: ["same-head"],
|
||||
isMerged: true,
|
||||
...overrides,
|
||||
};
|
||||
@@ -350,7 +349,7 @@ afterEach(() => {
|
||||
|
||||
describe("archiveIfSafe", () => {
|
||||
test("denies archive when checkout facts do not establish safety", async () => {
|
||||
for (const git of [{ headSha: undefined }, { isDirty: null }]) {
|
||||
for (const git of [{ headSha: undefined }, { behindOfOrigin: 1 }, { isDirty: null }]) {
|
||||
const harness = createHarness({ snapshot: createSnapshot({ git }) });
|
||||
await runArchiveIfSafe(harness);
|
||||
expect(harness.deps.archiveByScope).not.toHaveBeenCalled();
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { pullRequestContainsCommit } from "../../services/pull-request-contains-commit.js";
|
||||
import type { Logger } from "pino";
|
||||
|
||||
import type { AgentManager } from "../agent/agent-manager.js";
|
||||
@@ -66,8 +65,8 @@ export async function archiveIfSafe(input: {
|
||||
|
||||
if (
|
||||
!pullRequest?.isMerged ||
|
||||
!pullRequest.headSha ||
|
||||
!snapshot.git.headSha ||
|
||||
snapshot.git.headSha !== pullRequest.headSha ||
|
||||
snapshot.forge.error
|
||||
) {
|
||||
return;
|
||||
@@ -75,18 +74,13 @@ export async function archiveIfSafe(input: {
|
||||
if (snapshot.git.isDirty !== false) {
|
||||
return;
|
||||
}
|
||||
if (snapshot.git.aheadOfOrigin !== null && snapshot.git.aheadOfOrigin !== 0) {
|
||||
if (
|
||||
(snapshot.git.aheadOfOrigin !== null && snapshot.git.aheadOfOrigin !== 0) ||
|
||||
(snapshot.git.behindOfOrigin !== null && snapshot.git.behindOfOrigin !== 0)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (
|
||||
!pullRequestContainsCommit({
|
||||
workspaceCommit: snapshot.git.headSha,
|
||||
pullRequestCommits: pullRequest.commitOids,
|
||||
})
|
||||
)
|
||||
return;
|
||||
|
||||
const ownership = await deps.isPaseoOwnedWorktreeCwd(cwd, {
|
||||
paseoHome: options.paseoHome,
|
||||
worktreesRoot: options.paseoWorktreesBaseRoot,
|
||||
|
||||
@@ -179,7 +179,6 @@ async function createUnobservedWorkspace(journeyOptions?: {
|
||||
});
|
||||
let observation: PullRequestObservation | null = null;
|
||||
let remoteHeadSha = execFileSync("git", ["rev-parse", "HEAD"], { cwd, encoding: "utf8" }).trim();
|
||||
const workspaceHeadSha = remoteHeadSha;
|
||||
const reads: Array<string | undefined> = [];
|
||||
const archives: string[] = [];
|
||||
let archiveDecisions = 0;
|
||||
@@ -195,7 +194,6 @@ async function createUnobservedWorkspace(journeyOptions?: {
|
||||
status: observation && {
|
||||
...observation,
|
||||
headSha: remoteHeadSha,
|
||||
commitOids: [workspaceHeadSha, remoteHeadSha],
|
||||
title: observation.headRefName,
|
||||
baseRefName: "main",
|
||||
isMerged: observation.state === "merged",
|
||||
@@ -262,23 +260,7 @@ async function createUnobservedWorkspace(journeyOptions?: {
|
||||
metrics: () => service.getMetrics(),
|
||||
isActive: () => active,
|
||||
advanceRemoteHead: () => {
|
||||
remoteHeadSha = execFileSync(
|
||||
"git",
|
||||
[
|
||||
"-c",
|
||||
"user.name=Test",
|
||||
"-c",
|
||||
"user.email=test@example.com",
|
||||
"commit-tree",
|
||||
"HEAD^{tree}",
|
||||
"-p",
|
||||
"HEAD",
|
||||
"-m",
|
||||
"remote update",
|
||||
],
|
||||
{ cwd, encoding: "utf8" },
|
||||
).trim();
|
||||
run(cwd, ["update-ref", "refs/remotes/origin/workspace", remoteHeadSha]);
|
||||
remoteHeadSha = "a".repeat(40);
|
||||
},
|
||||
makeDirty: () => writeFileSync(path.join(cwd, "README.md"), "uncommitted work\n"),
|
||||
commitUnpushed: () => {
|
||||
@@ -325,7 +307,7 @@ describe("workspace auto-archive behavior", () => {
|
||||
expect(workspace.isActive()).toBe(true);
|
||||
});
|
||||
|
||||
test("archives a clean workspace contained in the advanced merged PR head", async () => {
|
||||
test("keeps a merged PR visible and the workspace active when its remote head advances", async () => {
|
||||
const workspace = await createUnobservedWorkspace();
|
||||
const open = await workspace.observe("open");
|
||||
workspace.advanceRemoteHead();
|
||||
@@ -333,9 +315,8 @@ describe("workspace auto-archive behavior", () => {
|
||||
await vi.waitFor(() => expect(workspace.archiveDecisions()).toBe(1));
|
||||
expect(merged.forge.pullRequest?.url).toBe(open.forge.pullRequest?.url);
|
||||
expect(merged.forge.pullRequest?.headSha).not.toBe(merged.git.headSha);
|
||||
expect(merged.git.behindOfOrigin).toBe(1);
|
||||
expect(workspace.isActive()).toBe(false);
|
||||
expect(workspace.archives).toHaveLength(1);
|
||||
expect(workspace.isActive()).toBe(true);
|
||||
expect(workspace.archives).toEqual([]);
|
||||
});
|
||||
|
||||
test("archives a clean owned workspace on an unobserved open-to-merged transition only once", async () => {
|
||||
|
||||
@@ -51,7 +51,6 @@ describe("checkout status projection", () => {
|
||||
const payload = normalizeCheckoutPrStatusPayload(
|
||||
{
|
||||
number: 123,
|
||||
commitOids: ["server-only-membership"],
|
||||
repoOwner: "internal-owner",
|
||||
repoName: "internal-repo",
|
||||
url: "https://github.com/getpaseo/paseo/pull/123",
|
||||
@@ -77,7 +76,6 @@ describe("checkout status projection", () => {
|
||||
"github",
|
||||
);
|
||||
|
||||
expect(payload).not.toHaveProperty("commitOids");
|
||||
expect(payload).toHaveProperty("repoOwner", "internal-owner");
|
||||
expect(payload).toHaveProperty("repoName", "internal-repo");
|
||||
expect(payload).toHaveProperty("forge", "github");
|
||||
|
||||
@@ -38,6 +38,7 @@ import {
|
||||
type ScheduleServiceOptions,
|
||||
} from "./service.js";
|
||||
import { ScheduleStore } from "./store.js";
|
||||
import { ForegroundPromptStart } from "../agent/agent-run-state.js";
|
||||
import type { ScheduleExecutionResult, StoredSchedule } from "@getpaseo/protocol/schedule/types";
|
||||
|
||||
interface ScheduleServiceInternals {
|
||||
@@ -754,6 +755,7 @@ describe("ScheduleService", () => {
|
||||
agent.id,
|
||||
expect.stringContaining(`Schedule fired (id=${schedule.id}, run=`),
|
||||
undefined,
|
||||
expect.any(ForegroundPromptStart),
|
||||
]);
|
||||
});
|
||||
|
||||
|
||||
@@ -6188,17 +6188,9 @@ export class Session {
|
||||
private buildWorkspaceGitHubRuntimePayload(
|
||||
snapshot: WorkspaceGitRuntimeSnapshot,
|
||||
): NonNullable<WorkspaceDescriptorPayload["githubRuntime"]> {
|
||||
if (!snapshot.forge.pullRequest) {
|
||||
return {
|
||||
featuresEnabled: snapshot.forge.featuresEnabled,
|
||||
pullRequest: null,
|
||||
error: snapshot.forge.error,
|
||||
};
|
||||
}
|
||||
const { commitOids: _commitOids, ...pullRequest } = snapshot.forge.pullRequest;
|
||||
return {
|
||||
featuresEnabled: snapshot.forge.featuresEnabled,
|
||||
pullRequest,
|
||||
pullRequest: snapshot.forge.pullRequest,
|
||||
error: snapshot.forge.error,
|
||||
};
|
||||
}
|
||||
@@ -9001,6 +8993,7 @@ export class Session {
|
||||
await waitForAgentRunStartWithTimeout(
|
||||
this.agentManager,
|
||||
agentId,
|
||||
result.started,
|
||||
this.delivery.requestSignal,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -50,7 +50,11 @@ export function createTestAgentMessages(params: {
|
||||
runOptions: { clientMessageId: request.messageIds[0] },
|
||||
});
|
||||
if (result.disposition === "turn_started")
|
||||
await waitForAgentRunStartWithTimeout(params.agentManager, request.recipientId);
|
||||
await waitForAgentRunStartWithTimeout(
|
||||
params.agentManager,
|
||||
request.recipientId,
|
||||
result.started,
|
||||
);
|
||||
return result.disposition;
|
||||
},
|
||||
onError: (error, request) =>
|
||||
|
||||
@@ -745,7 +745,7 @@ export class VoiceAssistantWebSocketServer {
|
||||
{ replayState: false },
|
||||
),
|
||||
dispatch: async (batch) => {
|
||||
const { disposition } = await sendPreparedPromptToAgent({
|
||||
const dispatch = await sendPreparedPromptToAgent({
|
||||
agentManager,
|
||||
agentStorage,
|
||||
agentId: batch.recipientId,
|
||||
@@ -758,9 +758,9 @@ export class VoiceAssistantWebSocketServer {
|
||||
runOptions: { clientMessageId: batch.messageIds[0] },
|
||||
logger: this.logger,
|
||||
});
|
||||
if (disposition === "turn_started")
|
||||
await waitForAgentRunStartWithTimeout(agentManager, batch.recipientId);
|
||||
return disposition;
|
||||
if (dispatch.disposition === "turn_started")
|
||||
await waitForAgentRunStartWithTimeout(agentManager, batch.recipientId, dispatch.started);
|
||||
return dispatch.disposition;
|
||||
},
|
||||
onError: (err, batch) =>
|
||||
this.logger.error(
|
||||
|
||||
@@ -201,8 +201,6 @@ export interface WorkspaceGitRuntimeSnapshot {
|
||||
baseRefName: string;
|
||||
headRefName: string;
|
||||
headSha?: string;
|
||||
/** Server-only commit membership evidence; never projected onto the wire. */
|
||||
commitOids?: string[];
|
||||
isMerged: boolean;
|
||||
isDraft?: boolean;
|
||||
mergeable?: PullRequestMergeable;
|
||||
|
||||
@@ -129,8 +129,6 @@ export interface CurrentPullRequestStatus {
|
||||
baseRefName: string;
|
||||
headRefName: string;
|
||||
headSha?: string;
|
||||
/** Server-only commit membership evidence; never projected onto the wire. */
|
||||
commitOids?: string[];
|
||||
isMerged: boolean;
|
||||
isDraft?: boolean;
|
||||
mergeable: PullRequestMergeable;
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
import { createPullRequestHistory } from "../test-utils/pull-request-history.js";
|
||||
import { onTestFinished } from "vitest";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import type { PullRequestCommandStatus, PullRequestTimelineItem } from "./forge-service.js";
|
||||
@@ -2050,8 +2048,6 @@ describe("createGiteaService", () => {
|
||||
if (args[0] === "pr" && args[1] === "list" && argValue(args, "--state") === "open") {
|
||||
return ok(JSON.stringify([]));
|
||||
}
|
||||
if (args[1]?.includes("/commits?"))
|
||||
return ok(JSON.stringify(args[1].includes("page=1") ? [{ sha: headSha }] : []));
|
||||
if (args[0] === "api" && args[1].includes("/pulls?state=all")) {
|
||||
return ok(JSON.stringify([closedPr]));
|
||||
}
|
||||
@@ -2071,38 +2067,6 @@ describe("createGiteaService", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it("follows commit pagination headers and stops without probing past the last page", async () => {
|
||||
const closed = currentPullRequestApi({
|
||||
number: 8,
|
||||
state: "closed",
|
||||
headRef: "feature",
|
||||
headSha: "remote-head",
|
||||
});
|
||||
const { service, calls } = makeService((args) => {
|
||||
if (args[0] === "pr" && args[1] === "list") return ok("[]");
|
||||
if (args[1]?.includes("/pulls?")) return ok(JSON.stringify([closed]));
|
||||
if (args[1]?.includes("/commits?")) {
|
||||
const page = new URL(args[1], "https://gitea.test").searchParams.get("page");
|
||||
if (page === "1")
|
||||
return {
|
||||
stdout: JSON.stringify([{ sha: "other" }]),
|
||||
stderr: 'HTTP/1.1 200 OK\nLink: <https://gitea.test/commits?page=2>; rel="next"\n',
|
||||
};
|
||||
if (page === "2") return ok(JSON.stringify([{ sha: "own" }]));
|
||||
throw new Error("HTTP 500: page past end");
|
||||
}
|
||||
throw new Error("Unexpected call");
|
||||
});
|
||||
await expect(
|
||||
service.getCurrentPullRequestStatus({
|
||||
cwd: "/repo",
|
||||
headRef: "feature",
|
||||
headSha: "own",
|
||||
}),
|
||||
).resolves.toMatchObject({ number: 8 });
|
||||
expect(calls.filter((args) => args[1]?.includes("/commits?"))).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("uses tea repository context when origin identity is unavailable", async () => {
|
||||
const headSha = "8888888888888888888888888888888888888888";
|
||||
const closedPr = currentPullRequestApi({
|
||||
@@ -2114,8 +2078,6 @@ describe("createGiteaService", () => {
|
||||
const { service, calls } = makeService(
|
||||
(args) => {
|
||||
if (args[0] === "pr" && args[1] === "list") return ok("[]");
|
||||
if (args[1]?.includes("/commits?"))
|
||||
return ok(JSON.stringify(args[1].includes("page=1") ? [{ sha: headSha }] : []));
|
||||
if (args[0] === "api" && args[1].startsWith("repos/{owner}/{repo}/pulls?")) {
|
||||
return ok(JSON.stringify([closedPr]));
|
||||
}
|
||||
@@ -2138,20 +2100,15 @@ describe("createGiteaService", () => {
|
||||
});
|
||||
|
||||
it("keeps a merged PR when its remote head advances beyond the checkout", async () => {
|
||||
const history = createPullRequestHistory();
|
||||
onTestFinished(history.dispose);
|
||||
const { cwd, workspaceCommit, pullRequestCommit } = history;
|
||||
const stale = currentPullRequestApi({
|
||||
number: 8,
|
||||
state: "closed",
|
||||
headRef: "dev",
|
||||
headSha: pullRequestCommit,
|
||||
headSha: "1111111111111111111111111111111111111111",
|
||||
merged: true,
|
||||
});
|
||||
const { service } = makeService((args) => {
|
||||
if (args[0] === "pr" && args[1] === "list") return ok("[]");
|
||||
if (args[1]?.includes("/commits?"))
|
||||
return ok(JSON.stringify(args[1].includes("page=1") ? [{ sha: workspaceCommit }] : []));
|
||||
if (args[0] === "api" && args[1].includes("/pulls?state=all")) {
|
||||
return ok(JSON.stringify([stale]));
|
||||
}
|
||||
@@ -2160,9 +2117,9 @@ describe("createGiteaService", () => {
|
||||
|
||||
await expect(
|
||||
service.getCurrentPullRequestStatus({
|
||||
cwd,
|
||||
cwd: "/repo",
|
||||
headRef: "dev",
|
||||
headSha: workspaceCommit,
|
||||
headSha: "2222222222222222222222222222222222222222",
|
||||
}),
|
||||
).resolves.toMatchObject({ number: 8, state: "merged" });
|
||||
});
|
||||
|
||||
@@ -1,7 +1,3 @@
|
||||
import {
|
||||
pullRequestContainsCommit,
|
||||
createPullRequestCommitReader,
|
||||
} from "./pull-request-contains-commit.js";
|
||||
import { z } from "zod";
|
||||
import { CHECK_TRAIT_ACTION_REQUIRED, CHECK_TRAIT_WARNING } from "@getpaseo/protocol/check-traits";
|
||||
import { mapGiteaCommitState } from "@getpaseo/protocol/gitea-status";
|
||||
@@ -167,7 +163,6 @@ const GiteaPrListItemSchema = z
|
||||
labels: z.string().optional(),
|
||||
ci: z.string().optional(),
|
||||
headSha: z.string().optional(),
|
||||
commitOids: z.array(z.string()).optional(),
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
@@ -1404,7 +1399,6 @@ function throwFirstNonTeaAuthSearchRejection(results: PromiseSettledResult<unkno
|
||||
}
|
||||
|
||||
export function createGiteaService(options: CreateGiteaServiceOptions = {}): ForgeService {
|
||||
const readRequestCommits = createPullRequestCommitReader();
|
||||
const runner = options.runner ?? runTeaCommand;
|
||||
const resolveTea = createCachedCliPathResolver(options.resolveTeaPath ?? resolveTeaPath);
|
||||
const resolveRemoteUrl = options.resolveRemoteUrl ?? defaultResolveRemoteUrl;
|
||||
@@ -1412,25 +1406,19 @@ export function createGiteaService(options: CreateGiteaServiceOptions = {}): For
|
||||
const now = options.now ?? Date.now;
|
||||
const currentPrHeadShaCache = new Map<string, { sha: string; expiresAt: number }>();
|
||||
|
||||
async function runResult(
|
||||
args: string[],
|
||||
runOptions: TeaCommandRunnerOptions,
|
||||
): Promise<TeaCommandResult> {
|
||||
async function run(args: string[], runOptions: TeaCommandRunnerOptions): Promise<string> {
|
||||
const teaPath = await resolveTea();
|
||||
if (!teaPath) {
|
||||
throw new TeaCliMissingError();
|
||||
}
|
||||
try {
|
||||
return await runner(args, runOptions);
|
||||
const result = await runner(args, runOptions);
|
||||
return result.stdout.trim();
|
||||
} catch (error) {
|
||||
throw teaCliRunner.normalizeError(error, { args: redactTeaArgs(args), cwd: runOptions.cwd });
|
||||
}
|
||||
}
|
||||
|
||||
async function run(args: string[], runOptions: TeaCommandRunnerOptions): Promise<string> {
|
||||
return (await runResult(args, runOptions)).stdout.trim();
|
||||
}
|
||||
|
||||
function runJsonParse<T>(
|
||||
args: string[],
|
||||
runOptions: TeaCommandRunnerOptions,
|
||||
@@ -1606,7 +1594,7 @@ export function createGiteaService(options: CreateGiteaServiceOptions = {}): For
|
||||
if (!match) {
|
||||
return null;
|
||||
}
|
||||
const status = { ...toCurrentPullRequestStatus(match), commitOids: match.commitOids };
|
||||
const status = toCurrentPullRequestStatus(match);
|
||||
return loadCurrentPullRequestChecks(input.cwd, match, status);
|
||||
}
|
||||
|
||||
@@ -1668,47 +1656,17 @@ export function createGiteaService(options: CreateGiteaServiceOptions = {}): For
|
||||
// owner gate.
|
||||
return input.headSha !== undefined && item.head.sha === input.headSha;
|
||||
});
|
||||
const open = candidates.find((candidate) => mapGiteaState(candidate.state) === "open");
|
||||
if (open) return currentPullRequestApiToListItem(open);
|
||||
candidates.sort(
|
||||
(left, right) =>
|
||||
Number(right.head.sha === input.headSha) - Number(left.head.sha === input.headSha),
|
||||
);
|
||||
for (const item of candidates) {
|
||||
const commitOids = await readRequestCommits(
|
||||
`${input.cwd}:${repoPath}/${item.number}@${item.head.sha}`,
|
||||
async () => {
|
||||
const result: string[] = [];
|
||||
for (let page = 1; ; page++) {
|
||||
const args = [
|
||||
"api",
|
||||
`${repoPath}/pulls/${item.number}/commits?limit=50&page=${page}&files=false&verification=false`,
|
||||
"--include",
|
||||
];
|
||||
const response = await runResult(args, { cwd: input.cwd });
|
||||
const commits = runJsonParse(
|
||||
args,
|
||||
{ cwd: input.cwd },
|
||||
response.stdout,
|
||||
z.array(z.object({ sha: z.string() })),
|
||||
);
|
||||
result.push(...commits.map((commit) => commit.sha));
|
||||
// tea writes response headers to stderr. Following Link also respects
|
||||
// server-side page caps and avoids probing beyond the final page.
|
||||
if (!/<[^>]+>;\s*rel="next"/i.test(response.stderr)) return result;
|
||||
}
|
||||
},
|
||||
);
|
||||
if (
|
||||
pullRequestContainsCommit({
|
||||
workspaceCommit: input.headSha,
|
||||
pullRequestCommits: commitOids,
|
||||
})
|
||||
) {
|
||||
return { ...currentPullRequestApiToListItem(item), commitOids };
|
||||
}
|
||||
}
|
||||
return null;
|
||||
const match =
|
||||
candidates.find((item) => mapGiteaState(item.state) === "open") ??
|
||||
candidates.find(
|
||||
(item) =>
|
||||
mapGiteaState(item.state) !== "open" &&
|
||||
input.headSha !== undefined &&
|
||||
item.head.sha === input.headSha,
|
||||
) ??
|
||||
candidates[0] ??
|
||||
null;
|
||||
return match ? currentPullRequestApiToListItem(match) : null;
|
||||
}
|
||||
|
||||
async function findOpenPullRequestForHeadRef(
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
import { createPullRequestCommitReader } from "./pull-request-contains-commit.js";
|
||||
import { createPullRequestHistory } from "../test-utils/pull-request-history.js";
|
||||
import { onTestFinished } from "vitest";
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
@@ -221,21 +218,6 @@ function currentPullRequestJson(overrides: Record<string, unknown> = {}): string
|
||||
});
|
||||
}
|
||||
|
||||
function commitPageJson(commitOids: string[]): Record<string, unknown> {
|
||||
return {
|
||||
pullRequest: {
|
||||
commits: {
|
||||
nodes: commitOids.map((oid) => ({ commit: { oid } })),
|
||||
pageInfo: { hasPreviousPage: false, startCursor: null },
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function directCommitsJson(commitOids: string[]): string {
|
||||
return JSON.stringify({ data: { repository: commitPageJson(commitOids) } });
|
||||
}
|
||||
|
||||
function currentPullRequestGithubFactsJson(overrides: Record<string, unknown> = {}): string {
|
||||
return JSON.stringify({
|
||||
data: {
|
||||
@@ -1129,252 +1111,6 @@ describe("ForgeService", () => {
|
||||
expect(currentPullRequestStatusCalls(runner.calls)).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("rejects failed commit reads and retries without retaining the failure", async () => {
|
||||
const read = createPullRequestCommitReader();
|
||||
await expect(
|
||||
read("bad@head", async () => {
|
||||
throw new Error("offline");
|
||||
}),
|
||||
).rejects.toThrow("offline");
|
||||
await expect(read("good@head", async () => ["own-commit"])).resolves.toEqual(["own-commit"]);
|
||||
await expect(read("bad@head", async () => ["recovered"])).resolves.toEqual(["recovered"]);
|
||||
await expect(
|
||||
read("good@head", async () => {
|
||||
throw new Error("must use cache");
|
||||
}),
|
||||
).resolves.toEqual(["own-commit"]);
|
||||
});
|
||||
|
||||
it.each(["transport", "alias"])(
|
||||
"preserves a failed workspace even with an older match and isolates a complete open workspace (%s)",
|
||||
async (failure) => {
|
||||
const runner = createScriptedRunner([
|
||||
batchPollStatusJson({
|
||||
t0: batchPollRepositoryJson([
|
||||
batchPollPrNodeJson({
|
||||
number: 60,
|
||||
headRefName: "a",
|
||||
}),
|
||||
batchPollPrNodeJson({
|
||||
number: 50,
|
||||
headRefName: "a",
|
||||
}),
|
||||
]),
|
||||
t1: batchPollRepositoryJson([
|
||||
batchPollPrNodeJson({ headRefName: "b", state: "OPEN", mergedAt: null }),
|
||||
]),
|
||||
}),
|
||||
batchPollStatusJson({
|
||||
t0: {
|
||||
pullRequest: {
|
||||
commits: { nodes: [], pageInfo: { hasPreviousPage: true, startCursor: "next" } },
|
||||
},
|
||||
},
|
||||
t1: commitPageJson(["own-a"]),
|
||||
}),
|
||||
failure === "transport"
|
||||
? { error: new Error("HTTP 502") }
|
||||
: batchPollStatusJson({ t0: null }),
|
||||
batchPollStatusJson({ t0: batchPollChecksAliasJson([]) }),
|
||||
]);
|
||||
const service = createGitHubService({
|
||||
runner: runner.runner,
|
||||
resolveGhPath: async () => "/usr/bin/gh",
|
||||
resolveRepoHost: async () => null,
|
||||
resolveRepoSlug: async () => "acme/widgets",
|
||||
});
|
||||
const errorsA: unknown[] = [],
|
||||
errorsB: unknown[] = [];
|
||||
const statusesA: Array<CurrentPullRequestStatus | null> = [];
|
||||
const statusesB: Array<CurrentPullRequestStatus | null> = [];
|
||||
service.retainCurrentPullRequestStatusPoll?.({
|
||||
cwd: "/a",
|
||||
headRef: "a",
|
||||
headSha: "own-a",
|
||||
onError: (error) => errorsA.push(error),
|
||||
onStatus: (status) => statusesA.push(status),
|
||||
});
|
||||
service.retainCurrentPullRequestStatusPoll?.({
|
||||
cwd: "/b",
|
||||
headRef: "b",
|
||||
headSha: "own-b",
|
||||
onError: (error) => errorsB.push(error),
|
||||
onStatus: (status) => statusesB.push(status),
|
||||
});
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
await flushMicrotasks();
|
||||
service.dispose?.();
|
||||
expect(errorsA).toHaveLength(1);
|
||||
expect(statusesA).toEqual([]);
|
||||
expect(errorsB).toEqual([]);
|
||||
expect(statusesB).toEqual([expect.objectContaining({ state: "open" })]);
|
||||
},
|
||||
);
|
||||
|
||||
it.each(["cached", "failed-lower", "paged-lower", "pending-higher"])(
|
||||
"ignores a lower-ranked unresolved PR after the preferred match (%s)",
|
||||
async (scenario) => {
|
||||
let now = 0;
|
||||
const cold = true;
|
||||
const pendingHigher = scenario === "pending-higher";
|
||||
const own = batchPollPrNodeJson({
|
||||
number: 50,
|
||||
headRefName: "a",
|
||||
});
|
||||
const older = batchPollPrNodeJson({ number: 42, headRefName: "a" });
|
||||
const runner = createScriptedRunner([
|
||||
batchPollStatusJson({ t0: batchPollRepositoryJson([older, own]) }),
|
||||
...(cold
|
||||
? [
|
||||
batchPollStatusJson({
|
||||
t0: {
|
||||
pullRequest: {
|
||||
commits: {
|
||||
nodes: [{ commit: { oid: pendingHigher ? "another" : "own-a" } }],
|
||||
pageInfo: {
|
||||
hasPreviousPage: pendingHigher,
|
||||
startCursor: pendingHigher ? "next" : null,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
t1:
|
||||
scenario === "failed-lower" || pendingHigher
|
||||
? null
|
||||
: {
|
||||
pullRequest: {
|
||||
commits: {
|
||||
nodes: [{ commit: { oid: "other" } }],
|
||||
pageInfo: { hasPreviousPage: true, startCursor: "older-page" },
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
]
|
||||
: []),
|
||||
...(pendingHigher
|
||||
? [
|
||||
batchPollStatusJson({
|
||||
t0: {
|
||||
pullRequest: {
|
||||
commits: {
|
||||
nodes: [{ commit: { oid: "own-a" } }],
|
||||
pageInfo: { hasPreviousPage: false, startCursor: null },
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
]
|
||||
: []),
|
||||
batchPollStatusJson({ t0: batchPollChecksAliasJson([]) }),
|
||||
...(scenario === "cached"
|
||||
? [batchPollStatusJson({ t0: batchPollRepositoryJson([older, own]) })]
|
||||
: []),
|
||||
]);
|
||||
const service = createGitHubService({
|
||||
now: () => now,
|
||||
runner: runner.runner,
|
||||
resolveGhPath: async () => "/usr/bin/gh",
|
||||
resolveRepoHost: async () => null,
|
||||
resolveRepoSlug: async () => "acme/widgets",
|
||||
});
|
||||
const statuses: Array<CurrentPullRequestStatus | null> = [],
|
||||
errors: unknown[] = [];
|
||||
service.retainCurrentPullRequestStatusPoll?.({
|
||||
cwd: "/a",
|
||||
headRef: "a",
|
||||
headSha: "own-a",
|
||||
onStatus: (status) => statuses.push(status),
|
||||
onError: (error) => errors.push(error),
|
||||
});
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
await flushMicrotasks();
|
||||
if (scenario === "cached") {
|
||||
now = EXPECTED_GITHUB_SLOW_POLL_MS;
|
||||
await vi.advanceTimersByTimeAsync(EXPECTED_GITHUB_SLOW_POLL_MS);
|
||||
await flushMicrotasks();
|
||||
}
|
||||
service.dispose?.();
|
||||
expect(errors).toEqual([]);
|
||||
expect(statuses).toHaveLength(scenario === "cached" ? 2 : 1);
|
||||
expect(statuses.every((status) => status?.number === 50)).toBe(true);
|
||||
expect(
|
||||
runner.calls.filter(({ args }) => args.join(" ").includes("PaseoBatchCommitPages")),
|
||||
).toHaveLength(Number(cold) + Number(pendingHigher));
|
||||
},
|
||||
);
|
||||
|
||||
it.each([false, true])(
|
||||
"filters terminal PRs in a batched poll (pagination: %s)",
|
||||
async (paginate) => {
|
||||
vi.useRealTimers();
|
||||
const history = createPullRequestHistory();
|
||||
onTestFinished(history.dispose);
|
||||
const { cwd, workspaceCommit, pullRequestCommit } = history;
|
||||
const runner = createScriptedRunner([
|
||||
batchPollStatusJson({
|
||||
t0: batchPollRepositoryJson([
|
||||
batchPollPrNodeJson({
|
||||
headRefName: "feature",
|
||||
headRefOid: pullRequestCommit,
|
||||
}),
|
||||
]),
|
||||
}),
|
||||
batchPollStatusJson({
|
||||
t0: {
|
||||
pullRequest: {
|
||||
commits: {
|
||||
nodes: [{ commit: { oid: paginate ? "other" : workspaceCommit } }],
|
||||
pageInfo: { hasPreviousPage: paginate, startCursor: "cursor-1" },
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
...(paginate
|
||||
? [
|
||||
batchPollStatusJson({
|
||||
t0: {
|
||||
pullRequest: {
|
||||
commits: {
|
||||
nodes: [{ commit: { oid: workspaceCommit } }],
|
||||
pageInfo: { hasPreviousPage: false, startCursor: "cursor-2" },
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
]
|
||||
: []),
|
||||
batchPollStatusJson({ t0: batchPollChecksAliasJson([]) }),
|
||||
]);
|
||||
const service = createGitHubService({
|
||||
runner: runner.runner,
|
||||
resolveGhPath: async () => "/usr/bin/gh",
|
||||
resolveRepoHost: async () => null,
|
||||
resolveRepoSlug: async () => "acme/widgets",
|
||||
});
|
||||
onTestFinished(() => service.dispose?.());
|
||||
const statuses: Array<CurrentPullRequestStatus | null> = [];
|
||||
const subscription = service.retainCurrentPullRequestStatusPoll?.({
|
||||
cwd,
|
||||
headRef: "feature",
|
||||
headSha: workspaceCommit,
|
||||
onStatus: (status) => statuses.push(status),
|
||||
});
|
||||
onTestFinished(() => subscription?.unsubscribe());
|
||||
await vi.waitFor(() => expect(statuses).toHaveLength(1));
|
||||
expect(statuses[0]).toMatchObject({ state: "merged", headSha: pullRequestCommit });
|
||||
expect(runner.calls).toHaveLength(paginate ? 4 : 3);
|
||||
expect(runner.calls[0]?.args[3]).not.toContain("commits(");
|
||||
expect(runner.calls[1]?.args[3]).toContain("commits(last:100");
|
||||
expect(
|
||||
runner.calls.every((call) => call.args[0] === "api" && call.args[1] === "graphql"),
|
||||
).toBe(true);
|
||||
expect(history.git(["rev-parse", "HEAD"])).toBe(workspaceCommit);
|
||||
expect(history.git(["rev-parse", "@{upstream}"])).toBe(workspaceCommit);
|
||||
expect(() => history.git(["rev-parse", "--verify", "FETCH_HEAD"])).toThrow();
|
||||
},
|
||||
);
|
||||
|
||||
it("batches PR status polls across workspaces into one GraphQL request", async () => {
|
||||
let now = 0;
|
||||
const runner = createScriptedRunner([
|
||||
@@ -1396,7 +1132,6 @@ describe("ForgeService", () => {
|
||||
}),
|
||||
]),
|
||||
}),
|
||||
batchPollStatusJson({ t0: commitPageJson(["oid-a"]), t1: commitPageJson(["oid-b"]) }),
|
||||
batchPollStatusJson({
|
||||
t0: batchPollChecksAliasJson([
|
||||
{ __typename: "StatusContext", context: "ci", state: "SUCCESS" },
|
||||
@@ -1452,7 +1187,7 @@ describe("ForgeService", () => {
|
||||
await flushMicrotasks();
|
||||
|
||||
expect(currentPullRequestStatusCalls(runner.calls)).toHaveLength(0);
|
||||
expect(runner.calls).toHaveLength(3);
|
||||
expect(runner.calls).toHaveLength(2);
|
||||
expect(runner.calls[0]?.args.slice(0, 2)).toEqual(["api", "graphql"]);
|
||||
expect(runner.calls[0]?.args[3]).toContain('t0: repository(owner: "acme", name: "widgets")');
|
||||
expect(runner.calls[0]?.args[3]).toContain('t1: repository(owner: "acme", name: "gadgets")');
|
||||
@@ -1479,7 +1214,7 @@ describe("ForgeService", () => {
|
||||
await vi.advanceTimersByTimeAsync(EXPECTED_GITHUB_SLOW_POLL_MS);
|
||||
await flushMicrotasks();
|
||||
|
||||
expect(runner.calls).toHaveLength(4);
|
||||
expect(runner.calls).toHaveLength(3);
|
||||
expect(statusesA).toHaveLength(2);
|
||||
expect(statusesA[1]).toEqual(expect.objectContaining({ number: 41, checksStatus: "success" }));
|
||||
|
||||
@@ -1513,7 +1248,6 @@ describe("ForgeService", () => {
|
||||
}),
|
||||
]),
|
||||
}),
|
||||
batchPollStatusJson({ t0: commitPageJson(["oid-a"]), t1: commitPageJson(["oid-b"]) }),
|
||||
batchPollStatusJson({
|
||||
t0: batchPollChecksAliasJson([]),
|
||||
t1: batchPollChecksAliasJson([]),
|
||||
@@ -1557,7 +1291,7 @@ describe("ForgeService", () => {
|
||||
await flushMicrotasks();
|
||||
|
||||
expect(currentPullRequestStatusCalls(runner.calls)).toHaveLength(0);
|
||||
expect(runner.calls).toHaveLength(3);
|
||||
expect(runner.calls).toHaveLength(2);
|
||||
expect(runner.calls[0]?.args.slice(0, 2)).toEqual(["api", "graphql"]);
|
||||
expect(runner.calls[0]?.args[3]).toContain('t0: repository(owner: "acme", name: "widgets")');
|
||||
expect(runner.calls[0]?.args[3]).toContain('t1: repository(owner: "acme", name: "gadgets")');
|
||||
@@ -1757,7 +1491,6 @@ describe("ForgeService", () => {
|
||||
t0: batchPollRepositoryJson([], { isFork: true, parent }),
|
||||
}),
|
||||
batchPollStatusJson({ t0: batchPollRepositoryJson([forkPr]) }),
|
||||
batchPollStatusJson({ t0: commitPageJson(["oid-a"]) }),
|
||||
batchPollStatusJson({
|
||||
t0: batchPollChecksAliasJson([
|
||||
{ __typename: "StatusContext", context: "ci", state: "SUCCESS" },
|
||||
@@ -1799,7 +1532,7 @@ describe("ForgeService", () => {
|
||||
await vi.advanceTimersByTimeAsync(EXPECTED_GITHUB_SLOW_POLL_MS);
|
||||
await flushMicrotasks();
|
||||
|
||||
expect(runner.calls[4]?.args[3]).toContain(
|
||||
expect(runner.calls[3]?.args[3]).toContain(
|
||||
't0: repository(owner: "upstream", name: "widgets")',
|
||||
);
|
||||
|
||||
@@ -1878,83 +1611,6 @@ describe("ForgeService", () => {
|
||||
service.dispose?.();
|
||||
});
|
||||
|
||||
it.each(["reserve", "error"])(
|
||||
"preserves known checks when commit paging pauses the host (%s)",
|
||||
async (failure) => {
|
||||
let now = 0;
|
||||
const open = batchPollRepositoryJson([
|
||||
batchPollPrNodeJson({ state: "OPEN", mergedAt: null, headRefName: "open" }),
|
||||
]);
|
||||
const runner = createScriptedRunner([
|
||||
batchPollStatusJson({ t0: open }),
|
||||
batchPollStatusJson({
|
||||
t0: batchPollChecksAliasJson([
|
||||
{ __typename: "StatusContext", context: "ci", state: "FAILURE" },
|
||||
]),
|
||||
}),
|
||||
batchPollStatusJson({
|
||||
t0: open,
|
||||
t1: batchPollRepositoryJson([batchPollPrNodeJson()]),
|
||||
}),
|
||||
...(failure === "reserve"
|
||||
? [
|
||||
batchPollStatusWithRateLimitJson({
|
||||
aliases: {},
|
||||
limit: 5000,
|
||||
remaining: 0,
|
||||
resetAt: new Date(3600000).toISOString(),
|
||||
}),
|
||||
]
|
||||
: [
|
||||
{
|
||||
error: Object.assign(new Error("gh exited 1"), {
|
||||
code: 1,
|
||||
stderr: "GraphQL: API rate limit already exceeded for user ID 123",
|
||||
}),
|
||||
},
|
||||
JSON.stringify({ resources: { graphql: { remaining: 0, reset: 3600 } } }),
|
||||
]),
|
||||
]);
|
||||
const service = createGitHubService({
|
||||
runner: runner.runner,
|
||||
ttlMs: 3600000,
|
||||
resolveGhPath: async () => "/usr/bin/gh",
|
||||
resolveRepoHost: async () => null,
|
||||
resolveRepoSlug: async () => "acme/widgets",
|
||||
now: () => now,
|
||||
});
|
||||
const statuses: Array<CurrentPullRequestStatus | null> = [];
|
||||
const errors: unknown[] = [],
|
||||
terminalErrors: unknown[] = [];
|
||||
service.retainCurrentPullRequestStatusPoll?.({
|
||||
cwd: "/open",
|
||||
headRef: "open",
|
||||
onStatus: (status) => statuses.push(status),
|
||||
onError: (error) => errors.push(error),
|
||||
});
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
await flushMicrotasks();
|
||||
expect(statuses).toEqual([expect.objectContaining({ checksStatus: "failure" })]);
|
||||
service.retainCurrentPullRequestStatusPoll?.({
|
||||
cwd: "/terminal",
|
||||
headRef: "feat-a",
|
||||
headSha: "oid-42",
|
||||
onError: (error) => terminalErrors.push(error),
|
||||
});
|
||||
now = EXPECTED_GITHUB_SLOW_POLL_MS;
|
||||
await vi.advanceTimersByTimeAsync(EXPECTED_GITHUB_SLOW_POLL_MS);
|
||||
await flushMicrotasks();
|
||||
expect(statuses).toEqual([expect.objectContaining({ checksStatus: "failure" })]);
|
||||
expect(errors).toHaveLength(1);
|
||||
expect(terminalErrors).toHaveLength(1);
|
||||
await expect(
|
||||
service.getCurrentPullRequestStatus({ cwd: "/open", headRef: "open" }),
|
||||
).resolves.toMatchObject({ checksStatus: "failure" });
|
||||
expect(runner.calls).toHaveLength(failure === "reserve" ? 4 : 5);
|
||||
service.dispose?.();
|
||||
},
|
||||
);
|
||||
|
||||
it("pauses a host until reset when a batch reaches the GraphQL reserve", async () => {
|
||||
let now = 0;
|
||||
const resetAt = new Date(EXPECTED_GITHUB_ERROR_BACKOFF_CAP_MS).toISOString();
|
||||
@@ -2061,7 +1717,6 @@ describe("ForgeService", () => {
|
||||
});
|
||||
const runner = createScriptedRunner([
|
||||
batchPollStatusJson({ t0: batchPollRepositoryJson([closedNode]) }),
|
||||
batchPollStatusJson({ t0: commitPageJson(["oid-closed"]) }),
|
||||
batchPollStatusJson({
|
||||
t0: batchPollChecksAliasJson([
|
||||
{ __typename: "StatusContext", context: "ci", state: "PENDING" },
|
||||
@@ -2093,7 +1748,7 @@ describe("ForgeService", () => {
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
await flushMicrotasks();
|
||||
|
||||
expect(runner.calls).toHaveLength(3);
|
||||
expect(runner.calls).toHaveLength(2);
|
||||
expect(statuses).toEqual([expect.objectContaining({ number: 9, checksStatus: "pending" })]);
|
||||
|
||||
// Pending checks are never frozen, so the next cycle re-runs the checks
|
||||
@@ -2102,7 +1757,7 @@ describe("ForgeService", () => {
|
||||
await vi.advanceTimersByTimeAsync(EXPECTED_GITHUB_FAST_POLL_MS);
|
||||
await flushMicrotasks();
|
||||
|
||||
expect(runner.calls).toHaveLength(5);
|
||||
expect(runner.calls).toHaveLength(4);
|
||||
expect(statuses[1]).toEqual(expect.objectContaining({ number: 9, checksStatus: "success" }));
|
||||
|
||||
subscription?.unsubscribe();
|
||||
@@ -2215,7 +1870,6 @@ describe("ForgeService", () => {
|
||||
stderr: "GraphQL: Could not resolve to a Repository",
|
||||
}),
|
||||
},
|
||||
batchPollStatusJson({ t0: commitPageJson(["oid-a"]) }),
|
||||
batchPollStatusJson({
|
||||
t0: batchPollChecksAliasJson([
|
||||
{ __typename: "StatusContext", context: "ci", state: "SUCCESS" },
|
||||
@@ -2248,7 +1902,7 @@ describe("ForgeService", () => {
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
await flushMicrotasks();
|
||||
|
||||
expect(runner.calls).toHaveLength(3);
|
||||
expect(runner.calls).toHaveLength(2);
|
||||
expect(statuses).toEqual([
|
||||
expect.objectContaining({ number: 41, state: "merged", checksStatus: "success" }),
|
||||
]);
|
||||
@@ -3484,42 +3138,6 @@ describe("ForgeService", () => {
|
||||
expect(details.truncated).toBe(true);
|
||||
});
|
||||
|
||||
it("chooses an open PR before reading an older terminal candidate's commits", async () => {
|
||||
const terminal = JSON.parse(
|
||||
currentPullRequestJson({
|
||||
number: 1,
|
||||
state: "MERGED",
|
||||
mergedAt: "2026-01-01T00:00:00Z",
|
||||
headRefName: "feature",
|
||||
headRepositoryOwner: { login: "acme" },
|
||||
}),
|
||||
);
|
||||
const open = JSON.parse(
|
||||
currentPullRequestJson({
|
||||
number: 2,
|
||||
headRefName: "feature",
|
||||
headRepositoryOwner: { login: "acme" },
|
||||
}),
|
||||
);
|
||||
const runner = createScriptedRunner([
|
||||
JSON.stringify(terminal),
|
||||
JSON.stringify({ owner: { login: "acme" }, name: "repo", parent: null }),
|
||||
JSON.stringify([open, terminal]),
|
||||
]);
|
||||
const service = createGitHubService({
|
||||
runner: runner.runner,
|
||||
resolveGhPath: async () => "/usr/bin/gh",
|
||||
});
|
||||
await expect(
|
||||
service.getCurrentPullRequestStatus({
|
||||
cwd: "/repo",
|
||||
headRef: "feature",
|
||||
headSha: "own",
|
||||
}),
|
||||
).resolves.toMatchObject({ number: 2, state: "open" });
|
||||
expect(runner.calls.some(({ args }) => args.join(" ").includes("commits(last:"))).toBe(false);
|
||||
});
|
||||
|
||||
it("retries current PR view without statusCheckRollup when token permissions are insufficient", async () => {
|
||||
const runner = createScriptedRunner([
|
||||
{
|
||||
@@ -3662,16 +3280,12 @@ describe("ForgeService", () => {
|
||||
|
||||
it("keeps a merged PR when headRefOid matches the checkout HEAD", async () => {
|
||||
const headSha = "2222222222222222222222222222222222222222";
|
||||
const candidate = currentPullRequestJson({
|
||||
state: "MERGED",
|
||||
mergedAt: "2026-07-17T12:00:00Z",
|
||||
headRefOid: headSha,
|
||||
headRepositoryOwner: { login: "forkOwner" },
|
||||
});
|
||||
const runner = createScriptedRunner([
|
||||
candidate,
|
||||
JSON.stringify([JSON.parse(candidate)]),
|
||||
directCommitsJson([headSha]),
|
||||
const runner = createRunner([
|
||||
currentPullRequestJson({
|
||||
state: "MERGED",
|
||||
mergedAt: "2026-07-17T12:00:00Z",
|
||||
headRefOid: headSha,
|
||||
}),
|
||||
]);
|
||||
const service = createGitHubService({
|
||||
runner: runner.runner,
|
||||
@@ -3682,7 +3296,6 @@ describe("ForgeService", () => {
|
||||
cwd: "/repo",
|
||||
headRef: "feature/fork",
|
||||
headSha,
|
||||
headRepositoryOwner: "forkOwner",
|
||||
});
|
||||
|
||||
expect(status?.number).toBe(42);
|
||||
@@ -3690,20 +3303,16 @@ describe("ForgeService", () => {
|
||||
});
|
||||
|
||||
it("keeps a merged PR when its remote head advances beyond the checkout", async () => {
|
||||
const history = createPullRequestHistory();
|
||||
onTestFinished(history.dispose);
|
||||
const { cwd, workspaceCommit, pullRequestCommit } = history;
|
||||
const stale = currentPullRequestJson({
|
||||
headRepositoryOwner: { login: "parentOwner" },
|
||||
state: "MERGED",
|
||||
mergedAt: "2026-07-17T12:00:00Z",
|
||||
headRefOid: pullRequestCommit,
|
||||
headRefOid: "1111111111111111111111111111111111111111",
|
||||
});
|
||||
const runner = createScriptedRunner([
|
||||
stale,
|
||||
JSON.stringify({ owner: { login: "parentOwner" }, name: "parentRepo", parent: null }),
|
||||
JSON.stringify([JSON.parse(stale)]),
|
||||
directCommitsJson([workspaceCommit, pullRequestCommit]),
|
||||
]);
|
||||
const service = createGitHubService({
|
||||
runner: runner.runner,
|
||||
@@ -3712,9 +3321,9 @@ describe("ForgeService", () => {
|
||||
|
||||
await expect(
|
||||
service.getCurrentPullRequestStatus({
|
||||
cwd,
|
||||
cwd: "/repo",
|
||||
headRef: "feature/fork",
|
||||
headSha: workspaceCommit,
|
||||
headSha: "2222222222222222222222222222222222222222",
|
||||
}),
|
||||
).resolves.toMatchObject({ state: "merged" });
|
||||
expect(runner.calls.some((call) => call.args[0] === "pr" && call.args[1] === "list")).toBe(
|
||||
@@ -3722,117 +3331,7 @@ describe("ForgeService", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it.each(["CLOSED", "MERGED"])(
|
||||
"hides a %s PR when a reused branch is ahead of its head",
|
||||
async (state) => {
|
||||
const history = createPullRequestHistory();
|
||||
onTestFinished(history.dispose);
|
||||
const candidate = JSON.parse(
|
||||
currentPullRequestJson({
|
||||
state,
|
||||
mergedAt: state === "MERGED" ? "2026-07-17T12:00:00Z" : null,
|
||||
headRefOid: history.workspaceCommit,
|
||||
headRepositoryOwner: { login: "forkOwner" },
|
||||
}),
|
||||
);
|
||||
const runner = createScriptedRunner([
|
||||
JSON.stringify(candidate),
|
||||
JSON.stringify([candidate]),
|
||||
directCommitsJson([history.workspaceCommit]),
|
||||
]);
|
||||
const service = createGitHubService({
|
||||
runner: runner.runner,
|
||||
resolveGhPath: async () => "/usr/bin/gh",
|
||||
});
|
||||
await expect(
|
||||
service.getCurrentPullRequestStatus({
|
||||
cwd: history.remote,
|
||||
headRef: "feature/fork",
|
||||
headRepositoryOwner: "forkOwner",
|
||||
headSha: history.pullRequestCommit,
|
||||
}),
|
||||
).resolves.toBeNull();
|
||||
},
|
||||
);
|
||||
|
||||
it.each(["CLOSED", "MERGED"])(
|
||||
"hides a %s PR when the workspace only shares its inherited base",
|
||||
async (state) => {
|
||||
const history = createPullRequestHistory();
|
||||
onTestFinished(history.dispose);
|
||||
const candidate = JSON.parse(
|
||||
currentPullRequestJson({
|
||||
state,
|
||||
headRefOid: history.pullRequestCommit,
|
||||
headRepositoryOwner: { login: "forkOwner" },
|
||||
}),
|
||||
);
|
||||
const runner = createScriptedRunner([
|
||||
JSON.stringify(candidate),
|
||||
JSON.stringify([candidate]),
|
||||
directCommitsJson([history.pullRequestCommit]),
|
||||
]);
|
||||
const service = createGitHubService({
|
||||
runner: runner.runner,
|
||||
resolveGhPath: async () => "/usr/bin/gh",
|
||||
});
|
||||
await expect(
|
||||
service.getCurrentPullRequestStatus({
|
||||
cwd: history.cwd,
|
||||
headRef: "feature/fork",
|
||||
headRepositoryOwner: "forkOwner",
|
||||
headSha: history.workspaceCommit,
|
||||
}),
|
||||
).resolves.toBeNull();
|
||||
},
|
||||
);
|
||||
|
||||
it("reads only commit IDs for a cold terminal lookup and reuses the list", async () => {
|
||||
const candidate = currentPullRequestJson({
|
||||
number: 987,
|
||||
state: "MERGED",
|
||||
headRefOid: "cold-own-head",
|
||||
|
||||
headRepositoryOwner: { login: "forkOwner" },
|
||||
});
|
||||
const runner = createScriptedRunner([
|
||||
candidate,
|
||||
JSON.stringify([JSON.parse(candidate)]),
|
||||
JSON.stringify({
|
||||
data: {
|
||||
repository: {
|
||||
pullRequest: {
|
||||
commits: {
|
||||
nodes: [{ commit: { oid: "cold-own-head" } }],
|
||||
pageInfo: { hasPreviousPage: false, startCursor: null },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
]);
|
||||
const service = createGitHubService({
|
||||
runner: runner.runner,
|
||||
resolveGhPath: async () => "/usr/bin/gh",
|
||||
});
|
||||
await expect(
|
||||
service.getCurrentPullRequestStatus({
|
||||
cwd: "/repo",
|
||||
headRef: "feature/fork",
|
||||
headRepositoryOwner: "forkOwner",
|
||||
headSha: "cold-own-head",
|
||||
}),
|
||||
).resolves.toMatchObject({ number: 987 });
|
||||
expect(runner.calls).toHaveLength(4);
|
||||
expect(runner.calls.filter((call) => call.args[3]?.includes("commits(last:100"))).toHaveLength(
|
||||
1,
|
||||
);
|
||||
expect(runner.calls[0]?.args.at(-1)).not.toContain("commits");
|
||||
expect(runner.calls[2]?.args[3]).toContain("commits(last:100");
|
||||
expect(runner.calls[2]?.args[3]).not.toContain("authors");
|
||||
});
|
||||
|
||||
it("rejects an unrelated terminal PR on a reused branch", async () => {
|
||||
it("prefers an exact terminal head and otherwise the most recently updated terminal PR", async () => {
|
||||
const owner = { login: "forkOwner" };
|
||||
const terminal = ({
|
||||
number,
|
||||
@@ -3869,15 +3368,9 @@ describe("ForgeService", () => {
|
||||
});
|
||||
for (const [headSha, expected] of [
|
||||
["old", 41],
|
||||
["other", undefined],
|
||||
["other", 42],
|
||||
] as const) {
|
||||
const runner = createScriptedRunner([
|
||||
JSON.stringify(older),
|
||||
JSON.stringify([older, newer]),
|
||||
...(headSha === "old"
|
||||
? [directCommitsJson(["old"])]
|
||||
: [directCommitsJson(["old"]), directCommitsJson(["new"])]),
|
||||
]);
|
||||
const runner = createScriptedRunner([JSON.stringify(older), JSON.stringify([older, newer])]);
|
||||
const service = createGitHubService({
|
||||
runner: runner.runner,
|
||||
resolveGhPath: async () => "/usr/bin/gh",
|
||||
@@ -3917,7 +3410,6 @@ describe("ForgeService", () => {
|
||||
const runner = createScriptedRunner([
|
||||
JSON.stringify(closedDraft),
|
||||
JSON.stringify([closedDraft, merged]),
|
||||
directCommitsJson(["exact"]),
|
||||
]);
|
||||
const service = createGitHubService({
|
||||
runner: runner.runner,
|
||||
@@ -3990,7 +3482,6 @@ describe("ForgeService", () => {
|
||||
parent: { owner: { login: "acme" }, name: "app" },
|
||||
}),
|
||||
"[]",
|
||||
directCommitsJson(["checkout-head"]),
|
||||
]);
|
||||
const service = createGitHubService({
|
||||
runner: runner.runner,
|
||||
@@ -4019,7 +3510,7 @@ describe("ForgeService", () => {
|
||||
for (const [state, headSha, updatedAt, expected] of [
|
||||
["OPEN", "other", "2026-07-16T12:00:00Z", 8],
|
||||
["CLOSED", "other", "2026-07-18T12:00:00Z", 7],
|
||||
["CLOSED", "other", "2026-07-18T12:00:00Z", undefined],
|
||||
["CLOSED", "other", "2026-07-18T12:00:00Z", 8],
|
||||
] as const) {
|
||||
const parent = {
|
||||
...local,
|
||||
@@ -4030,11 +3521,6 @@ describe("ForgeService", () => {
|
||||
headRefOid: headSha,
|
||||
updatedAt,
|
||||
};
|
||||
const commitResponses: string[] = [];
|
||||
if (state !== "OPEN") {
|
||||
commitResponses.push(directCommitsJson(["local-head"]));
|
||||
if (expected !== 7) commitResponses.push(directCommitsJson(["other"]));
|
||||
}
|
||||
const runner = createScriptedRunner([
|
||||
JSON.stringify(local),
|
||||
JSON.stringify({
|
||||
@@ -4044,7 +3530,6 @@ describe("ForgeService", () => {
|
||||
}),
|
||||
JSON.stringify([{ number: 8 }]),
|
||||
JSON.stringify(parent),
|
||||
...commitResponses,
|
||||
]);
|
||||
const service = createGitHubService({
|
||||
runner: runner.runner,
|
||||
@@ -4141,8 +3626,6 @@ describe("ForgeService", () => {
|
||||
stderr: "",
|
||||
};
|
||||
}
|
||||
if (args[0] === "api" && args[1] === "graphql")
|
||||
return { stdout: directCommitsJson([checkoutSha]), stderr: "" };
|
||||
if (args[0] === "api") {
|
||||
// Newest first, and the checkout is sitting on the oldest attempt.
|
||||
return {
|
||||
|
||||
@@ -1,7 +1,3 @@
|
||||
import {
|
||||
pullRequestContainsCommit,
|
||||
createPullRequestCommitReader,
|
||||
} from "./pull-request-contains-commit.js";
|
||||
import { z } from "zod";
|
||||
import {
|
||||
isGitHubHost,
|
||||
@@ -637,22 +633,6 @@ query PullRequestTimeline($owner: String!, $name: String!, $number: Int!) {
|
||||
}
|
||||
}`;
|
||||
|
||||
const PullRequestCommitPageSchema = z.object({
|
||||
nodes: z.array(z.object({ commit: z.object({ oid: z.string() }) })),
|
||||
pageInfo: z
|
||||
.object({ hasPreviousPage: z.boolean(), startCursor: z.string().nullable() })
|
||||
.refine(
|
||||
(page) => !page.hasPreviousPage || !!page.startCursor,
|
||||
"A previous commit page requires a cursor",
|
||||
),
|
||||
});
|
||||
|
||||
type PullRequestMembership =
|
||||
| { kind: "unknown" }
|
||||
| { kind: "partial"; commitOids: string[]; cursor: string }
|
||||
| { kind: "complete"; commitOids: string[] }
|
||||
| { kind: "failed"; error: unknown };
|
||||
|
||||
const BatchPollPrNodeSchema = z.object({
|
||||
number: z.number(),
|
||||
url: z.string().catch(""),
|
||||
@@ -1145,7 +1125,6 @@ interface GitHubBatchDistribution {
|
||||
}
|
||||
|
||||
interface ResolvedPullRequestCandidate {
|
||||
membership: PullRequestMembership;
|
||||
status: CurrentPullRequestStatus;
|
||||
headSha?: string;
|
||||
headRepositoryOwner?: string;
|
||||
@@ -1194,9 +1173,6 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G
|
||||
// Rollup nodes for merged/closed PRs keyed by repo#number@headOid: their
|
||||
// checks can no longer change, so each is fetched at most once per daemon run.
|
||||
const frozenPullRequestChecksCache = new Map<string, unknown[]>();
|
||||
const readCommits = createPullRequestCommitReader();
|
||||
const terminalCommitPages = new Map<string, PullRequestMembership>();
|
||||
const batchMembership = new WeakMap<BatchPollPrNode, PullRequestMembership>();
|
||||
const pollRepositoryRedirects = new Map<
|
||||
string,
|
||||
{ owner: string; name: string; headRepositoryOwner: string }
|
||||
@@ -1685,32 +1661,15 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G
|
||||
return;
|
||||
}
|
||||
|
||||
const repositories = new Map<GitHubBatchPollEntry, BatchPollRepository>();
|
||||
for (const [index, entry] of addressedEntries.entries()) {
|
||||
const parsed = BatchPollRepositorySchema.safeParse(response.aliases[batchAlias(index)]);
|
||||
if (parsed.success) repositories.set(entry, parsed.data);
|
||||
}
|
||||
const failedCommitEntries = await loadBatchCommitPages(addressedEntries, repositories);
|
||||
const distribution = distributeGitHubPollBatch({
|
||||
entries: addressedEntries,
|
||||
repositories,
|
||||
aliases: response.aliases,
|
||||
args,
|
||||
startedAt,
|
||||
failedCommitEntries,
|
||||
});
|
||||
if ((pollPausedUntilByHost.get(firstEntry.host) ?? 0) > deps.now()) {
|
||||
const error = new Error(
|
||||
"GitHub GraphQL polling is paused; pull request checks could not be refreshed",
|
||||
);
|
||||
for (const item of distribution.pendingChecks) {
|
||||
updatePollTargetAfterError(item.entry.target, error);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (distribution.pendingChecks.length > 0) {
|
||||
await loadBatchPullRequestChecks(distribution.pendingChecks, startedAt);
|
||||
}
|
||||
if ((pollPausedUntilByHost.get(firstEntry.host) ?? 0) > deps.now()) return;
|
||||
await Promise.all(distribution.legacyFallback.map((target) => runGitHubPoll(target)));
|
||||
if (distribution.redirected.length > 0) {
|
||||
await runGitHubPollBatch(distribution.redirected, startedAt);
|
||||
@@ -1721,7 +1680,6 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G
|
||||
entries: GitHubBatchPollEntry[];
|
||||
firstEntry: GitHubBatchPollEntry;
|
||||
args: string[];
|
||||
onError?: (entries: GitHubBatchPollEntry[], error: unknown) => void;
|
||||
}): Promise<GitHubBatchQueryResponse | null> {
|
||||
try {
|
||||
const stdout = await run(input.args, { cwd: input.firstEntry.target.cwd });
|
||||
@@ -1730,7 +1688,7 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G
|
||||
const isPaused = await pauseGitHubPollsAfterRateLimit(input.firstEntry, error);
|
||||
const partial = extractGraphqlBatchAliasesFromError(error);
|
||||
if (isPaused || !partial) {
|
||||
(input.onError ?? reportGitHubBatchError)(input.entries, error);
|
||||
reportGitHubBatchError(input.entries, error);
|
||||
return null;
|
||||
}
|
||||
const stdout = error instanceof GitHubCommandError ? (error.stdout ?? "") : "";
|
||||
@@ -1744,145 +1702,21 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G
|
||||
}
|
||||
}
|
||||
|
||||
function collectBatchCommitPages(
|
||||
entries: GitHubBatchPollEntry[],
|
||||
repositories: Map<GitHubBatchPollEntry, BatchPollRepository>,
|
||||
): Array<{ entry: GitHubBatchPollEntry; node: BatchPollPrNode }> {
|
||||
const candidates: Array<{ entry: GitHubBatchPollEntry; node: BatchPollPrNode }> = [];
|
||||
for (const entry of entries) {
|
||||
const repository = repositories.get(entry);
|
||||
if (!repository || (repository.isFork && repository.parent)) continue;
|
||||
const nodes = batchPollNodesForWorkspace(entry, repository);
|
||||
if (nodes.some((node) => node.state === "OPEN")) continue;
|
||||
for (const node of nodes) {
|
||||
batchMembership.set(
|
||||
node,
|
||||
terminalCommitPages.get(batchCommitKey(entry, node)) ?? { kind: "unknown" },
|
||||
);
|
||||
if (entry.target.headSha) candidates.push({ entry, node });
|
||||
}
|
||||
}
|
||||
return candidates;
|
||||
}
|
||||
|
||||
function batchCommitKey(entry: GitHubBatchPollEntry, node: BatchPollPrNode): string {
|
||||
return `${entry.host}/${entry.owner}/${entry.name}#${node.number}@${node.headRefOid}`;
|
||||
}
|
||||
|
||||
async function loadBatchCommitPages(
|
||||
entries: GitHubBatchPollEntry[],
|
||||
repositories: Map<GitHubBatchPollEntry, BatchPollRepository>,
|
||||
): Promise<Set<GitHubBatchPollEntry>> {
|
||||
const pending = collectBatchCommitPages(entries, repositories);
|
||||
while (pending.length) {
|
||||
const blocked = new Set<GitHubBatchPollEntry>();
|
||||
const needing = unresolvedBatchCommitPages(pending).filter(({ entry, node }) => {
|
||||
if (batchMembership.get(node)?.kind === "failed") blocked.add(entry);
|
||||
return !blocked.has(entry);
|
||||
});
|
||||
if (!needing.length) break;
|
||||
const fields = needing.map(({ entry, node }, index) => {
|
||||
const membership = batchMembership.get(node);
|
||||
const cursor = membership?.kind === "partial" ? membership.cursor : null;
|
||||
return `${batchAlias(index)}: repository(owner: ${graphqlString(entry.owner)}, name: ${graphqlString(entry.name)}) { pullRequest(number: ${node.number}) { commits(last:100${cursor ? `, before:${graphqlString(cursor)}` : ""}) { nodes { commit { oid } } pageInfo { hasPreviousPage startCursor } } } }`;
|
||||
});
|
||||
const args = [
|
||||
"api",
|
||||
"graphql",
|
||||
"-f",
|
||||
`query=query PaseoBatchCommitPages { rateLimit { limit remaining resetAt } ${fields.join("\n")} }`,
|
||||
];
|
||||
const needingEntries = [...new Set(needing.map(({ entry }) => entry))];
|
||||
const response = await loadGitHubPollBatchResponse({
|
||||
entries: needingEntries,
|
||||
firstEntry: needingEntries[0]!,
|
||||
args,
|
||||
onError: (affected, error) => {
|
||||
for (const { entry, node } of needing)
|
||||
if (affected.includes(entry)) batchMembership.set(node, { kind: "failed", error });
|
||||
},
|
||||
});
|
||||
if (!response) break;
|
||||
const rateLimit = parseGraphqlBatchRateLimit(response.stdout);
|
||||
if (rateLimit && pauseGitHubPollsAtReserve(entries[0]!.host, rateLimit)) {
|
||||
const error = new GitHubGraphqlPollPausedError(rateLimit);
|
||||
for (const { node } of needing) batchMembership.set(node, { kind: "failed", error });
|
||||
break;
|
||||
}
|
||||
for (const [index, { entry, node }] of needing.entries()) {
|
||||
const parsed = z
|
||||
.object({
|
||||
pullRequest: z.object({ commits: PullRequestCommitPageSchema }),
|
||||
})
|
||||
.safeParse(response.aliases[batchAlias(index)]);
|
||||
if (!parsed.success) {
|
||||
batchMembership.set(node, { kind: "failed", error: parsed.error });
|
||||
continue;
|
||||
}
|
||||
const page = parsed.data.pullRequest.commits;
|
||||
const previous = batchMembership.get(node);
|
||||
const commitOids = [
|
||||
...(previous?.kind === "partial" ? previous.commitOids : []),
|
||||
...page.nodes.map(({ commit }) => commit.oid),
|
||||
];
|
||||
const membership: PullRequestMembership =
|
||||
page.pageInfo.hasPreviousPage && page.pageInfo.startCursor
|
||||
? { kind: "partial", commitOids, cursor: page.pageInfo.startCursor }
|
||||
: { kind: "complete", commitOids };
|
||||
batchMembership.set(node, membership);
|
||||
const key = batchCommitKey(entry, node);
|
||||
terminalCommitPages.delete(key);
|
||||
terminalCommitPages.set(key, membership);
|
||||
if (terminalCommitPages.size > 512)
|
||||
terminalCommitPages.delete(terminalCommitPages.keys().next().value!);
|
||||
}
|
||||
}
|
||||
return reportUnresolvedCommitReads(pending);
|
||||
}
|
||||
|
||||
function unresolvedBatchCommitPages(
|
||||
candidates: Array<{ entry: GitHubBatchPollEntry; node: BatchPollPrNode }>,
|
||||
): Array<{ entry: GitHubBatchPollEntry; node: BatchPollPrNode }> {
|
||||
const byEntry = new Map<GitHubBatchPollEntry, BatchPollPrNode[]>();
|
||||
for (const { entry, node } of candidates) {
|
||||
const nodes = byEntry.get(entry) ?? [];
|
||||
nodes.push(node);
|
||||
byEntry.set(entry, nodes);
|
||||
}
|
||||
return [...byEntry].flatMap(([entry, nodes]) =>
|
||||
inspectBatchPollCandidates(entry, nodes).pending.map((node) => ({ entry, node })),
|
||||
);
|
||||
}
|
||||
|
||||
function reportUnresolvedCommitReads(
|
||||
candidates: Array<{ entry: GitHubBatchPollEntry; node: BatchPollPrNode }>,
|
||||
): Set<GitHubBatchPollEntry> {
|
||||
const failed = new Set<GitHubBatchPollEntry>();
|
||||
for (const { entry, node } of unresolvedBatchCommitPages(candidates)) {
|
||||
const membership = batchMembership.get(node);
|
||||
if (membership?.kind !== "failed" || failed.has(entry)) continue;
|
||||
failed.add(entry);
|
||||
updatePollTargetAfterError(entry.target, membership.error);
|
||||
}
|
||||
return failed;
|
||||
}
|
||||
|
||||
function distributeGitHubPollBatch(input: {
|
||||
entries: GitHubBatchPollEntry[];
|
||||
repositories: Map<GitHubBatchPollEntry, BatchPollRepository>;
|
||||
aliases: Record<string, unknown>;
|
||||
args: string[];
|
||||
startedAt: number;
|
||||
failedCommitEntries: ReadonlySet<GitHubBatchPollEntry>;
|
||||
}): GitHubBatchDistribution {
|
||||
const distribution: GitHubBatchDistribution = {
|
||||
pendingChecks: [],
|
||||
legacyFallback: [],
|
||||
redirected: [],
|
||||
};
|
||||
for (const entry of input.entries) {
|
||||
if (input.failedCommitEntries.has(entry)) continue;
|
||||
const repository = input.repositories.get(entry);
|
||||
if (!repository) {
|
||||
for (const [index, entry] of input.entries.entries()) {
|
||||
const aliasValue = input.aliases[batchAlias(index)];
|
||||
const repository = aliasValue ? BatchPollRepositorySchema.safeParse(aliasValue) : null;
|
||||
if (!repository?.success) {
|
||||
updatePollTargetAfterError(
|
||||
entry.target,
|
||||
new GitHubCommandError({
|
||||
@@ -1894,29 +1728,32 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G
|
||||
);
|
||||
continue;
|
||||
}
|
||||
if (repository.isFork && repository.parent) {
|
||||
const forkOwner = repository.owner?.login ?? entry.owner;
|
||||
if (repository.data.isFork && repository.data.parent) {
|
||||
const forkOwner = repository.data.owner?.login ?? entry.owner;
|
||||
pollRepositoryRedirects.set(batchRepositoryRedirectKey(entry), {
|
||||
owner: repository.parent.owner.login,
|
||||
name: repository.parent.name,
|
||||
owner: repository.data.parent.owner.login,
|
||||
name: repository.data.parent.name,
|
||||
headRepositoryOwner: forkOwner,
|
||||
});
|
||||
distribution.redirected.push(entry);
|
||||
continue;
|
||||
}
|
||||
const node = selectBatchPollNode(entry, repository);
|
||||
const node = selectBatchPollNode(entry, repository.data);
|
||||
if (!node) {
|
||||
// Legacy fallback covers the two ways "no match" can be wrong: a fork
|
||||
// whose PR lives in the parent repository, and a full candidate page —
|
||||
// ten newer same-named fork PRs can crowd the checkout's own PR out of
|
||||
// the first:N window, so absence is only conclusive on a partial page.
|
||||
if (repository.isFork || repository.pullRequests.nodes.length >= BATCH_PR_CANDIDATE_LIMIT) {
|
||||
if (
|
||||
repository.data.isFork ||
|
||||
repository.data.pullRequests.nodes.length >= BATCH_PR_CANDIDATE_LIMIT
|
||||
) {
|
||||
distribution.legacyFallback.push(entry.target);
|
||||
} else {
|
||||
finalizeBatchPollTarget({
|
||||
entry,
|
||||
node: null,
|
||||
repository: repository,
|
||||
repository: repository.data,
|
||||
rollup: null,
|
||||
startedAt: input.startedAt,
|
||||
});
|
||||
@@ -1933,7 +1770,7 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G
|
||||
finalizeBatchPollTarget({
|
||||
entry,
|
||||
node,
|
||||
repository: repository,
|
||||
repository: repository.data,
|
||||
rollup: cachedRollup,
|
||||
startedAt: input.startedAt,
|
||||
});
|
||||
@@ -1941,7 +1778,7 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G
|
||||
distribution.pendingChecks.push({
|
||||
entry,
|
||||
node,
|
||||
repository: repository,
|
||||
repository: repository.data,
|
||||
cacheKey: frozenKey,
|
||||
});
|
||||
}
|
||||
@@ -1965,59 +1802,41 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G
|
||||
return `${entry.host}\n${entry.originOwner}/${entry.originName}`;
|
||||
}
|
||||
|
||||
function batchPollNodesForWorkspace(
|
||||
entry: GitHubBatchPollEntry,
|
||||
repository: BatchPollRepository,
|
||||
): BatchPollPrNode[] {
|
||||
// Branch names also match other forks; reject those before loading commit lists.
|
||||
const owner = entry.target.headRepositoryOwner ?? entry.headRepositoryOwner;
|
||||
const selfOwner = (repository.owner?.login ?? entry.owner).toLowerCase();
|
||||
return repository.pullRequests.nodes.filter(
|
||||
(node) =>
|
||||
node.headRefName === entry.target.headRef &&
|
||||
(owner
|
||||
? node.headRepositoryOwner?.login === owner
|
||||
: node.headRepositoryOwner?.login?.toLowerCase() === selfOwner),
|
||||
);
|
||||
}
|
||||
|
||||
function selectBatchPollNode(
|
||||
entry: GitHubBatchPollEntry,
|
||||
repository: BatchPollRepository,
|
||||
): BatchPollPrNode | null {
|
||||
const resolution = inspectBatchPollCandidates(
|
||||
entry,
|
||||
batchPollNodesForWorkspace(entry, repository),
|
||||
);
|
||||
return resolution.pending.length ? null : resolution.match;
|
||||
}
|
||||
|
||||
function inspectBatchPollCandidates(
|
||||
entry: GitHubBatchPollEntry,
|
||||
nodes: BatchPollPrNode[],
|
||||
): { match: BatchPollPrNode | null; pending: BatchPollPrNode[] } {
|
||||
// Prefer the canonical owner from the response: the origin slug can carry
|
||||
// stale casing or a pre-transfer owner that repository() redirects from.
|
||||
const selfOwner = (repository.owner?.login ?? entry.owner).toLowerCase();
|
||||
const headRepositoryOwner = entry.target.headRepositoryOwner ?? entry.headRepositoryOwner;
|
||||
const nodeByCandidate = new Map<ResolvedPullRequestCandidate, BatchPollPrNode>();
|
||||
const candidates: ResolvedPullRequestCandidate[] = [];
|
||||
for (const node of nodes) {
|
||||
for (const node of repository.pullRequests.nodes) {
|
||||
const candidate = toCurrentPullRequestCandidate(
|
||||
toBatchCurrentPullRequestItem(node, undefined),
|
||||
entry.target.headRef,
|
||||
);
|
||||
if (!candidate) continue;
|
||||
candidate.membership = batchMembership.get(node) ?? { kind: "unknown" };
|
||||
if (!candidate) {
|
||||
continue;
|
||||
}
|
||||
// pullRequests(headRefName:) also matches forks whose branch shares the
|
||||
// name. Without a fork-owner hint the workspace branch lives in this
|
||||
// repository, so only self-owned heads are real candidates (mirrors
|
||||
// `gh pr view` resolving the current branch's own PR).
|
||||
if (!headRepositoryOwner && candidate.headRepositoryOwner?.toLowerCase() !== selfOwner) {
|
||||
continue;
|
||||
}
|
||||
nodeByCandidate.set(candidate, node);
|
||||
candidates.push(candidate);
|
||||
}
|
||||
const resolution = inspectPullRequestCandidates({
|
||||
const match = pickPullRequestCandidate({
|
||||
candidates,
|
||||
headRef: entry.target.headRef,
|
||||
headSha: entry.target.headSha,
|
||||
headRepositoryOwner: entry.target.headRepositoryOwner ?? entry.headRepositoryOwner,
|
||||
headRepositoryOwner,
|
||||
});
|
||||
return {
|
||||
match: resolution.match ? nodeByCandidate.get(resolution.match)! : null,
|
||||
pending: resolution.pending.map((candidate) => nodeByCandidate.get(candidate)!),
|
||||
};
|
||||
return match ? (nodeByCandidate.get(match) ?? null) : null;
|
||||
}
|
||||
|
||||
async function loadBatchPullRequestChecks(
|
||||
@@ -2142,14 +1961,7 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G
|
||||
toBatchCurrentPullRequestItem(node, input.rollup ?? undefined),
|
||||
entry.target.headRef,
|
||||
);
|
||||
const membership = batchMembership.get(node);
|
||||
const commitOids =
|
||||
membership?.kind === "complete" || membership?.kind === "partial"
|
||||
? membership.commitOids
|
||||
: undefined;
|
||||
status = built
|
||||
? { ...built, commitOids, forgeSpecific: { forge: "github", ...facts } }
|
||||
: null;
|
||||
status = built ? { ...built, forgeSpecific: { forge: "github", ...facts } } : null;
|
||||
}
|
||||
const cacheKey = buildCacheKey({
|
||||
cwd: entry.target.cwd,
|
||||
@@ -2365,7 +2177,6 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G
|
||||
readOptions: input,
|
||||
load: async () => {
|
||||
const status = await resolveCurrentPullRequestView({
|
||||
readCommits,
|
||||
cwd: input.cwd,
|
||||
headRef: input.headRef,
|
||||
headSha: input.headSha,
|
||||
@@ -3178,13 +2989,20 @@ async function resolveCurrentPullRequestView(options: {
|
||||
headRef: string;
|
||||
headSha?: string;
|
||||
headRepositoryOwner?: string;
|
||||
readCommits: ReturnType<typeof createPullRequestCommitReader>;
|
||||
run: (args: string[], options: GitHubCommandRunnerOptions) => Promise<string>;
|
||||
}): Promise<CurrentPullRequestStatus | null> {
|
||||
const viewCandidate = await tryCurrentPullRequestView(options);
|
||||
const viewCandidates = viewCandidate ? [viewCandidate] : [];
|
||||
const open = pickPullRequestCandidate({ ...options, candidates: viewCandidates });
|
||||
if (open?.status.state === "open") return open.status;
|
||||
const viewMatch = viewCandidate
|
||||
? pickPullRequestCandidate({
|
||||
candidates: [viewCandidate],
|
||||
headRef: options.headRef,
|
||||
headSha: options.headSha,
|
||||
headRepositoryOwner: options.headRepositoryOwner,
|
||||
})
|
||||
: null;
|
||||
if (viewMatch?.status.state === "open") {
|
||||
return viewMatch.status;
|
||||
}
|
||||
|
||||
let headRepositoryOwner = options.headRepositoryOwner;
|
||||
|
||||
@@ -3194,17 +3012,13 @@ async function resolveCurrentPullRequestView(options: {
|
||||
const parentOwner = repo?.parent?.owner?.login;
|
||||
const parentName = repo?.parent?.name;
|
||||
if (!forkOwner) {
|
||||
const match = await loadAndPickPullRequestCandidate({
|
||||
...options,
|
||||
candidates: viewCandidates,
|
||||
});
|
||||
return match?.status ?? null;
|
||||
return viewMatch?.status ?? null;
|
||||
}
|
||||
if (parentOwner && parentName) {
|
||||
return resolveForkPullRequestView({
|
||||
...options,
|
||||
forkOwner,
|
||||
viewCandidate,
|
||||
viewMatch,
|
||||
repo: `${parentOwner}/${parentName}`,
|
||||
});
|
||||
}
|
||||
@@ -3214,14 +3028,10 @@ async function resolveCurrentPullRequestView(options: {
|
||||
const candidates = await listCurrentPullRequestCandidates({
|
||||
cwd: options.cwd,
|
||||
headRef: options.headRef,
|
||||
headRepositoryOwner,
|
||||
run: options.run,
|
||||
});
|
||||
const match = await loadAndPickPullRequestCandidate({
|
||||
readCommits: options.readCommits,
|
||||
cwd: options.cwd,
|
||||
run: options.run,
|
||||
candidates: [...candidates, ...viewCandidates],
|
||||
const match = pickPullRequestCandidate({
|
||||
candidates: viewMatch ? [...candidates, viewMatch] : candidates,
|
||||
headRef: options.headRef,
|
||||
headSha: options.headSha,
|
||||
headRepositoryOwner,
|
||||
@@ -3242,9 +3052,8 @@ async function resolveForkPullRequestView(options: {
|
||||
headRef: string;
|
||||
headSha?: string;
|
||||
forkOwner: string;
|
||||
viewCandidate: ResolvedPullRequestCandidate | null;
|
||||
viewMatch: ResolvedPullRequestCandidate | null;
|
||||
repo: string;
|
||||
readCommits: ReturnType<typeof createPullRequestCommitReader>;
|
||||
run: (args: string[], options: GitHubCommandRunnerOptions) => Promise<string>;
|
||||
}): Promise<CurrentPullRequestStatus | null> {
|
||||
const numbers = await listForkPullRequestNumbers(options);
|
||||
@@ -3258,20 +3067,16 @@ async function resolveForkPullRequestView(options: {
|
||||
}),
|
||||
),
|
||||
);
|
||||
const match = await loadAndPickPullRequestCandidate({
|
||||
readCommits: options.readCommits,
|
||||
cwd: options.cwd,
|
||||
run: options.run,
|
||||
const match = pickPullRequestCandidate({
|
||||
candidates: [
|
||||
...candidates.filter(
|
||||
(candidate): candidate is ResolvedPullRequestCandidate =>
|
||||
candidate !== null && candidate.headRepositoryOwner === options.forkOwner,
|
||||
),
|
||||
...(options.viewCandidate ? [options.viewCandidate] : []),
|
||||
...(options.viewMatch ? [options.viewMatch] : []),
|
||||
],
|
||||
headRef: options.headRef,
|
||||
headSha: options.headSha,
|
||||
headRepositoryOwner: options.forkOwner,
|
||||
});
|
||||
return match?.status ?? null;
|
||||
}
|
||||
@@ -3365,62 +3170,6 @@ async function loadPullRequestGithubFacts(options: {
|
||||
}
|
||||
}
|
||||
|
||||
async function loadAndPickPullRequestCandidate(
|
||||
options: Parameters<typeof pickPullRequestCandidate>[0] & {
|
||||
cwd: string;
|
||||
readCommits: ReturnType<typeof createPullRequestCommitReader>;
|
||||
run: (args: string[], options: GitHubCommandRunnerOptions) => Promise<string>;
|
||||
},
|
||||
): Promise<ResolvedPullRequestCandidate | null> {
|
||||
for (;;) {
|
||||
const resolution = inspectPullRequestCandidates(options);
|
||||
const next = resolution.pending[0];
|
||||
if (!next) return resolution.match;
|
||||
await completeCandidateCommits(next, options);
|
||||
}
|
||||
}
|
||||
|
||||
async function completeCandidateCommits(
|
||||
candidate: ResolvedPullRequestCandidate,
|
||||
options: {
|
||||
cwd: string;
|
||||
headRef: string;
|
||||
headRepositoryOwner?: string;
|
||||
readCommits: ReturnType<typeof createPullRequestCommitReader>;
|
||||
run: (args: string[], options: GitHubCommandRunnerOptions) => Promise<string>;
|
||||
},
|
||||
): Promise<void> {
|
||||
const status = candidate.status;
|
||||
if (!isCandidateForHeadRef(candidate, options.headRef)) return;
|
||||
if (options.headRepositoryOwner && candidate.headRepositoryOwner !== options.headRepositoryOwner)
|
||||
return;
|
||||
if (status.state === "open" || candidate.membership.kind === "complete") return;
|
||||
const commitOids = await options.readCommits(`${status.url}@${status.headSha}`, async () => {
|
||||
const commits: string[] = [];
|
||||
let cursor: string | null = null;
|
||||
for (;;) {
|
||||
const query = `query { repository(owner:${graphqlString(status.repoOwner!)},name:${graphqlString(status.repoName!)}) { pullRequest(number:${status.number}) { commits(last:100${cursor ? `,before:${graphqlString(cursor)}` : ""}) { nodes { commit { oid } } pageInfo { hasPreviousPage startCursor } } } } }`;
|
||||
const stdout = await options.run(["api", "graphql", "-f", `query=${query}`], {
|
||||
cwd: options.cwd,
|
||||
});
|
||||
const page = z
|
||||
.object({
|
||||
data: z.object({
|
||||
repository: z.object({
|
||||
pullRequest: z.object({ commits: PullRequestCommitPageSchema }),
|
||||
}),
|
||||
}),
|
||||
})
|
||||
.parse(JSON.parse(stdout)).data.repository.pullRequest.commits;
|
||||
commits.push(...page.nodes.map(({ commit }) => commit.oid));
|
||||
if (!page.pageInfo?.hasPreviousPage) return commits;
|
||||
cursor = page.pageInfo.startCursor;
|
||||
}
|
||||
});
|
||||
candidate.membership = { kind: "complete", commitOids };
|
||||
status.commitOids = commitOids;
|
||||
}
|
||||
|
||||
async function tryCurrentPullRequestView(options: {
|
||||
cwd: string;
|
||||
headRef: string;
|
||||
@@ -3434,11 +3183,10 @@ async function tryCurrentPullRequestView(options: {
|
||||
run: options.run,
|
||||
args,
|
||||
});
|
||||
const candidate = parseCurrentPullRequestCandidate(stdout, options.headRef, {
|
||||
return parseCurrentPullRequestCandidate(stdout, options.headRef, {
|
||||
args: [...args, "--json", CURRENT_PR_STATUS_FIELDS],
|
||||
cwd: options.cwd,
|
||||
});
|
||||
return candidate;
|
||||
} catch (error) {
|
||||
if (isNoPullRequestFoundError(error)) {
|
||||
return null;
|
||||
@@ -3450,7 +3198,6 @@ async function tryCurrentPullRequestView(options: {
|
||||
async function listCurrentPullRequestCandidates(options: {
|
||||
cwd: string;
|
||||
headRef: string;
|
||||
headRepositoryOwner?: string;
|
||||
run: (args: string[], options: GitHubCommandRunnerOptions) => Promise<string>;
|
||||
}): Promise<ResolvedPullRequestCandidate[]> {
|
||||
const args = ["pr", "list", "--state", "all", "--head", options.headRef, "--limit", "10"];
|
||||
@@ -3460,11 +3207,10 @@ async function listCurrentPullRequestCandidates(options: {
|
||||
run: options.run,
|
||||
args,
|
||||
});
|
||||
const candidates = parseCurrentPullRequestCandidateList(stdout, options.headRef, {
|
||||
return parseCurrentPullRequestCandidateList(stdout, options.headRef, {
|
||||
args: [...args, "--json", CURRENT_PR_STATUS_FIELDS],
|
||||
cwd: options.cwd,
|
||||
});
|
||||
return candidates;
|
||||
} catch (error) {
|
||||
if (isNoPullRequestFoundError(error)) {
|
||||
return [];
|
||||
@@ -3682,7 +3428,6 @@ function toCurrentPullRequestCandidate(
|
||||
const headSha = item.headRefOid;
|
||||
return {
|
||||
status,
|
||||
membership: { kind: "unknown" },
|
||||
updatedAt: item.updatedAt,
|
||||
...(headSha ? { headSha } : {}),
|
||||
...(headRepositoryOwner ? { headRepositoryOwner } : {}),
|
||||
@@ -3703,38 +3448,6 @@ function pickPullRequestCandidate(options: {
|
||||
headSha?: string;
|
||||
headRepositoryOwner?: string;
|
||||
}): ResolvedPullRequestCandidate | null {
|
||||
const result = inspectPullRequestCandidates(options);
|
||||
return result.pending.length ? null : result.match;
|
||||
}
|
||||
|
||||
function inspectPullRequestCandidates(options: Parameters<typeof pickPullRequestCandidate>[0]): {
|
||||
match: ResolvedPullRequestCandidate | null;
|
||||
pending: ResolvedPullRequestCandidate[];
|
||||
} {
|
||||
const matching = matchingPullRequestCandidates(options);
|
||||
const open = matching.find((candidate) => candidate.status.state === "open");
|
||||
if (open) return { match: open, pending: [] };
|
||||
const pending: ResolvedPullRequestCandidate[] = [];
|
||||
if (!options.headSha) return { match: null, pending };
|
||||
for (const candidate of matching) {
|
||||
if (
|
||||
pullRequestContainsCommit({
|
||||
workspaceCommit: options.headSha,
|
||||
pullRequestCommits:
|
||||
candidate.membership.kind === "complete" || candidate.membership.kind === "partial"
|
||||
? candidate.membership.commitOids
|
||||
: undefined,
|
||||
})
|
||||
)
|
||||
return { match: candidate, pending };
|
||||
if (candidate.membership.kind !== "complete") pending.push(candidate);
|
||||
}
|
||||
return { match: null, pending };
|
||||
}
|
||||
|
||||
function matchingPullRequestCandidates(
|
||||
options: Parameters<typeof pickPullRequestCandidate>[0],
|
||||
): ResolvedPullRequestCandidate[] {
|
||||
const matching = options.candidates.filter((candidate) => {
|
||||
if (!isCandidateForHeadRef(candidate, options.headRef)) {
|
||||
return false;
|
||||
@@ -3747,7 +3460,7 @@ function matchingPullRequestCandidates(
|
||||
matching.sort((left, right) =>
|
||||
comparePullRequestCandidatePreference(left, right, options.headSha),
|
||||
);
|
||||
return matching;
|
||||
return matching[0] ?? null;
|
||||
}
|
||||
|
||||
function comparePullRequestCandidatePreference(
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
import { createPullRequestHistory } from "../test-utils/pull-request-history.js";
|
||||
import { onTestFinished } from "vitest";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import type { PullRequestCommandStatus } from "./forge-service.js";
|
||||
@@ -377,7 +375,6 @@ describe("createGitLabService", () => {
|
||||
const { service, calls } = makeService((args) => {
|
||||
if (args[1] === "list") return ok(JSON.stringify([newestStale, exactOlder]));
|
||||
if (args[1] === "view" && args[2] === "270") return ok(JSON.stringify(exactOlder));
|
||||
if (args[1]?.includes("/commits?")) return ok(JSON.stringify([{ id: checkoutSha }]));
|
||||
if (args[0] === "api") return ok("{}");
|
||||
throw new Error(`unexpected call: ${args.join(" ")}`);
|
||||
});
|
||||
@@ -389,93 +386,25 @@ describe("createGitLabService", () => {
|
||||
});
|
||||
|
||||
expect(status?.number).toBe(270);
|
||||
expect(calls[2]).toEqual(["mr", "view", "270", "-F", "json"]);
|
||||
});
|
||||
|
||||
it("checks fork MR membership on a reused base branch and caches successful lists", async () => {
|
||||
const requests = Array.from({ length: 100 }, (_, index) => ({
|
||||
...OPEN_MR,
|
||||
iid: index + 1,
|
||||
source_branch: "main",
|
||||
state: "closed",
|
||||
source_project_id: 202,
|
||||
target_project_id: 101,
|
||||
sha: `fork-head-${index}`,
|
||||
web_url: `https://gitlab.example.com/example-group/example-project/-/merge_requests/${index + 1}`,
|
||||
}));
|
||||
let commitReads = 0;
|
||||
const { service } = makeService((args) => {
|
||||
if (args[1] === "list") return ok(JSON.stringify(requests));
|
||||
if (args[1]?.includes("/commits?")) {
|
||||
commitReads++;
|
||||
return ok(JSON.stringify([{ id: "fork-own-commit" }]));
|
||||
}
|
||||
if (args[1] === "view") return ok(JSON.stringify(requests[0]));
|
||||
return ok("{}");
|
||||
});
|
||||
const input = { cwd: "/repo", headRef: "main", headSha: "inherited-base" };
|
||||
await expect(service.getCurrentPullRequestStatus(input)).resolves.toBeNull();
|
||||
expect(commitReads).toBe(100);
|
||||
await expect(
|
||||
service.getCurrentPullRequestStatus({ ...input, force: true }),
|
||||
).resolves.toBeNull();
|
||||
expect(commitReads).toBe(100);
|
||||
await expect(
|
||||
service.getCurrentPullRequestStatus({ ...input, headSha: "fork-own-commit", force: true }),
|
||||
).resolves.toMatchObject({ number: 1, state: "closed" });
|
||||
expect(commitReads).toBe(100);
|
||||
});
|
||||
|
||||
it("rejects an unknown newer MR instead of choosing an older match and retries", async () => {
|
||||
const older = { ...OPEN_MR, iid: 270, state: "merged", sha: "older-head" };
|
||||
const newer = { ...older, iid: 271, state: "closed", sha: "newer-head" };
|
||||
let failedReads = 0;
|
||||
const { service } = makeService((args) => {
|
||||
if (args[1] === "list") return ok(JSON.stringify([newer, older]));
|
||||
if (args[1]?.includes("/271/commits?")) {
|
||||
failedReads++;
|
||||
if (failedReads < 3) throw new Error("HTTP 502");
|
||||
return ok(JSON.stringify([{ id: "workspace-commit" }]));
|
||||
}
|
||||
if (args[1]?.includes("/270/commits?"))
|
||||
return ok(JSON.stringify([{ id: "workspace-commit" }]));
|
||||
if (args[1] === "view") return ok(JSON.stringify(newer));
|
||||
return ok("{}");
|
||||
});
|
||||
const input = { cwd: "/repo", headRef: OPEN_MR.source_branch, headSha: "workspace-commit" };
|
||||
await expect(service.getCurrentPullRequestStatus(input)).rejects.toThrow(
|
||||
"GitLab CLI command failed",
|
||||
);
|
||||
await expect(
|
||||
service.getCurrentPullRequestStatus({ ...input, force: true, reason: "retry" }),
|
||||
).rejects.toThrow("GitLab CLI command failed");
|
||||
expect(failedReads).toBe(2);
|
||||
await expect(
|
||||
service.getCurrentPullRequestStatus({ ...input, force: true, reason: "recovered" }),
|
||||
).resolves.toMatchObject({ number: 271 });
|
||||
expect(calls[1]).toEqual(["mr", "view", "270", "-F", "json"]);
|
||||
});
|
||||
|
||||
it("keeps a merged MR when its remote head advances beyond the checkout", async () => {
|
||||
const history = createPullRequestHistory();
|
||||
onTestFinished(history.dispose);
|
||||
const { cwd, workspaceCommit, pullRequestCommit } = history;
|
||||
const stale = {
|
||||
...OPEN_MR,
|
||||
state: "merged",
|
||||
source_branch: "dev",
|
||||
sha: pullRequestCommit,
|
||||
sha: "1111111111111111111111111111111111111111",
|
||||
};
|
||||
const { service, calls } = makeService((args) => {
|
||||
if (args[1]?.includes("/commits?"))
|
||||
return ok(JSON.stringify([{ id: workspaceCommit }, { id: pullRequestCommit }]));
|
||||
return ok(JSON.stringify(args[1] === "list" ? [stale] : stale));
|
||||
});
|
||||
const { service, calls } = makeService((args) =>
|
||||
ok(JSON.stringify(args[1] === "list" ? [stale] : stale)),
|
||||
);
|
||||
|
||||
await expect(
|
||||
service.getCurrentPullRequestStatus({
|
||||
cwd,
|
||||
cwd: "/repo",
|
||||
headRef: "dev",
|
||||
headSha: workspaceCommit,
|
||||
headSha: "2222222222222222222222222222222222222222",
|
||||
}),
|
||||
).resolves.toMatchObject({ state: "merged" });
|
||||
expect(calls[0]).toEqual(currentMrListArgs("dev"));
|
||||
|
||||
@@ -1,7 +1,3 @@
|
||||
import {
|
||||
pullRequestContainsCommit,
|
||||
createPullRequestCommitReader,
|
||||
} from "./pull-request-contains-commit.js";
|
||||
import { z } from "zod";
|
||||
import { parseGitRemoteLocation } from "@getpaseo/protocol/git-remote";
|
||||
import { findExecutable } from "../executable-resolution/executable-resolution.js";
|
||||
@@ -157,7 +153,6 @@ const GitLabMergeRequestSchema = z
|
||||
source_branch: z.string(),
|
||||
target_branch: z.string(),
|
||||
sha: z.string().optional(),
|
||||
commitOids: z.array(z.string()).optional(),
|
||||
source_project_id: z.number().nullable().optional(),
|
||||
target_project_id: z.number().nullable().optional(),
|
||||
draft: z.boolean().optional(),
|
||||
@@ -744,7 +739,6 @@ function toCurrentPullRequestStatus(
|
||||
baseRefName: mr.target_branch,
|
||||
headRefName: mr.source_branch,
|
||||
...(mr.sha ? { headSha: mr.sha } : {}),
|
||||
commitOids: mr.commitOids,
|
||||
isMerged: mr.state === "merged" || mr.merged_at != null,
|
||||
isDraft: mr.draft ?? mr.work_in_progress ?? false,
|
||||
mergeable: mapMergeable(mr),
|
||||
@@ -925,7 +919,6 @@ function gitLabNumberQuery(query: string | undefined): string | null {
|
||||
}
|
||||
|
||||
export function createGitLabService(options: CreateGitLabServiceOptions = {}): ForgeService {
|
||||
const readRequestCommits = createPullRequestCommitReader();
|
||||
const runner = options.runner ?? runGlabCommand;
|
||||
const resolveGlab = createCachedCliPathResolver(options.resolveGlabPath ?? resolveGlabPath);
|
||||
const resolveRemoteUrl = options.resolveRemoteUrl ?? defaultResolveRemoteUrl;
|
||||
@@ -999,32 +992,15 @@ export function createGitLabService(options: CreateGitLabServiceOptions = {}): F
|
||||
): Promise<GitLabMergeRequest | null> {
|
||||
const mergeRequests = await listMergeRequestsBySourceBranch(cwd, headRef);
|
||||
const candidates = mergeRequests.filter((mr) => mr.source_branch === headRef);
|
||||
const open = candidates.find((candidate) => mapMergeRequestState(candidate.state) === "open");
|
||||
if (open) return viewMergeRequest(cwd, String(open.iid));
|
||||
candidates.sort((left, right) => Number(right.sha === headSha) - Number(left.sha === headSha));
|
||||
for (const mr of candidates) {
|
||||
const project = mr.target_project_id ?? extractProjectPath(mr.references?.full);
|
||||
if (project === undefined) continue;
|
||||
const commitOids = await readRequestCommits(`${mr.web_url}@${mr.sha}`, async () => {
|
||||
const result: string[] = [];
|
||||
for (let page = 1; ; page++) {
|
||||
const commits = await runJson(
|
||||
[
|
||||
"api",
|
||||
`projects/${encodeURIComponent(project)}/merge_requests/${mr.iid}/commits?per_page=100&page=${page}`,
|
||||
],
|
||||
{ cwd },
|
||||
z.array(z.object({ id: z.string() })),
|
||||
);
|
||||
result.push(...commits.map((commit) => commit.id));
|
||||
if (commits.length < 100) return result;
|
||||
}
|
||||
});
|
||||
if (pullRequestContainsCommit({ workspaceCommit: headSha, pullRequestCommits: commitOids })) {
|
||||
return { ...(await viewMergeRequest(cwd, String(mr.iid))), commitOids };
|
||||
}
|
||||
}
|
||||
return null;
|
||||
const match =
|
||||
candidates.find((mr) => mapMergeRequestState(mr.state) === "open") ??
|
||||
candidates.find(
|
||||
(mr) =>
|
||||
mapMergeRequestState(mr.state) !== "open" && headSha !== undefined && mr.sha === headSha,
|
||||
) ??
|
||||
candidates[0] ??
|
||||
null;
|
||||
return match ? viewMergeRequest(cwd, String(match.iid)) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,23 +0,0 @@
|
||||
/** Only commits introduced by the request establish workspace ownership. */
|
||||
export function pullRequestContainsCommit(input: {
|
||||
workspaceCommit?: string;
|
||||
pullRequestCommits?: readonly string[];
|
||||
}): boolean {
|
||||
return !!input.workspaceCommit && !!input.pullRequestCommits?.includes(input.workspaceCommit);
|
||||
}
|
||||
|
||||
/** Terminal commit lists are immutable for a request head. Failed reads remain retryable. */
|
||||
export function createPullRequestCommitReader() {
|
||||
const cache = new Map<string, Promise<string[]>>();
|
||||
return (key: string, load: () => Promise<string[]>): Promise<string[]> => {
|
||||
const existing = cache.get(key);
|
||||
if (existing) return existing;
|
||||
const commits = load().catch((error: unknown) => {
|
||||
cache.delete(key);
|
||||
throw error;
|
||||
});
|
||||
cache.set(key, commits);
|
||||
if (cache.size > 1024) cache.delete(cache.keys().next().value!);
|
||||
return commits;
|
||||
};
|
||||
}
|
||||
@@ -1,44 +0,0 @@
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { mkdirSync, mkdtempSync, rmSync } from "node:fs";
|
||||
import { resolve, join } from "node:path";
|
||||
|
||||
export function createPullRequestHistory() {
|
||||
const root = resolve(import.meta.dirname, "../../../../.artifacts");
|
||||
mkdirSync(root, { recursive: true });
|
||||
const directory = mkdtempSync(join(root, "pr-history-"));
|
||||
const remote = join(directory, "remote");
|
||||
const cwd = join(directory, "checkout");
|
||||
const git = (path: string, args: string[]) =>
|
||||
execFileSync("git", args, {
|
||||
cwd: path,
|
||||
encoding: "utf8",
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
}).trim();
|
||||
git(directory, ["init", remote]);
|
||||
const commit = (message: string) =>
|
||||
git(remote, [
|
||||
"-c",
|
||||
"user.name=Test",
|
||||
"-c",
|
||||
"user.email=test@example.com",
|
||||
"-c",
|
||||
"commit.gpgsign=false",
|
||||
"commit",
|
||||
"--allow-empty",
|
||||
"-m",
|
||||
message,
|
||||
]);
|
||||
commit("workspace");
|
||||
const workspaceCommit = git(remote, ["rev-parse", "HEAD"]);
|
||||
git(directory, ["clone", remote, cwd]);
|
||||
commit("remote branch update");
|
||||
const pullRequestCommit = git(remote, ["rev-parse", "HEAD"]);
|
||||
return {
|
||||
cwd,
|
||||
remote,
|
||||
workspaceCommit,
|
||||
pullRequestCommit,
|
||||
git: (args: string[]) => git(cwd, args),
|
||||
dispose: () => rmSync(directory, { recursive: true, force: true }),
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user