Compare commits

...
Author SHA1 Message Date
Mohamed Boudra 15071640ce test(server): reap crash-test terminal processes before teardown 2026-11-17 06:59:38 +01:00
Mohamed Boudra efd7c5cc53 fix(server): preserve PR checks while GitHub polling is paused 2026-11-17 06:27:56 +01:00
Mohamed Boudra 7931027162 fix(server): isolate PR membership state from forge metadata 2026-11-17 06:19:56 +01:00
Mohamed Boudra 220d4cb546 fix(server): share ranked PR resolution with batched polling 2026-11-17 05:56:16 +01:00
Mohamed Boudra 9e4806e615 fix(server): defer terminal PR reads and follow forge pagination 2026-11-17 05:39:54 +01:00
Mohamed Boudra 45e2869ad8 fix(server): preserve PR state when membership reads fail 2026-11-17 05:23:39 +01:00
Mohamed Boudra 35d0edb67b fix(server): isolate and cache terminal PR commit reads
Keep membership out of metadata polls and request only terminal commit IDs in newest-first batches. Failed candidates remain retryable and do not prevent complete workspaces or other matching candidates from updating.
2026-11-17 05:11:19 +01:00
Mohamed Boudra 9dc32bb549 fix(server): narrow absent PR state before projecting workspace payload 2026-11-17 04:47:09 +01:00
Mohamed Boudra fedb40d112 fix(server): require membership in the pull request own commits
Exclude inherited base commits using forge commit lists. Carry membership evidence in the server snapshot so auto-archive uses the same rule without Git subprocesses or network fetches. Preserve GitHub batching and cache terminal commit reads.
2026-11-17 04:39:03 +01:00
Mohamed Boudra 7e5ea17d6c fix(server): match terminal pull requests by workspace commit ancestry
Branch-name fallback attached historical closed requests to reused workspaces. Share containment between forge lookup and auto-archive so remote branch updates remain eligible without accepting unrelated requests. Fetch missing Git objects without consuming the batched GitHub API budget or moving refs.
2026-11-17 04:12:29 +01:00
ce09360241 fix(server): agents archived while not loaded get the archive time as their last update (#9926)
* fix(server): move updatedAt when archiving an agent that is only in storage

Archiving a loaded agent sets its updatedAt to the archive time
(markRecordArchived). Archiving an agent that is only in storage, which
is also how a parent's archive reaches its children, kept the old
updatedAt. Lists sorted by updated_at, such as History, then left a
just-archived agent where its last turn put it, sometimes days back, and
clients paging such a list by time never reached it.

archiveSnapshotUnlocked now records the archive time as updatedAt too.

Co-authored-by: RoundRedDot <roundreddot@gmail.com>

* fix(server): keep updatedAt from moving back when an archive is restored

Archiving a stored-only agent now sets updatedAt to the archive time.
When the archive time is earlier than the record's updatedAt, as when a
failed send or resume puts an agent's original archive back after
unarchiving it, updatedAt stays where it is. Clients drop agent updates
that are older than the one they hold, so moving it back left them
showing the agent active.

Co-authored-by: luke <luopeihuan@gmail.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(server): keep updatedAt from moving back when a loaded agent's archive is restored

The rule that archiving never moves updatedAt backwards now lives in
buildArchivedAgentRecord, which both archive paths use. A failed send
that resumed the agent before a later loading step failed puts its
original archive back through the loaded path, which had the same
backwards move.

The workspace archive stamp test now uses stamps taken after the
agents' activity, as real archive stamps are.

Co-authored-by: luke <luopeihuan@gmail.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor(server): require the archive time when building an archived agent

buildArchivedAgentRecord no longer accepts an archive that leaves
updatedAt unset, the gap #9920 came through, and its tests now assert
the rule: a later archive time moves updatedAt, an earlier one keeps it.

Co-authored-by: luke <luopeihuan@gmail.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: luke <luopeihuan@gmail.com>
Co-authored-by: RoundRedDot <roundreddot@gmail.com>
Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 02:55:35 +00:00
paseo-bot[bot]andClaude Opus 5.5 8f3752ecb9 test(app): wait for a label filter row to be laid out before measuring it (#9922)
The workspace-labels journey measured the Urgent filter row right after
opening the label filter page. While the page is still coming in, the
row has no box yet, and the measuring helper threw inside expect.poll,
which ends the poll instead of retrying it. An element with no box now
counts as not settled, and the helper returns the box it settled on
instead of measuring a second time.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 00:36:12 +00:00
73c22f7917 Keep desktop workspaces reachable when sidebar navigation overflows (#9903)
* fix(app): keep desktop workspaces reachable when sidebar navigation overflows

Apply the mobile cap from #8727 to DesktopSidebar: the navigation rows
scroll inside a viewport capped at half the sidebar, so plugin rows no
longer push the Workspaces list out of a short window. The viewport sits
outside the titlebar drag area and opts out of app regions, since
Electron does not clip app-region rects to scroll viewports.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(app): keep the sidebar drag strip on Windows and Linux

Moving the desktop navigation rows into a scroll viewport left the
sidebar's drag overlay in an empty container when the window controls
sit top-right, so Windows and Linux lost every window-drag surface in
the sidebar. The strip above the navigation now carries the drag
overlay there, and the rows start flush below it.

Refs #9872

Co-authored-by: Alex Tong <alex.tong@pentatonic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor(app): share the window-content marker from the drag-region module

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor(app): share one nav scroller between the mobile and desktop sidebars

The desktop sidebar's capped nav viewport was a plain ScrollView on every
platform, so on tablets it did not join the overlay's close swipe the way
the mobile nav block and the workspace list do. Both sidebars now render
SidebarNavScroll, which owns the 50% cap, the native gesture-handler
branch linked to the close gesture, the divider, and the web
window-content marker.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(app): drop the empty nav divider and drag strip when every top item is hidden

With every top navigation item turned off, the desktop sidebar now starts
at the Workspaces section again, as on main: no 1px divider and no 8px
drag strip above it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Alex Tong <alex.tong@pentatonic.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-11-16 23:59:03 +00:00
paseo-bot[bot]andClaude Opus 5.5 038a9ca00d fix(opencode): clear a question that a new message replaces (#9891)
With the default send setting, a message sent while an OpenCode agent
waits on a question steers the turn, and Paseo rejects the question in
OpenCode. The OpenCode session dropped the question from its own list
without reporting it resolved, so the agent manager and the app kept
showing it. Answering or dismissing it then failed with "No pending
permission request", and the prompt could not be closed.

The session now reports permission_resolved whenever OpenCode accepts a
reply, rejection, or answer, as the other providers do.

Fixes #9879

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 19:03:40 +00:00
paseo-bot[bot]andClaude Opus 5.5 3a7e216b7d test(server): read the latest event when checking a removed file on macOS (#9898)
macOS FSEvents can replay the file's pre-subscription write as a create
after the observer starts. The test read the first event for the path,
so it stayed on that create after the delete arrived in a later batch.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 18:45:26 +00:00
paseo-bot[bot]andClaude Opus 5.5 6ef188416f test(e2e): start the plugin modal settle check once the sheet is in view (#9889)
The compact sheet holds below the viewport for a few frames before it
slides up. On a slow runner two settle reads 100 ms apart can both land
in that hold. Waiting for the title to enter the viewport first means the
settle check only starts once the slide has begun.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 18:04:29 +00:00
791bbd3596 fix(app): keep preview tab identities unique across split panes (#9888)
* fix(app): keep preview tab identities unique across split panes

Reserve existing pane and sheet IDs when allocating a new instance, including tabs opened by reconciliation. Keep menu-hosted sheet identities stable across layout changes.

Repair duplicate IDs in saved layouts without discarding tabs, state, or pane focus. Resolve file navigation by target rather than an ID retained from a previous preview.

* fix(app): open a listed subagent as its own agent tab

A subagent opened in place of the compact subagent list got a random
instance id, so "Open as tab" created a tab that no longer carried the
subagent's agent tab id. The in-place sheet now starts from the
subagent's own tab id, still checked against occupied ids and kept
stable across layout updates.

Co-authored-by: Kosmo CHE <108672813+KosmoCHE@users.noreply.github.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Kosmo CHE <kosmoche@gmail.com>
Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: Kosmo CHE <108672813+KosmoCHE@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 18:04:19 +00:00
Angus Buick b95f1bbf31 fix(app): draw the Add host text fields as inputs again (#9864) (#9865)
AdaptiveTextInput wraps its input with withUnistyles, and the pairing link and direct connection modals wrapped AdaptiveTextInput a second time. On web each wrapper is a display: contents element whose style lands on its direct child, so the outer style landed on the inner wrapper and the input lost its border, background and padding.

Drop the outer wrapper, AdaptiveTextInput already themes the placeholder colour. Also give the host password field a placeholder and focus it when pairing asks for a password.
2026-11-16 16:58:48 +00:00
paseo-bot[bot]andClaude Opus 5.5 c2a24ae81e test(e2e): wait for a plugin modal sheet to settle before using the pointer (#9884)
On compact layouts the sheet holds below the viewport and then slides up,
so the Horizontal tab hover could resolve its point mid-slide and the wheel
landed on the rows below the tabs. openExample now waits for the title to
stop moving.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 15:48:36 +00:00
paseo-bot[bot] 6eb94611b3 test(e2e): wait for the isolated daemon itself, not any listener on its port (#9863)
* test(e2e): wait for the isolated daemon itself, not any listener on its port

The helper reserves a port, releases it, and starts the daemon on it. If
another process takes the port in between, the daemon exits with
EADDRINUSE, but the readiness probe already succeeded against the other
listener. The worker fixture then reported the daemon as started and its
seed client retried a dead endpoint until the 60s fixture timeout.

Readiness now requires /api/status on the port to report this daemon's
server id, so the probe keeps waiting, sees the EADDRINUSE exit, and the
existing retry moves to a fresh port.

* test(e2e): authenticate the readiness probe with the daemon's local credential

A password with spaces cannot travel as an HTTP bearer, so the status
probe of a password-protected daemon stayed 401. The daemon writes a
local credential into its home before listening and /api/status accepts
it, as the CLI's local status does.

---------

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-11-16 15:03:02 +00:00
Okan YILDIRIM a8cadae0ee fix(app): keep saved hosts when one entry can't be read (#9847)
The host registry was parsed with a strict array schema, so one host or
connection this build couldn't read failed the whole array. The loader then
removed @paseo:daemon-registry, and every saved host and password with it.
That happens after a downgrade, or once a newer build saves a connection kind
this build doesn't know.

- Hosts and connections are read one at a time. One this build can't read
  is skipped, and the other hosts load.
- Skipped entries are written back on every save, so the build that wrote
  them still finds them. Removing a host also drops what this build couldn't
  read for it.
- A value that isn't a JSON array is copied to
  @paseo:daemon-registry:unreadable instead of being removed.
- The stored-password migration still moves a connection password to its
  host when that host also has an unreadable connection.
2026-11-16 14:01:03 +00:00
5a78c1cd16 Let idle cleanup release Codex chats opened only to read history (#9859)
A Codex session opened to read history reads the thread and disposes its
app-server right away, but canStopRuntime() vetoed it because it had no
client. Idle cleanup then kept every such chat loaded in the daemon.

Closes #9804

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: Spencer Shulem <1703265+Spshulem@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 13:01:00 +00:00
56 changed files with 2928 additions and 356 deletions
+10
View File
@@ -590,6 +590,16 @@ bookkeeping may scan opaque row sizes during a deferred write, never during host
before a requested cache row can paint. The row store is not encrypted. A cached timeline can contain
source code, prompts, and tool output; encrypted-at-rest storage is a separate security decision.
### Saved hosts
**AsyncStorage key:** `@paseo:daemon-registry`, an array of host profiles.
Every app build on a device shares this key, including an older build after a downgrade and a newer
one that saves a connection kind this build doesn't know. The key holds every saved host and its
password, so never remove it. Read each host and connection on its own, skip the ones this build
can't read, and write them back on every save. A value that isn't a JSON array is copied to
`@paseo:daemon-registry:unreadable` before the next save overwrites it.
### Draft Store
**AsyncStorage key:** `paseo-drafts` (version 2)
+19 -6
View File
@@ -97,12 +97,25 @@ Register the adapter in `defaultForgeRegistry` with:
- `matchesHost` from manifest `cloudHosts`
- `probeHost` when self-hosted/Enterprise detection is supported
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.
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.
Keep checkout HEAD in adapter cache and poll identities so checkout changes
refresh the facts used by archive eligibility.
@@ -2,10 +2,16 @@ import { copyPluginExample } from "../support/helpers/plugin-fixture";
import { expect, test as base, type Page } from "../support/fixtures";
import { gotoAppShell } from "../support/helpers/app";
import { connectNewWorkspaceDaemonClient } from "../support/helpers/new-workspace";
import { waitForSettledPosition } from "../support/helpers/sheet-layout";
async function openExample(page: Page, example: string) {
await page.getByRole("button", { name: `Open ${example}`, exact: true }).click();
await expect(page.getByText(`Modal example: ${example}`, { exact: true })).toBeVisible();
const title = page.getByText(`Modal example: ${example}`, { exact: true });
// A compact sheet holds below the viewport and then slides up, so a pointer placed before it
// stops lands on whatever slides under it. The settle check starts once the slide has begun;
// two equal reads during the hold would otherwise count as settled.
await expect(title).toBeInViewport();
await waitForSettledPosition(title);
}
async function closeExample(page: Page) {
@@ -208,6 +208,35 @@ test.describe("Plugin sidebar items", () => {
});
});
test("a short desktop sidebar keeps workspaces usable while navigation scrolls", async ({
page,
}) => {
await page.setViewportSize({ width: 1280, height: 480 });
await gotoAppShell(page);
await expect(botRow(page, "status")).toBeAttached();
const workspace = visibleTestId(page, `sidebar-workspace-row-${getServerId()}:${workspaceId}`);
await expect(workspace).toBeInViewport({ ratio: 1 });
await expect(botRow(page, "status")).not.toBeInViewport();
await test.step("navigation stays within half the sidebar", async () => {
const nav = await boxOf(visibleTestId(page, "sidebar-nav-scroll"));
expect(nav.height).toBeLessThanOrEqual(480 / 2 + 1);
});
await test.step("scrolling navigation reaches its last row without moving workspaces", async () => {
const before = await boxOf(workspace);
await visibleTestId(page, "sidebar-global-new-workspace").hover();
await page.mouse.wheel(0, 800);
await expect(botRow(page, "status")).toBeInViewport({ ratio: 1 });
await expect(workspace).toBeInViewport({ ratio: 1 });
expect((await boxOf(workspace)).y).toBe(before.y);
await qaScreenshot(page, "desktop-short-sidebar-nav-scrolled");
await botRow(page, "status").click();
await expect(page.getByText("Bot status details", { exact: true })).toBeVisible();
await page.getByRole("button", { name: "Close bot status", exact: true }).click();
});
});
test("a restored plugin screen waits for its catalog before rendering", async ({ page }) => {
await page.setViewportSize(WIDE);
await gotoWorkspace(page, workspaceId);
@@ -0,0 +1,106 @@
import { expect, type Page } from "@playwright/test";
import { test } from "../support/fixtures";
import { gotoAppShell, openSettings } from "../support/helpers/app";
import { renameHostFromSettings } from "../support/helpers/hosts";
import { getServerId } from "../support/helpers/server-id";
import { openHostSection, selectSettingsHost } from "../support/helpers/settings";
const REGISTRY_KEY = "@paseo:daemon-registry";
const SEED_NONCE_KEY = "@paseo:e2e-seed-nonce";
const DISABLE_DEFAULT_SEED_ONCE_KEY = "@paseo:e2e-disable-default-seed-once";
// What a build with a connection kind this one doesn't know leaves in the registry: an extra
// connection on a host this build can reach, and a host reached only through it.
const UNKNOWN_CONNECTION = { id: "future:garage", type: "futureKind", address: "garage" };
const UNKNOWN_HOST = {
serverId: "srv_e2e_unknown_connection_host",
label: "Unknown connection host",
connections: [{ id: "future:roof", type: "futureKind", address: "roof" }],
preferredConnectionId: "future:roof",
};
const OFFLINE_HOST = {
serverId: "srv_e2e_saved_offline_host",
label: "Saved offline host",
password: "e2e-fake-password",
connections: [{ id: "direct:127.0.0.1:59999", type: "directTcp", endpoint: "127.0.0.1:59999" }],
preferredConnectionId: "direct:127.0.0.1:59999",
};
interface StoredHost {
serverId: string;
label?: string;
password?: string;
connections: unknown[];
}
async function addUnreadableEntriesAndReload(page: Page): Promise<void> {
await page.evaluate(
({ keys, primaryServerId, unknownConnection, offlineHost, unknownHost }) => {
const nonce = localStorage.getItem(keys.nonce);
if (!nonce) {
throw new Error("Expected the e2e seed nonce before overriding the host registry.");
}
const registry: StoredHost[] = JSON.parse(localStorage.getItem(keys.registry) ?? "[]");
registry
.find((host) => host.serverId === primaryServerId)
?.connections.push(unknownConnection);
registry.push(offlineHost, unknownHost);
localStorage.setItem(keys.registry, JSON.stringify(registry));
localStorage.setItem(keys.disableSeedOnce, nonce);
},
{
keys: {
registry: REGISTRY_KEY,
nonce: SEED_NONCE_KEY,
disableSeedOnce: DISABLE_DEFAULT_SEED_ONCE_KEY,
},
primaryServerId: getServerId(),
unknownConnection: UNKNOWN_CONNECTION,
offlineHost: OFFLINE_HOST,
unknownHost: UNKNOWN_HOST,
},
);
await page.reload();
}
async function readStoredRegistry(page: Page): Promise<StoredHost[] | null> {
return page.evaluate((key) => JSON.parse(localStorage.getItem(key) ?? "null"), REGISTRY_KEY);
}
async function readStoredHost(page: Page, serverId: string): Promise<StoredHost | undefined> {
return (await readStoredRegistry(page))?.find((host) => host.serverId === serverId);
}
test("saved hosts survive a registry entry this build can't read, and saving keeps it", async ({
page,
}) => {
await gotoAppShell(page);
await addUnreadableEntriesAndReload(page);
await test.step("both readable hosts are listed", async () => {
await page.getByTestId("sidebar-hosts-trigger").click();
await expect(page.getByTestId(`sidebar-host-row-${getServerId()}`)).toBeVisible();
await expect(page.getByTestId(`sidebar-host-row-${OFFLINE_HOST.serverId}`)).toBeVisible();
await expect(page.getByTestId(`sidebar-host-row-${UNKNOWN_HOST.serverId}`)).toHaveCount(0);
await page.keyboard.press("Escape");
});
await test.step("renaming a host keeps its password and the entries it can't read", async () => {
await openSettings(page);
await selectSettingsHost(page, OFFLINE_HOST.serverId);
await openHostSection(page, OFFLINE_HOST.serverId, "host");
await renameHostFromSettings(page, "Renamed offline host");
await expect
.poll(() => readStoredHost(page, OFFLINE_HOST.serverId))
.toMatchObject({ label: "Renamed offline host", password: OFFLINE_HOST.password });
const stored = await readStoredRegistry(page);
expect(stored?.map((host) => host.serverId)).toEqual([
getServerId(),
OFFLINE_HOST.serverId,
UNKNOWN_HOST.serverId,
]);
expect(stored?.[0]?.connections).toContainEqual(UNKNOWN_CONNECTION);
expect(stored?.[2]).toEqual(UNKNOWN_HOST);
});
});
@@ -33,6 +33,8 @@ import {
expectNoHostPasswordControls,
removeHostFromHostPage,
addDirectHostFromSettings,
expectAddHostFieldDrawnAsInput,
selectHostConnectionType,
expectHostOnlineWithoutError,
expectIdleAgentRelease,
editRestartRecoveryPrompt,
@@ -307,6 +309,24 @@ async function closeAddHostAndChangeTheme(page: import("@playwright/test").Page)
await page.keyboard.press("Control+Alt+t");
}
test("Add host draws its text fields as bordered inputs", async ({ page }) => {
await gotoAppShell(page);
await test.step("the pairing link field", async () => {
await openSidebarAddHost(page);
await selectHostConnectionType(page, "relay");
await expectAddHostFieldDrawnAsInput(page, "pair-link-input");
await page.getByTestId("pair-link-cancel").click();
});
await test.step("the direct connection fields", async () => {
await selectHostConnectionType(page, "direct");
await expectAddHostFieldDrawnAsInput(page, "direct-host-input");
await expectAddHostFieldDrawnAsInput(page, "direct-port-input");
await expectAddHostFieldDrawnAsInput(page, "direct-password-input");
});
});
test("sidebar Add host completes without navigating", async ({ page }) => {
await gotoAppShell(page);
await expect(page).toHaveURL(/\/open-project$/);
@@ -110,6 +110,7 @@ test.describe("Sidebar items in Appearance settings", () => {
await test.step("the sidebar starts in the default order", async () => {
await expectSidebarOrder(page, ["new-workspace", "history", "search", "schedules"]);
await expect(page.locator('[data-testid="sidebar-nav-separator"]:visible')).toHaveCount(1);
});
await test.step("the Sidebar section lists every item in the same order", async () => {
@@ -195,6 +196,9 @@ test.describe("Sidebar items in Appearance settings", () => {
await expectSidebarItemHidden(page, "history");
await expectSidebarItemHidden(page, "search");
await expectSidebarItemHidden(page, "schedules");
// Nothing is left above the Workspaces section: no drag strip, no empty divider.
await expect(page.locator('[data-testid="sidebar-nav-drag-strip"]:visible')).toHaveCount(0);
await expect(page.locator('[data-testid="sidebar-nav-separator"]:visible')).toHaveCount(0);
});
});
@@ -73,35 +73,36 @@ function labelRow(page: import("@playwright/test").Page, name: string) {
return page.getByTestId(`workspace-label-picker-row-${name}`);
}
async function box(locator: import("@playwright/test").Locator) {
const measured = await locator.boundingBox();
if (!measured) throw new Error("expected a visible element to measure");
return measured;
}
async function size(locator: import("@playwright/test").Locator) {
await settled(locator);
const { width, height } = await box(locator);
const { width, height } = await settled(locator);
return { width, height };
}
/**
* Waits until an element stops moving.
* Waits until an element is on screen and stops moving, and returns where it settled.
*
* The flyout scales in and the sidebar behind it re-lays out as the filter changes, so a rail
* measured mid-animation is not a rail — and a measurement built from two `boundingBox()` calls
* would take its two halves from two different frames.
* would take its two halves from two different frames. A row that has not been laid out yet has
* no box at all; that is not settled either, so the poll keeps waiting instead of failing.
*/
async function settled(locator: import("@playwright/test").Locator) {
let previous = "";
const last: { box: Awaited<ReturnType<typeof locator.boundingBox>>; key: string | null } = {
box: null,
key: null,
};
await expect
.poll(async () => {
const current = JSON.stringify(await box(locator));
const stable = current === previous;
previous = current;
const current = await locator.boundingBox();
const key = current ? JSON.stringify(current) : null;
const stable = key !== null && key === last.key;
last.box = current;
last.key = key;
return stable;
})
.toBe(true);
if (!last.box) throw new Error("a settled element has a box");
return last.box;
}
async function expectAssigned(
@@ -6,7 +6,7 @@ import {
type ChildProcess,
type SpawnOptions,
} from "node:child_process";
import { mkdtemp, rm, writeFile } from "node:fs/promises";
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import net from "node:net";
import { tmpdir } from "node:os";
import path from "node:path";
@@ -59,7 +59,17 @@ export async function getAvailableHostDaemonPort(): Promise<number> {
return port;
}
async function waitForServer(port: number, child: ChildProcess): Promise<void> {
/**
* Resolves once this daemon answers on its port. An open TCP port is not
* enough: the port is released before the daemon binds it, and whatever takes
* it in between also accepts connections while the daemon exits with
* EADDRINUSE. Only the daemon's own status reports its server id.
*/
async function waitForServer(
port: number,
child: ChildProcess,
identity: { serverId: string; paseoHome: string },
): Promise<void> {
const deadline = Date.now() + 90_000;
let lastError: unknown = null;
@@ -70,22 +80,13 @@ async function waitForServer(port: number, child: ChildProcess): Promise<void> {
);
}
try {
await new Promise<void>((resolve, reject) => {
const socket = net.connect(port, "127.0.0.1", () => {
socket.end();
resolve();
});
socket.setTimeout(1_000, () => {
socket.destroy();
reject(new Error(`Connection timed out to isolated daemon port ${port}`));
});
socket.on("error", reject);
});
return;
const serverId = await readServerId(port, identity.paseoHome);
if (serverId === identity.serverId) return;
lastError = new Error(`Port ${port} is served by ${serverId}, not ${identity.serverId}`);
} catch (error) {
lastError = error;
await new Promise((resolve) => setTimeout(resolve, 100));
}
await new Promise((resolve) => setTimeout(resolve, 100));
}
throw new Error(
@@ -95,6 +96,25 @@ async function waitForServer(port: number, child: ChildProcess): Promise<void> {
);
}
/**
* Reads the server id from the daemon's status route. The route needs a bearer
* on a password-protected daemon; the daemon accepts the local credential it
* writes into its home before listening, as the CLI does for local status.
*/
async function readServerId(port: number, paseoHome: string): Promise<string> {
const localCredential = await readFile(path.join(paseoHome, "local-credential"), "utf8").then(
(token) => token.trim(),
() => null,
);
const response = await fetch(`http://127.0.0.1:${port}/api/status`, {
headers: localCredential ? { authorization: `Bearer ${localCredential}` } : {},
signal: AbortSignal.timeout(1_000),
});
if (!response.ok) throw new Error(`Status request to port ${port} returned ${response.status}`);
const status = (await response.json()) as { serverId?: unknown };
return String(status.serverId);
}
function withMutableRelay(
config: NonNullable<IsolatedHostDaemonOptions["config"]>,
relay: NonNullable<IsolatedHostDaemonOptions["mutableRelay"]>,
@@ -221,7 +241,7 @@ export async function startIsolatedHostDaemon(
});
try {
await waitForServer(port, spawned);
await waitForServer(port, spawned, { serverId, paseoHome });
return spawned;
} catch (error) {
throw new Error(
@@ -223,6 +223,14 @@ export async function addDirectHostFromSettings(
await expect(page.getByTestId("add-host-modal")).toHaveCount(0, { timeout: 30_000 });
}
export async function expectAddHostFieldDrawnAsInput(page: Page, testId: string): Promise<void> {
const field = page.getByTestId(testId);
await expect(field).toBeVisible();
await expect(field).toHaveCSS("border-top-width", "1px");
await expect(field).not.toHaveCSS("padding-left", "0px");
await expect(field).not.toHaveCSS("background-color", "rgba(0, 0, 0, 0)");
}
export async function toggleHostAdvanced(page: Page): Promise<void> {
await page.getByTestId("direct-host-advanced-toggle").click();
}
@@ -17,6 +17,13 @@ import { isNative } from "@/constants/platform";
* On macOS, Electron handles edge resize natively.
*/
/**
* Marks a scroll viewport as window content: it and its descendants emit no window
* regions, because Electron does not clip app-region rects to scroll viewports.
* See the `[data-window-content]` rule in public/index.html.
*/
export const WINDOW_CONTENT_DATASET = { "window-content": "" };
export const titlebarDragSurfaceStyle: React.CSSProperties = {
cursor: "default",
// @ts-expect-error — WebkitAppRegion is not in CSSProperties
+89 -43
View File
@@ -9,7 +9,16 @@ import {
type LucideIcon,
} from "lucide-react-native";
import { useTranslation } from "react-i18next";
import { memo, useCallback, useEffect, useMemo, useRef, useState, type RefObject } from "react";
import {
memo,
useCallback,
useEffect,
useMemo,
useRef,
useState,
type ReactNode,
type RefObject,
} from "react";
import {
Pressable,
ScrollView,
@@ -19,12 +28,19 @@ import {
View,
type LayoutChangeEvent,
} from "react-native";
import { Gesture, ScrollView as GHScrollView } from "react-native-gesture-handler";
import {
Gesture,
type GestureType,
ScrollView as GHScrollView,
} from "react-native-gesture-handler";
import Animated, { runOnJS, useAnimatedStyle, useSharedValue } from "react-native-reanimated";
import { scheduleOnRN } from "react-native-worklets";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { StyleSheet, useUnistyles } from "react-native-unistyles";
import { TitlebarDragRegion } from "@/components/desktop/titlebar-drag-region";
import {
TitlebarDragRegion,
WINDOW_CONTENT_DATASET,
} from "@/components/desktop/titlebar-drag-region";
import { SidebarCloseButton } from "@/components/headers/sidebar-close-button";
import {
resolveDesktopSidebarInsetLeft,
@@ -39,7 +55,7 @@ import { HostPicker } from "@/components/hosts/host-picker";
import { SidebarDisplayPreferencesMenu } from "@/components/sidebar/display-preferences/menu";
import { SidebarSeparator } from "@/components/sidebar/sidebar-separator";
import { SidebarToastRegion } from "@/components/sidebar/sidebar-toast-region";
import { SidebarNavRows } from "@/components/sidebar/sidebar-nav-rows";
import { SidebarNavRows, useVisibleSidebarNavItems } from "@/components/sidebar/sidebar-nav-rows";
import { SidebarFooterIconHighlight } from "@/components/sidebar/sidebar-footer-icon-highlight";
import { SidebarHelpMenu } from "@/components/sidebar/sidebar-help-menu";
import { SidebarFooterOverflowMenu } from "@/components/sidebar/sidebar-footer-overflow-menu";
@@ -622,29 +638,7 @@ function MobileSidebar({
>
<View style={styles.sidebarContent} pointerEvents="auto">
<WindowChromeSafeArea placement="below" />
{platformIsNative ? (
<GHScrollView
// Same contract as the workspace list: vertical drags scroll the nav
// block, a clear horizontal intent still activates the close pan.
simultaneousHandlers={closeGestureRef}
style={styles.mobileNavScroll}
showsVerticalScrollIndicator={false}
alwaysBounceVertical={false}
testID="sidebar-nav-scroll"
>
{navRows}
</GHScrollView>
) : (
<ScrollView
style={styles.mobileNavScroll}
showsVerticalScrollIndicator={false}
alwaysBounceVertical={false}
testID="sidebar-nav-scroll"
>
{navRows}
</ScrollView>
)}
<SidebarSeparator />
<SidebarNavScroll closeGestureRef={closeGestureRef}>{navRows}</SidebarNavScroll>
<SidebarViewSlot dismiss={handleWorkspacePress}>
<SidebarToastRegion active={active}>
@@ -689,6 +683,47 @@ function MobileSidebar({
);
}
interface SidebarNavScrollProps {
closeGestureRef: RefObject<GestureType | undefined>;
/** Web only: the viewport emits no window regions (see WINDOW_CONTENT_DATASET). */
windowContent?: boolean;
children: ReactNode;
}
// The capped, scrolling nav block shared by the mobile and desktop sidebars, with the
// divider below it. The divider is a sibling because Unistyles does not patch the
// gesture-handler ScrollView.
function SidebarNavScroll({ closeGestureRef, windowContent, children }: SidebarNavScrollProps) {
return (
<>
{platformIsNative ? (
<GHScrollView
// Same contract as the workspace list: vertical drags scroll the nav
// block, a clear horizontal intent still activates the close pan.
simultaneousHandlers={closeGestureRef}
style={styles.navScroll}
showsVerticalScrollIndicator={false}
alwaysBounceVertical={false}
testID="sidebar-nav-scroll"
>
{children}
</GHScrollView>
) : (
<ScrollView
dataSet={windowContent ? WINDOW_CONTENT_DATASET : undefined}
style={styles.navScroll}
showsVerticalScrollIndicator={false}
alwaysBounceVertical={false}
testID="sidebar-nav-scroll"
>
{children}
</ScrollView>
)}
<SidebarSeparator testID="sidebar-nav-separator" />
</>
);
}
function DesktopSidebar({
theme,
workspaceGroups,
@@ -809,12 +844,14 @@ function DesktopSidebar({
],
[insetsTop, insets.bottom, insets.left, overlay, divisionLayout],
);
// Below the window controls' row, or in the top band's place, the first row starts flush.
const inTopBand = useTopBand() !== null;
const sidebarHeaderGroupStyle = useMemo(
() => [styles.sidebarHeaderGroup, (ownsTopLeft || inTopBand) && styles.sidebarHeaderGroupFlush],
[ownsTopLeft, inTopBand],
);
// Windows and Linux draw their window controls top-right, so the sidebar has no chrome
// row there. The strip above the scrolling rows is then its window drag surface.
const showsChromeRow = ownsTopLeft || Boolean(DEV_BUILD_LABEL);
// With every top item hidden the sidebar starts at the Workspaces section, as before the
// nav scroller existed: no strip above it and no divider below it.
const hasNavRows = useVisibleSidebarNavItems().length > 0;
const showsDragStrip = hasNavRows && !showsChromeRow && !inTopBand;
return (
<MobilePanelOverlay
panel="agent-list"
@@ -825,7 +862,7 @@ function DesktopSidebar({
<Animated.View style={desktopSidebarStyle}>
<View style={desktopSidebarBorderStyle}>
<View style={styles.sidebarDragArea}>
{ownsTopLeft || DEV_BUILD_LABEL ? (
{showsChromeRow ? (
<View style={styles.desktopChromeRow}>
<TitlebarDragRegion />
{DEV_BUILD_LABEL ? (
@@ -842,11 +879,21 @@ function DesktopSidebar({
</View>
) : null}
</View>
) : (
<TitlebarDragRegion />
)}
<SidebarNavRows style={sidebarHeaderGroupStyle} onBeforeNavigate={closeSidebar} />
) : null}
{showsDragStrip ? (
<View style={styles.desktopDragStrip} testID="sidebar-nav-drag-strip">
<TitlebarDragRegion />
</View>
) : null}
</View>
{/* The drag overlay stays above this viewport: Electron does not clip
app-region rects to scroll viewports, so a scrolled-out row would
still claim its no-drag rect. */}
{hasNavRows ? (
<SidebarNavScroll closeGestureRef={closeGestureRef} windowContent>
<SidebarNavRows style={styles.sidebarHeaderGroup} onBeforeNavigate={closeSidebar} />
</SidebarNavScroll>
) : null}
<SidebarViewSlot dismiss={closeSidebar}>
<SidebarToastRegion active={active}>
@@ -935,19 +982,18 @@ const staticStyles = RNStyleSheet.create({
});
const styles = StyleSheet.create((theme) => ({
// The rows start flush: the chrome row, drag strip, or top band above them gives the inset.
sidebarHeaderGroup: {
paddingTop: theme.spacing[2],
gap: 2,
paddingBottom: theme.spacing[1.5],
borderBottomWidth: 1,
borderBottomColor: theme.colors.border,
},
sidebarHeaderGroupFlush: {
paddingTop: 0,
desktopDragStrip: {
position: "relative",
height: theme.spacing[2],
},
// The nav block caps at half the sidebar; a long item list scrolls inside the
// cap instead of crowding the workspace list off a short screen.
mobileNavScroll: {
navScroll: {
flexGrow: 0,
flexShrink: 1,
maxHeight: "50%",
@@ -35,14 +35,19 @@ interface SidebarNavRowsProps extends SidebarNavRowProps {
firstRowTrailing?: ReactNode;
}
/** The top-level items the user keeps visible, in display order. */
export function useVisibleSidebarNavItems() {
const { items } = useSidebarNavItems("header");
return useMemo(() => items.filter((item) => item.visible), [items]);
}
/**
* Top-level sidebar navigation, ordered and filtered by the user's
* `sidebarNavItems` preference. Renders nothing — not even the bordered group
* wrapper — when every item is hidden and there is no `firstRowTrailing`.
*/
export function SidebarNavRows({ style, onBeforeNavigate, firstRowTrailing }: SidebarNavRowsProps) {
const { items } = useSidebarNavItems("header");
const visibleItems = useMemo(() => items.filter((item) => item.visible), [items]);
const visibleItems = useVisibleSidebarNavItems();
const groupRef = useRef<View | null>(null);
if (visibleItems.length === 0 && !firstRowTrailing) return null;
@@ -431,7 +431,7 @@ function AddHostModalContent({ visible, onClose, onCancel, onSaved }: AddHostMod
<View style={styles.portRow}>
<View style={hostFieldStyle}>
<Text style={styles.label}>{t("pairing.direct.fields.host")}</Text>
<ThemedAdaptiveTextInput
<AdaptiveTextInput
testID="direct-host-input"
nativeID="direct-host-input"
accessibilityLabel={t("pairing.direct.fields.host")}
@@ -449,7 +449,7 @@ function AddHostModalContent({ visible, onClose, onCancel, onSaved }: AddHostMod
</View>
<View style={portFieldStyle}>
<Text style={styles.label}>{t("pairing.direct.fields.port")}</Text>
<ThemedAdaptiveTextInput
<AdaptiveTextInput
testID="direct-port-input"
nativeID="direct-port-input"
accessibilityLabel={t("pairing.direct.fields.port")}
@@ -491,7 +491,7 @@ function AddHostModalContent({ visible, onClose, onCancel, onSaved }: AddHostMod
<View style={styles.field}>
<Text style={styles.label}>{t("pairing.direct.fields.password")}</Text>
<View style={styles.passwordRow}>
<ThemedAdaptiveTextInput
<AdaptiveTextInput
testID="direct-password-input"
nativeID="direct-password-input"
accessibilityLabel={t("pairing.direct.fields.password")}
@@ -539,7 +539,7 @@ function AddHostModalContent({ visible, onClose, onCancel, onSaved }: AddHostMod
<Text style={styles.advancedText}>{t("pairing.direct.advanced.label")}</Text>
</PressHighlight>
{isAdvancedOpen ? (
<ThemedAdaptiveTextInput
<AdaptiveTextInput
testID="direct-host-uri-input"
nativeID="direct-host-uri-input"
accessibilityLabel={t("pairing.direct.fields.connectionUri")}
@@ -598,7 +598,3 @@ const ThemedChevronRight = withUnistyles(ChevronRight, (theme) => ({
const ThemedEye = withUnistyles(Eye, (theme) => ({ color: theme.colors.foregroundMuted }));
const ThemedEyeOff = withUnistyles(EyeOff, (theme) => ({ color: theme.colors.foregroundMuted }));
const ThemedAdaptiveTextInput = withUnistyles(AdaptiveTextInput, (theme) => ({
placeholderTextColor: theme.colors.foregroundMuted,
}));
@@ -212,7 +212,7 @@ function PairLinkModalContent({
<View style={styles.field}>
<Text style={styles.label}>{t("pairing.link.label")}</Text>
<ThemedAdaptiveTextInput
<AdaptiveTextInput
ref={inputRef}
initialValue={initialUrl}
testID="pair-link-input"
@@ -234,11 +234,13 @@ function PairLinkModalContent({
<Text style={styles.label}>
{t("pairing.hostPassword.title", { host: parsedHostLabel(offerUrlRef.current) })}
</Text>
<ThemedAdaptiveTextInput
<AdaptiveTextInput
testID="pair-link-password-input"
resetKey={`pair-link-password-${passwordResetKey}`}
accessibilityLabel={t("pairing.hostPassword.label")}
placeholder={t("pairing.hostPassword.label")}
onChangeText={setPassword}
autoFocus
secureTextEntry
style={styles.input}
/>
@@ -275,7 +277,3 @@ function PairLinkModalContent({
}
const ThemedLink = withUnistyles(Link, (theme) => ({ color: theme.colors.accentForeground }));
const ThemedAdaptiveTextInput = withUnistyles(AdaptiveTextInput, (theme) => ({
placeholderTextColor: theme.colors.foregroundMuted,
}));
@@ -2256,6 +2256,59 @@ describe("HostRuntimeController", () => {
});
});
const REGISTRY_KEY = "@paseo:daemon-registry";
const futureConnection = { id: "future:1", type: "futureKind", address: "future.example.com" };
const directA: HostConnection = {
id: "direct:lan-a:6767",
type: "directTcp",
endpoint: "lan-a:6767",
};
const directB: HostConnection = {
id: "direct:lan-b:6767",
type: "directTcp",
endpoint: "lan-b:6767",
};
// What a build with a connection kind this one doesn't know leaves behind: an extra connection
// on a host this build can reach, and a host reached only through it.
const storedWithUnreadableEntries = [
{
...makeHost({ serverId: "srv_a", password: "secret-a" }),
connections: [futureConnection, directA],
},
makeHost({ serverId: "srv_b", password: "secret-b", connections: [directB] }),
{ serverId: "srv_future", label: "future host", connections: [futureConnection] },
];
async function bootWithRegistry(registry: string): Promise<{
store: HostRuntimeStore;
storage: HostRuntimeStorage;
}> {
const storage = createMemoryHostRuntimeStorage({
[REGISTRY_KEY]: registry,
"@paseo:e2e": "1",
});
const store = new HostRuntimeStore({
storage,
deps: {
createClient: () => new FakeDaemonClient() as unknown as DaemonClient,
connectToDaemon: async ({ host }) => ({
client: makeConnectedProbeClient(5) as unknown as DaemonClient,
serverId: host.serverId,
hostname: host.label ?? null,
}),
getClientId: async () => "cid_test_runtime",
},
revokePushNotifications: async () => undefined,
});
await store.boot();
return { store, storage };
}
async function readRegistry(storage: HostRuntimeStorage): Promise<unknown> {
const raw = await storage.getItem(REGISTRY_KEY);
return raw === null ? null : JSON.parse(raw);
}
describe("HostRuntimeStore", () => {
function gatewayRecoveryFixture() {
const parent = new FakeDaemonClient();
@@ -2686,6 +2739,98 @@ describe("HostRuntimeStore", () => {
session.clearSession(host.serverId);
});
it("keeps readable hosts when the registry holds entries this build can't read", async () => {
const { store, storage } = await bootWithRegistry(JSON.stringify(storedWithUnreadableEntries));
expect(store.getHosts().map((host) => [host.serverId, host.password])).toEqual([
["srv_a", "secret-a"],
["srv_b", "secret-b"],
]);
expect(store.getHosts()[0]?.connections.map((connection) => connection.id)).toEqual([
directA.id,
]);
expect(await readRegistry(storage)).toEqual(storedWithUnreadableEntries);
store.syncHosts([]);
});
it("keeps the entries it can't read when it saves the registry", async () => {
const { store, storage } = await bootWithRegistry(JSON.stringify(storedWithUnreadableEntries));
await store.renameHost("srv_b", "renamed");
expect(await readRegistry(storage)).toMatchObject([
{
serverId: "srv_a",
password: "secret-a",
connections: [{ id: directA.id }, futureConnection],
},
{ serverId: "srv_b", password: "secret-b", label: "renamed" },
storedWithUnreadableEntries[2],
]);
store.syncHosts([]);
});
it("moves a stored connection password to its host and keeps the connection it can't read", async () => {
const { store, storage } = await bootWithRegistry(
JSON.stringify([
{
serverId: "srv_legacy",
connections: [
{ type: "directTcp", endpoint: "lan-a:6767", password: "old-secret" },
futureConnection,
],
},
]),
);
expect(store.getHosts().map((host) => [host.serverId, host.password])).toEqual([
["srv_legacy", "old-secret"],
]);
await vi.waitFor(async () =>
expect(await readRegistry(storage)).toMatchObject([
{ serverId: "srv_legacy", password: "old-secret" },
]),
);
expect(await readRegistry(storage)).toMatchObject([
{ connections: [{ ...directA, useTls: false }, futureConnection] },
]);
const [written] = (await readRegistry(storage)) as Array<{ connections: unknown[] }>;
expect(written?.connections[0]).not.toHaveProperty("password");
store.syncHosts([]);
});
it("forgets an entry it can't read once that host is paired again and removed", async () => {
const { store, storage } = await bootWithRegistry(
JSON.stringify([{ serverId: "srv_future", connections: [futureConnection] }]),
);
expect(store.getHosts()).toEqual([]);
await store.upsertDirectConnection({ serverId: "srv_future", endpoint: directA.endpoint });
await vi.waitFor(async () =>
expect(await readRegistry(storage)).toMatchObject([
{ serverId: "srv_future", connections: [{ id: directA.id }] },
]),
);
await store.removeHost("srv_future");
expect(await readRegistry(storage)).toEqual([]);
store.syncHosts([]);
});
it("copies a registry that isn't JSON aside instead of deleting it", async () => {
const { store, storage } = await bootWithRegistry("{not json");
expect(store.getHosts()).toEqual([]);
expect(await storage.getItem(`${REGISTRY_KEY}:unreadable`)).toBe("{not json");
expect(await storage.getItem(REGISTRY_KEY)).toBe("{not json");
store.syncHosts([]);
});
it("marks the host registry loaded after boot reads storage", async () => {
const previousOverride = process.env.EXPO_PUBLIC_LOCAL_DAEMON;
process.env.EXPO_PUBLIC_LOCAL_DAEMON = "not-an-endpoint";
+37 -28
View File
@@ -17,14 +17,16 @@ import {
import {
connectionFromListen,
createRemoteSshHostConnection,
normalizeStoredHostProfile,
forgetUnreadableHost,
pinRelayProtectedSecurityInProfiles,
readHostRegistry,
upsertHostConnectionInProfiles,
registryHasConnection,
relayConnectionFromOffer,
StoredHostRegistrySchema,
writeHostRegistry,
type HostConnection,
type HostProfile,
type UnreadableHostEntries,
} from "@/types/host-connection";
import { defaultHostAppearance, type HostBadgeDisplay, type HostColor } from "@/hosts/appearance";
import {
@@ -43,7 +45,7 @@ import { isWeb } from "@/constants/platform";
import { connectToDaemon, getConnectionAuthFailureReason } from "@/utils/test-daemon-connection";
import { getOrCreateClientId } from "@/utils/client-id";
import { z } from "zod";
import { readValidatedJson, readValidatedString } from "@/storage/validated-storage";
import { readValidatedString } from "@/storage/validated-storage";
import {
selectBestConnection,
type ConnectionCandidate,
@@ -1692,6 +1694,7 @@ export class HostRuntimeStore {
private hostListVersion = 0;
private hostRegistryLoaded = false;
private hosts: HostProfile[] = [];
private unreadableHosts: UnreadableHostEntries = { hosts: [], connectionsByServerId: new Map() };
private hostAppearanceMutationTail: Promise<void> = Promise.resolve();
private hostRegistryStatus: HostRegistryStatus = "loading";
private deps: HostRuntimeControllerDeps;
@@ -1799,32 +1802,17 @@ export class HostRuntimeStore {
let shouldPersistHosts = false;
let profiles: HostProfile[] = [];
try {
const stored = await readValidatedJson(
this.storage,
REGISTRY_STORAGE_KEY,
StoredHostRegistrySchema,
);
const stored = await this.readStoredRegistry();
if (stored) {
const normalizedProfiles: HostProfile[] = [];
for (const entry of stored) {
const profile = normalizeStoredHostProfile(entry);
if (!profile) {
await this.storage.removeItem(REGISTRY_STORAGE_KEY);
normalizedProfiles.length = 0;
break;
}
// COMPAT(connectionPassword): added in v0.9.1, remove after 2027-03-24 with stored-password migration.
if (
entry.connections.some(
(connection) => connection.type === "directTcp" && connection.password,
)
) {
shouldPersistHosts = true;
}
normalizedProfiles.push(profile);
// An entry this build can't read skips only that host or connection, and stays stored.
const registry = readHostRegistry(stored);
this.unreadableHosts = registry.unreadable;
// COMPAT(connectionPassword): added in v0.9.1, remove after 2027-03-24 with stored-password migration.
if (registry.movedConnectionPassword) {
shouldPersistHosts = true;
}
profiles = normalizedProfiles.filter((entry) => !isPlaceholderServerId(entry.serverId));
if (profiles.length !== normalizedProfiles.length) {
profiles = registry.hosts.filter((entry) => !isPlaceholderServerId(entry.serverId));
if (profiles.length !== registry.hosts.length) {
shouldPersistHosts = true;
}
}
@@ -2320,6 +2308,7 @@ export class HostRuntimeStore {
async removeHost(serverId: string): Promise<void> {
await this.revokePushNotifications({ client: this.getClient(serverId), serverId });
const remaining = this.hosts.filter((daemon) => daemon.serverId !== serverId);
this.unreadableHosts = forgetUnreadableHost(this.unreadableHosts, serverId);
this.setHostsAndSync(remaining);
await this.persistHosts();
}
@@ -2408,7 +2397,27 @@ export class HostRuntimeStore {
}
private async persistHosts(hosts = this.hosts): Promise<void> {
await this.storage.setItem(REGISTRY_STORAGE_KEY, JSON.stringify(hosts));
await this.storage.setItem(
REGISTRY_STORAGE_KEY,
JSON.stringify(writeHostRegistry(hosts, this.unreadableHosts)),
);
}
/**
* Reads the stored registry without removing it. A value that isn't a JSON array is copied to
* `<key>:unreadable` first, because the next save overwrites the key.
*/
private async readStoredRegistry(): Promise<unknown[] | null> {
const raw = await this.storage.getItem(REGISTRY_STORAGE_KEY);
if (raw === null) return null;
try {
const value: unknown = JSON.parse(raw);
if (Array.isArray(value)) return value;
} catch {
// Not JSON: copied aside below.
}
await this.storage.setItem(`${REGISTRY_STORAGE_KEY}:unreadable`, raw);
return null;
}
private emitHostList(): void {
@@ -21,8 +21,7 @@ import {
import { useLocalDaemonServerId } from "@/hooks/use-is-local-daemon";
import { PairDeviceModal } from "@/desktop/components/pair-device-modal";
import { buildSettingsHostSectionRoute } from "@/utils/host-routes";
const WINDOW_CONTENT_DATASET = { "window-content": "" };
import { WINDOW_CONTENT_DATASET } from "@/components/desktop/titlebar-drag-region";
export function OpenProjectScreen() {
const { t } = useTranslation();
@@ -106,6 +106,79 @@ describe("workspace-pane-state", () => {
});
});
it("does not locate a file by an id retained from a previous target", () => {
const layout: WorkspaceLayout = {
root: {
kind: "pane",
pane: {
id: "main",
tabIds: ["file_/repo/a.ts", "agent_agent-a"],
focusedTabId: "agent_agent-a",
},
},
focusedPaneId: "main",
};
const tabs = [
createTab("file_/repo/a.ts", { kind: "file", path: "/repo/b.ts" }),
createTab("agent_agent-a", { kind: "agent", agentId: "agent-a" }),
];
const target: WorkspaceTab["target"] = { kind: "file", path: "/repo/a.ts" };
expect(resolveSideFileOpenPlacement({ layout, sourcePaneId: "main", tabs, target })).toEqual({
kind: "split-side-pane",
paneId: "main",
});
expect(deriveWorkspacePaneState({ layout, tabs, preferredTarget: target }).activeTabId).toBe(
"agent_agent-a",
);
});
it("matches a retained file instance when only the requested line range differs", () => {
const pane = {
id: "main",
tabIds: ["retained-file", "agent_agent-a"],
focusedTabId: "agent_agent-a",
};
const layout: WorkspaceLayout = { root: { kind: "pane", pane }, focusedPaneId: "main" };
const tabs = [
createTab("retained-file", { kind: "file", path: "/repo/a.ts", lineStart: 2 }),
createTab("agent_agent-a", { kind: "agent", agentId: "agent-a" }),
];
const target: WorkspaceTab["target"] = {
kind: "file",
path: "/repo/a.ts",
lineStart: 12,
lineEnd: 20,
};
expect(resolveSideFileOpenPlacement({ layout, sourcePaneId: "main", tabs, target })).toEqual({
kind: "open-in-source",
});
expect(deriveWorkspacePaneState({ layout, tabs, preferredTarget: target }).activeTabId).toBe(
"retained-file",
);
});
it("prefers an exact file navigation target over another instance of the same resource", () => {
const pane = {
id: "main",
tabIds: ["first", "second"],
focusedTabId: "first",
};
const tabs = [
createTab("first", { kind: "file", path: "/repo/a.ts", lineStart: 2 }),
createTab("second", { kind: "file", path: "/repo/a.ts", lineStart: 12 }),
];
expect(
deriveWorkspacePaneState({
pane,
tabs,
preferredTarget: { kind: "file", path: "/repo/a.ts", lineStart: 12 },
}).activeTabId,
).toBe("second");
});
it("resolves side file opens to an existing file tab", () => {
const layout: WorkspaceLayout = {
root: {
@@ -5,12 +5,9 @@ import {
} from "@/stores/workspace-layout-store";
import type { WorkspaceTab, WorkspaceTabTarget } from "@/workspace-tabs/model";
import type { WorkspaceTabDescriptor } from "@/screens/workspace/workspace-tabs-types";
import {
buildDeterministicWorkspaceTabId,
normalizeWorkspaceTabTarget,
workspaceTabTargetsEqual,
} from "@/workspace-tabs/identity";
import { normalizeWorkspaceTabTarget, workspaceTabTargetsEqual } from "@/workspace-tabs/identity";
import { findAdjacentPane } from "@/utils/split-navigation";
import { panelResourceKey } from "@/panels/panel-manifest";
export interface WorkspaceDerivedTab {
descriptor: WorkspaceTabDescriptor;
@@ -124,8 +121,10 @@ function getActiveTabId(input: {
}
const matchingTab =
input.tabs.find((tab) => workspaceTabTargetsEqual(tab.descriptor.target, preferredTarget)) ??
null;
return matchingTab?.descriptor.tabId ?? buildDeterministicWorkspaceTabId(preferredTarget);
input.tabs.find(
(tab) => panelResourceKey(tab.descriptor.target) === panelResourceKey(preferredTarget),
);
return matchingTab?.descriptor.tabId ?? null;
})();
if (preferredTabId && input.openTabIds.has(preferredTabId)) {
@@ -211,10 +210,8 @@ export function resolveSideFileOpenPlacement(input: {
tabs: WorkspaceTab[];
target: WorkspaceTabTarget;
}): WorkspaceSideFileOpenPlacement {
const targetTabId = buildDeterministicWorkspaceTabId(input.target);
const existingTab = input.tabs.find(
(tab) => tab.tabId === targetTabId || workspaceTabTargetsEqual(tab.target, input.target),
);
const targetKey = panelResourceKey(input.target);
const existingTab = input.tabs.find((tab) => panelResourceKey(tab.target) === targetKey);
if (existingTab) {
return { kind: "open-in-source" };
}
@@ -3,7 +3,7 @@ import type { JsonValue } from "@getpaseo/protocol/agent-types";
import type { WorkspaceTab, WorkspaceTabTarget } from "@/workspace-tabs/model";
import { MIN_SPLIT_SIZE } from "@/stores/workspace-layout-constants";
import { panelResourceKey, panelSupportsHost } from "@/panels/panel-manifest";
import { defaultWorkspaceLayoutIds } from "@/stores/workspace-layout-ids";
import { allocateWorkspaceTabId, defaultWorkspaceLayoutIds } from "@/stores/workspace-layout-ids";
import type { WorkspaceLayoutNodeIdPrefix } from "@/stores/workspace-layout-ids";
import {
buildDeterministicWorkspaceTabId,
@@ -137,6 +137,8 @@ interface OpenTabInLayoutInput {
placement: WorkspaceTabPlacement;
/** Required so a new caller cannot silently opt out of Explorer placement rules. */
explorerSidebarPaneId: string | null;
/** Live sheets share the workspace's panel-instance namespace with its tabs. */
reservedTabIds?: ReadonlySet<string>;
}
interface CreateTabInLayoutInput extends OpenTabInLayoutInput {
@@ -261,6 +263,7 @@ interface ReorderPaneTabsInLayoutInput {
export interface WorkspaceTabReconcileState {
layout: WorkspaceLayout;
reservedTabIds?: ReadonlySet<string>;
pinnedAgentIds?: ReadonlySet<string> | null;
hiddenAgentIds?: ReadonlySet<string> | null;
explorerSidebarPaneId: string | null;
@@ -398,15 +401,11 @@ function normalizeWorkspaceTabs(input: unknown): WorkspaceTab[] {
if (!Array.isArray(input)) {
return [];
}
// Preserve colliding entries until the whole layout can assign each an identity.
const next: WorkspaceTab[] = [];
const seen = new Set<string>();
for (const value of input) {
const tab = normalizeWorkspaceTab(value);
if (!tab || seen.has(tab.tabId)) {
continue;
}
seen.add(tab.tabId);
next.push(tab);
if (tab) next.push(tab);
}
return next;
}
@@ -1022,13 +1021,65 @@ function insertSplitInternal(input: InsertSplitInternalInput): InsertSplitIntern
};
}
function repairDuplicateTabIds(root: SplitNodeInternal): {
root: SplitNodeInternal;
ambiguousIds: ReadonlySet<string>;
} {
const keepers = new Map<string, WorkspaceTab>();
const ambiguousIds = new Set<string>();
for (const tab of collectAllTabs(root)) {
const keeper = keepers.get(tab.tabId);
if (!keeper) {
keepers.set(tab.tabId, tab);
continue;
}
ambiguousIds.add(tab.tabId);
if (
buildDeterministicWorkspaceTabId(tab.target) === tab.tabId &&
buildDeterministicWorkspaceTabId(keeper.target) !== keeper.tabId
) {
keepers.set(tab.tabId, tab);
}
}
if (ambiguousIds.size === 0) return { root, ambiguousIds };
// Reserve every original id before assigning replacements, including hidden panes.
const occupiedIds = new Set(keepers.keys());
function repair(node: SplitNodeInternal): SplitNodeInternal {
if (node.kind === "group") {
return { ...node, group: { ...node.group, children: node.group.children.map(repair) } };
}
const focusedCandidates = node.pane.tabs.filter((tab) => tab.tabId === node.pane.focusedTabId);
const focusedTab =
focusedCandidates.find((tab) => keepers.get(tab.tabId) === tab) ?? focusedCandidates[0];
let focusedTabId = node.pane.focusedTabId;
const tabs = node.pane.tabs.map((tab) => {
if (keepers.get(tab.tabId) === tab) return tab;
const tabId = allocateWorkspaceTabId(
buildDeterministicWorkspaceTabId(tab.target),
occupiedIds,
);
occupiedIds.add(tabId);
if (tab === focusedTab) focusedTabId = tabId;
return { ...tab, tabId };
});
return {
...node,
pane: { ...node.pane, tabs, tabIds: tabs.map((tab) => tab.tabId), focusedTabId },
};
}
return { root: repair(root), ambiguousIds };
}
export function normalizeLayout(layout: unknown): WorkspaceLayout {
if (!layout || typeof layout !== "object") {
return createDefaultLayout();
}
const rawLayout = layout as WorkspaceLayout;
const root = normalizeNode(rawLayout.root) ?? asInternalNode(createDefaultLayout().root);
const { root, ambiguousIds } = repairDuplicateTabIds(
normalizeNode(rawLayout.root) ?? asInternalNode(createDefaultLayout().root),
);
const focusedPaneId =
rawLayout.focusedPaneId === null ? null : trimNonEmpty(rawLayout.focusedPaneId);
const resolvedFocusedPaneId =
@@ -1047,7 +1098,16 @@ export function normalizeLayout(layout: unknown): WorkspaceLayout {
openTabIds: new Set(collectAllTabs(root).map((tab) => tab.tabId)),
});
return parentTabIdByTabId ? { ...normalizedLayout, parentTabIdByTabId } : normalizedLayout;
if (parentTabIdByTabId) {
// A duplicated id cannot identify either end of a parent relationship unambiguously.
for (const [childId, parentId] of Object.entries(parentTabIdByTabId)) {
if (ambiguousIds.has(childId) || ambiguousIds.has(parentId))
delete parentTabIdByTabId[childId];
}
if (Object.keys(parentTabIdByTabId).length > 0)
return { ...normalizedLayout, parentTabIdByTabId };
}
return normalizedLayout;
}
export function findPaneById(root: SplitNode, paneId: string | null | undefined): SplitPane | null {
@@ -1364,7 +1424,9 @@ function insertNewTabIntoPane(
return null;
}
const tabId = input.createTabId();
const occupiedIds = new Set(input.reservedTabIds);
for (const tab of collectAllTabs(layout.root)) occupiedIds.add(tab.tabId);
const tabId = allocateWorkspaceTabId(input.createTabId(), occupiedIds);
const nextTab: WorkspaceTab = {
tabId,
target: input.target,
@@ -2284,6 +2346,7 @@ function openEntityTabWithoutFocusing(input: {
layout: WorkspaceLayout;
target: WorkspaceTabTarget;
explorerSidebarPaneId: string | null;
reservedTabIds: ReadonlySet<string> | undefined;
}): WorkspaceLayout {
return (
insertNewTabIntoPane({
@@ -2292,6 +2355,7 @@ function openEntityTabWithoutFocusing(input: {
now: Date.now(),
placement: AMBIENT_PLACEMENT,
explorerSidebarPaneId: input.explorerSidebarPaneId,
reservedTabIds: input.reservedTabIds,
createTabId: () => buildDeterministicWorkspaceTabId(input.target),
focus: false,
})?.layout ?? input.layout
@@ -2382,6 +2446,7 @@ function addMissingEntityTabs(input: {
hasActivePendingTerminalCreate: boolean;
hasActivePendingDraftCreate: boolean;
explorerSidebarPaneId: string | null;
reservedTabIds: ReadonlySet<string> | undefined;
}): WorkspaceLayout {
const {
autoOpenAgentIds,
@@ -2412,6 +2477,7 @@ function addMissingEntityTabs(input: {
layout: nextLayout,
target: { kind: "agent", agentId },
explorerSidebarPaneId,
reservedTabIds: input.reservedTabIds,
});
currentAgentIds.add(agentId);
}
@@ -2426,6 +2492,7 @@ function addMissingEntityTabs(input: {
layout: nextLayout,
target: { kind: "terminal", terminalId },
explorerSidebarPaneId,
reservedTabIds: input.reservedTabIds,
});
currentTerminalIds.add(terminalId);
}
@@ -2525,6 +2592,7 @@ export function reconcileWorkspaceTabs(
hasActivePendingTerminalCreate: snapshot.hasActivePendingTerminalCreate ?? false,
hasActivePendingDraftCreate: snapshot.hasActivePendingDraftCreate ?? false,
explorerSidebarPaneId: state.explorerSidebarPaneId,
reservedTabIds: state.reservedTabIds,
});
if (reconciledFocusedTabId) {
@@ -11,6 +11,22 @@ function createRandomIdValue(): string {
: `${Date.now()}-${Math.random().toString(16).slice(2)}`;
}
export function createWorkspaceTabInstanceId(): string {
return `tab_${createRandomIdValue()}`;
}
/** A resource-derived id may still belong to a preview slot showing another target. */
export function allocateWorkspaceTabId(
preferredId: string,
occupiedIds: ReadonlySet<string>,
): string {
let tabId = preferredId;
for (let suffix = 2; occupiedIds.has(tabId); suffix += 1) {
tabId = `${preferredId}:${suffix}`;
}
return tabId;
}
export const defaultWorkspaceLayoutIds: WorkspaceLayoutIdSource = {
createNodeId: (prefix) => `${prefix}_${createRandomIdValue()}`,
createFocusRestorationToken: () => `workspace-focus-${createRandomIdValue()}`,
@@ -59,6 +59,84 @@ it("skips unchanged reconciliations and immediately saves real layout changes",
);
});
it("hydrates a saved preview collision and persists the repaired identities", async () => {
const workspaceKey = "server:workspace";
const duplicateId = "file_a.ts";
const values = new Map([
[
"workspace-layout-state",
JSON.stringify({
version: 2,
state: {
layoutByWorkspace: {
[workspaceKey]: {
root: {
kind: "group",
group: {
id: "split",
direction: "horizontal",
sizes: [0.5, 0.5],
children: [
{ id: "main", path: "b.ts" },
{ id: "right", path: "a.ts" },
].map(({ id, path }) => ({
kind: "pane",
pane: {
id,
tabIds: [duplicateId],
focusedTabId: duplicateId,
tabs: [{ tabId: duplicateId, target: { kind: "file", path }, createdAt: 1 }],
},
})),
},
},
focusedPaneId: "right",
},
},
},
}),
],
]);
const storage: StateStorage = {
getItem: (name) => values.get(name) ?? null,
setItem: (name, value) => {
values.set(name, value);
},
removeItem: (name) => {
values.delete(name);
},
};
const store = createWorkspaceLayoutStore(undefined, storage);
await store.persist.rehydrate();
const layout = store.getState().layoutByWorkspace[workspaceKey];
const tabs = collectAllTabs(layout.root);
expect(tabs.filter((tab) => tab.target.kind === "file").map((tab) => tab.tabId)).toEqual([
"file_b.ts",
"file_a.ts",
]);
expect(
deriveWorkspacePaneState({ layout, tabs, paneId: "main" }).activeTab?.descriptor.target,
).toEqual({
kind: "file",
path: "b.ts",
});
expect(
deriveWorkspacePaneState({ layout, tabs, paneId: "right" }).activeTab?.descriptor.target,
).toEqual({
kind: "file",
path: "a.ts",
});
store.getState().focusTab(workspaceKey, "file_b.ts");
expect(store.getState().layoutByWorkspace[workspaceKey].focusedPaneId).toBe("main");
const reloaded = createWorkspaceLayoutStore(undefined, storage);
await reloaded.persist.rehydrate();
expect(reloaded.getState().layoutByWorkspace[workspaceKey]).toEqual(
store.getState().layoutByWorkspace[workspaceKey],
);
});
it("keeps the saved layout when the shell publishes its layout mode before hydration", async () => {
const values = new Map<string, string>();
const storage: StateStorage = {
@@ -906,6 +906,91 @@ describe("workspace-layout-store actions", () => {
).toEqual(override);
});
it("keeps reused file tabs unique and focuses the matching split pane", () => {
const workspaceKey = createWorkspaceKey();
const store = workspaceLayoutStore.getState();
const firstTabId = store.openTab({
workspaceKey,
target: { kind: "file", path: "src/a.ts" },
intent: "reveal",
})!;
store.replaceTab(workspaceKey, firstTabId, { kind: "file", path: "src/b.ts" });
const rightPaneId = store.splitPaneEmpty(workspaceKey, {
targetPaneId: "main",
position: "right",
});
if (!rightPaneId) throw new Error("Expected a right split pane");
const rightTabId = store.openTab({
workspaceKey,
target: { kind: "file", path: "src/a.ts" },
intent: "reveal",
placement: { mode: "pane", paneId: rightPaneId },
})!;
store.openTab({
workspaceKey,
target: { kind: "file", path: "src/b.ts" },
intent: "reveal",
});
store.focusTab(workspaceKey, rightTabId);
const layout = workspaceLayoutStore.getState().layoutByWorkspace[workspaceKey];
const fileTabs = collectAllTabs(layout.root).filter((tab) => tab.target.kind === "file");
expect({
fileTabCount: fileTabs.length,
uniqueFileTabCount: new Set(fileTabs.map((tab) => tab.tabId)).size,
fileTargets: fileTabs.map((tab) => tab.target),
focusedPaneId: layout.focusedPaneId,
}).toEqual({
fileTabCount: 2,
uniqueFileTabCount: 2,
fileTargets: [
{ kind: "file", path: "src/b.ts" },
{ kind: "file", path: "src/a.ts" },
],
focusedPaneId: rightPaneId,
});
});
it("allocates distinct ids across retained tabs, sheets, and background opens", () => {
const workspaceKey = createWorkspaceKey();
const layoutStore = createWorkspaceLayoutStore(workspaceLayoutIds);
const store = layoutStore.getState();
const fileTabId = store.openTab({
workspaceKey,
target: { kind: "file", path: "src/a.ts" },
intent: "reveal",
})!;
store.replaceTab(workspaceKey, fileTabId, { kind: "file", path: "src/b.ts" });
layoutStore.setState({ layoutMode: "compact" });
const sheetTabId = store.openTab({
workspaceKey,
target: { kind: "file", path: "src/a.ts" },
intent: "reveal",
})!;
const selectedSheet = selectSheetTab(layoutStore.getState(), {
workspaceKey,
target: { kind: "file", path: "src/a.ts" },
});
expect(selectedSheet?.tab.tabId).toBe(sheetTabId);
const backgroundTabId = store.openTab({
workspaceKey,
target: { kind: "file", path: "src/a.ts" },
intent: "background",
})!;
expect(new Set([fileTabId, sheetTabId, backgroundTabId]).size).toBe(3);
expect(layoutStore.getState().sheetsByWorkspace[workspaceKey]).toHaveLength(1);
expect(
collectAllTabs(layoutStore.getState().layoutByWorkspace[workspaceKey].root)
.filter((tab) => tab.target.kind === "file")
.map((tab) => tab.target),
).toEqual([
{ kind: "file", path: "src/b.ts" },
{ kind: "file", path: "src/a.ts" },
]);
});
it("keeps the tab instance when a panel receives a same-kind replacement", () => {
const workspaceKey = createWorkspaceKey();
const store = workspaceLayoutStore.getState();
@@ -3200,6 +3285,75 @@ describe("workspace-layout-store actions", () => {
]);
});
it("repairs persisted duplicate ids without losing tabs, pane focus, or unambiguous parents", () => {
const file = (tabId: string, path: string) => ({
tabId,
target: { kind: "file", path },
createdAt: 1,
state: { treeVisible: true, treeWidth: 280 },
});
const leftTabs = [file("file_a.ts", "b.ts"), file("file_a.ts", "c.ts")];
const rightTabs = [
file("file_a.ts", "a.ts"),
file("file_b.ts", "b.ts"),
file("file_b.ts:2", "b.ts"),
file("child", "child.ts"),
file("parent", "parent.ts"),
];
const layout = normalizeLayout({
root: {
kind: "group",
group: {
id: "root",
direction: "horizontal",
sizes: [0.4, 0.6],
children: [
{
kind: "pane",
pane: {
id: "main",
tabs: leftTabs,
tabIds: leftTabs.map((tab) => tab.tabId),
focusedTabId: "file_a.ts",
},
},
{
kind: "pane",
pane: {
id: "right",
tabs: rightTabs,
tabIds: rightTabs.map((tab) => tab.tabId),
focusedTabId: "file_a.ts",
hidden: true,
},
},
],
},
},
focusedPaneId: "main",
parentTabIdByTabId: {
"file_a.ts": "parent",
"file_b.ts": "file_a.ts",
child: "parent",
},
});
const tabs = collectAllTabs(layout.root);
expect(tabs).toHaveLength(7);
expect(new Set(tabs.map((tab) => tab.tabId)).size).toBe(7);
expect(tabs[0]).toEqual({ ...leftTabs[0], tabId: "file_b.ts:3" });
expect(tabs[1]).toEqual({ ...leftTabs[1], tabId: "file_c.ts" });
expect(tabs.slice(2)).toEqual(rightTabs);
expect(findPaneById(layout.root, "main")?.tabIds).toEqual(["file_b.ts:3", "file_c.ts"]);
expect(findPaneById(layout.root, "main")?.focusedTabId).toBe("file_b.ts:3");
expect(findPaneById(layout.root, "right")).toMatchObject({
hidden: true,
focusedTabId: "file_a.ts",
});
expect(layout.parentTabIdByTabId).toEqual({ child: "parent" });
expect(normalizeLayout(layout)).toEqual(layout);
});
it("hydrates duplicate Changes and Pull request instances without collapsing their ids or state", () => {
const tabs = [
{
@@ -5110,6 +5264,50 @@ describe("compact workspace sheet", () => {
expect(sheetTargets(store)).toEqual([fileTarget, nextTarget]);
});
it("reserves a retargeted sheet's id when reconciling a new root agent tab", () => {
seedAgents([
{ id: "root", parentAgentId: null, workspaceId: "sheet-ws" },
{ id: "child-a", parentAgentId: "root", workspaceId: "sheet-ws" },
{ id: "child-b", parentAgentId: "root", workspaceId: "sheet-ws" },
]);
const store = createCompactStore();
store.getState().openTab({
workspaceKey,
target: { kind: "agent", agentId: "child-a" },
intent: "reveal",
});
const sheetId = requireTopSheet(store).tab.tabId;
store.getState().replaceTab(workspaceKey, sheetId, { kind: "agent", agentId: "child-b" });
seedAgents([
{ id: "root", parentAgentId: null, workspaceId: "sheet-ws" },
{ id: "child-a", parentAgentId: null, workspaceId: "sheet-ws" },
{ id: "child-b", parentAgentId: "root", workspaceId: "sheet-ws" },
]);
store.getState().reconcileTabs(workspaceKey, {
agentsHydrated: true,
terminalsHydrated: true,
activeAgentIds: ["root", "child-a", "child-b"],
autoOpenAgentIds: ["child-a"],
knownTerminalIds: ["term-1"],
standaloneTerminalIds: ["term-1"],
});
const tab = collectAllTabs(store.getState().layoutByWorkspace[workspaceKey].root).find(
(candidate) => candidate.target.kind === "agent" && candidate.target.agentId === "child-a",
);
if (!tab) throw new Error("Expected the root agent's tab");
expect(tab.tabId).not.toBe(sheetId);
store.getState().closeTab(workspaceKey, tab.tabId);
expect(requireTopSheet(store).tab).toMatchObject({
tabId: sheetId,
target: { kind: "agent", agentId: "child-b" },
});
expect(
collectAllTabs(store.getState().layoutByWorkspace[workspaceKey].root),
).not.toContainEqual(tab);
});
it("closes the sheet when its agent stops being a subagent, leaving one tab for it", () => {
seedAgents([
{ id: "root", parentAgentId: null, workspaceId: "sheet-ws" },
@@ -7,6 +7,8 @@ import { WorkspaceLayoutPersistedStateSchema } from "./workspace-layout-storage"
import type { JsonValue } from "@getpaseo/protocol/agent-types";
import type { WorkspaceTab, WorkspaceTabTarget } from "@/workspace-tabs/model";
import {
allocateWorkspaceTabId,
createWorkspaceTabInstanceId,
defaultWorkspaceLayoutIds,
type WorkspaceLayoutIdSource,
} from "@/stores/workspace-layout-ids";
@@ -431,14 +433,6 @@ function trimNonEmpty(value: string | null | undefined): string | null {
return trimmed.length > 0 ? trimmed : null;
}
function createWorkspaceTabInstanceId(): string {
const value =
typeof globalThis.crypto?.randomUUID === "function"
? globalThis.crypto.randomUUID()
: `${Date.now()}-${Math.random().toString(16).slice(2)}`;
return `tab_${value}`;
}
function addAgentIdToWorkspaceSet(
state: Record<string, Set<string>>,
workspaceKey: string,
@@ -531,7 +525,10 @@ export function selectExplorerSidebarPaneId(
*/
export function selectSheetTab(
state: Pick<WorkspaceLayoutStore, "layoutMode" | "layoutByWorkspace" | "sheetsByWorkspace">,
input: Pick<OpenWorkspaceTabInput, "workspaceKey" | "target" | "parentTabId">,
input: Pick<OpenWorkspaceTabInput, "workspaceKey" | "target" | "parentTabId"> & {
/** A host outside the sheet stack owns its instance identity. */
preferredTabId?: string;
},
): SheetTab | null {
const workspaceKey = trimNonEmpty(input.workspaceKey);
const target = normalizeWorkspaceTabTarget(input.target);
@@ -539,9 +536,14 @@ export function selectSheetTab(
const policy = resolveSheetPolicy(state, workspaceKey, target, "reveal");
if (!policy) return null;
return placeTargetInSheet({
kept: undefined,
occupiedTabIds: collectWorkspaceTabIds(state, workspaceKey),
kept: input.preferredTabId
? undefined
: getSheets(state, workspaceKey).find(
(sheet) => panelResourceKey(sheet.tab.target) === panelResourceKey(target),
),
target,
intent: "reveal",
createTabId: () => input.preferredTabId ?? buildDeterministicWorkspaceTabId(target),
policy,
parentTabId: resolveOpenParentTabId(state, workspaceKey, input.parentTabId),
state: undefined,
@@ -638,6 +640,7 @@ function getOpenTabPlacement(
layout: WorkspaceLayout;
placement: WorkspaceTabPlacement;
explorerSidebarPaneId: string | null;
reservedTabIds: Set<string>;
} {
const layout = getWorkspaceLayout(state.layoutByWorkspace, workspaceKey);
const explorerSidebarPaneId = resolveExplorerSidebarPaneId(
@@ -670,6 +673,7 @@ function getOpenTabPlacement(
layout,
placement: resolvedPlacement,
explorerSidebarPaneId,
reservedTabIds: new Set(getSheets(state, workspaceKey).map((sheet) => sheet.tab.tabId)),
};
}
@@ -815,11 +819,23 @@ function resolveOpenParentTabId(
return findSheet(state, workspaceKey, parentTabId)?.parentTabId ?? parentTabId;
}
function collectWorkspaceTabIds(
state: Pick<WorkspaceLayoutStore, "layoutByWorkspace" | "sheetsByWorkspace">,
workspaceKey: string,
): Set<string> {
const layout = state.layoutByWorkspace[workspaceKey];
return new Set([
...(layout ? collectAllTabs(layout.root).map((tab) => tab.tabId) : []),
...getSheets(state, workspaceKey).map((sheet) => sheet.tab.tabId),
]);
}
function placeTargetInSheet(input: {
occupiedTabIds: ReadonlySet<string>;
/** The sheet whose tab the target keeps, if any. */
kept: SheetTab | undefined;
target: WorkspaceTabTarget;
intent: WorkspaceTabOpenIntent;
createTabId: () => string;
policy: CompactSheetPolicy;
parentTabId: string | null;
state: JsonValue | undefined;
@@ -829,10 +845,7 @@ function placeTargetInSheet(input: {
}
return {
tab: {
tabId:
input.intent === "reveal"
? buildDeterministicWorkspaceTabId(input.target)
: createWorkspaceTabInstanceId(),
tabId: allocateWorkspaceTabId(input.createTabId(), input.occupiedTabIds),
target: input.target,
createdAt: Date.now(),
...(input.state !== undefined ? { state: input.state } : {}),
@@ -853,6 +866,7 @@ function promoteSheetToTab(
): { tabId: string; patch: Partial<WorkspaceLayoutStore> } | null {
const { tab } = sheet;
const placement = getOpenTabPlacement(state, workspaceKey, tab.target, FOCUSED_PANE_PLACEMENT);
placement.reservedTabIds.delete(tab.tabId);
const input = {
...placement,
target: tab.target,
@@ -1122,9 +1136,13 @@ export function createWorkspaceLayoutStore(
const sheets = getSheets(get(), normalizedWorkspaceKey);
const { keptIndex } = sheetPlacement;
const sheet = placeTargetInSheet({
occupiedTabIds: collectWorkspaceTabIds(get(), normalizedWorkspaceKey),
kept: keptIndex === null ? undefined : sheets[keptIndex],
target: normalizedTarget,
intent: input.intent,
createTabId: () =>
input.intent === "reveal"
? buildDeterministicWorkspaceTabId(normalizedTarget)
: createWorkspaceTabInstanceId(),
policy: sheetPlacement.policy,
parentTabId,
state: input.state,
@@ -1706,9 +1724,14 @@ export function createWorkspaceLayoutStore(
explorerSidebarPaneId,
rawLayout.focusedPaneId,
);
const sheets = getSheets(state, normalizedWorkspaceKey);
const fittingSheets = sheets.filter(
(sheet) => !sheetAgentNoLongerFits(normalizedWorkspaceKey, sheet, snapshot),
);
const nextState = reconcileWorkspaceTabs(
{
layout: currentLayout,
reservedTabIds: new Set(fittingSheets.map((sheet) => sheet.tab.tabId)),
pinnedAgentIds: state.pinnedAgentIdsByWorkspace[normalizedWorkspaceKey] ?? null,
hiddenAgentIds: state.hiddenAgentIdsByWorkspace[normalizedWorkspaceKey] ?? null,
explorerSidebarPaneId,
@@ -1730,10 +1753,6 @@ export function createWorkspaceLayoutStore(
);
}
}
const sheets = getSheets(state, normalizedWorkspaceKey);
const fittingSheets = sheets.filter(
(sheet) => !sheetAgentNoLongerFits(normalizedWorkspaceKey, sheet, snapshot),
);
const sheetAgentGone = fittingSheets.length !== sheets.length;
if (
state.layoutByWorkspace[normalizedWorkspaceKey] &&
@@ -138,6 +138,88 @@ describe("useSubagentSheetTab", () => {
expect(result.current?.tab.tabId).toBe(tabId);
});
it("keeps an open menu sheet's id when an unrelated reused tab disappears", () => {
const row = seedParentWithChild();
const store = useWorkspaceLayoutStore.getState();
const reusedId = store.openTab({
workspaceKey,
target: { kind: "agent", agentId: "child" },
intent: "reveal",
asTab: true,
});
if (!reusedId) throw new Error("Expected a child tab");
store.replaceTab(workspaceKey, reusedId, { kind: "agent", agentId: "other" });
store.setLayoutMode("compact");
const { result } = renderHook(() => useSubagentSheetTab(workspaceKey, "parent-tab")(row));
const sheetId = result.current?.tab.tabId;
expect(result.current?.tab.target).toEqual({ kind: "agent", agentId: "child" });
expect(sheetId).not.toBe(reusedId);
act(() => {
store.reconcileTabs(workspaceKey, {
agentsHydrated: true,
terminalsHydrated: true,
activeAgentIds: ["parent", "child"],
autoOpenAgentIds: [],
knownTerminalIds: [],
standaloneTerminalIds: [],
});
});
expect(store.getWorkspaceTabs(workspaceKey).map((tab) => tab.tabId)).not.toContain(reusedId);
expect(result.current?.tab.tabId).toBe(sheetId);
expect(result.current?.tab.target).toEqual({ kind: "agent", agentId: "child" });
});
it("promotes a menu sheet to the subagent's own tab", () => {
const row = seedParentWithChild();
const store = useWorkspaceLayoutStore.getState();
store.setLayoutMode("compact");
const { result } = renderHook(() => useSubagentSheetTab(workspaceKey, "parent-tab")(row));
const sheet = result.current;
if (!sheet) throw new Error("Expected a menu sheet");
let promotedId: string | null = null;
act(() => {
promotedId = store.openTabInFront(workspaceKey, sheet);
});
expect(promotedId).toBe("agent_child");
expect(
store.getWorkspaceTabs(workspaceKey).filter((tab) => tab.target.kind === "agent"),
).toEqual([
expect.objectContaining({
tabId: "agent_child",
target: { kind: "agent", agentId: "child" },
}),
]);
});
it("does not reuse a menu id retained by a promoted tab showing another target", () => {
const row = seedParentWithChild();
const store = useWorkspaceLayoutStore.getState();
store.setLayoutMode("compact");
const { result } = renderHook(() => useSubagentSheetTab(workspaceKey, "parent-tab")(row));
const sheet = result.current;
if (!sheet) throw new Error("Expected a menu sheet");
act(() => {
store.openTabInFront(workspaceKey, sheet);
});
expect(result.current).toBeNull();
act(() => {
store.replaceTab(workspaceKey, sheet.tab.tabId, { kind: "agent", agentId: "other" });
});
expect(result.current?.tab.target).toEqual({ kind: "agent", agentId: "child" });
expect(result.current?.tab.tabId).not.toBe(sheet.tab.tabId);
expect(
store.getWorkspaceTabs(workspaceKey).filter((tab) => tab.target.kind === "agent"),
).toEqual([
expect.objectContaining({
tabId: sheet.tab.tabId,
target: { kind: "agent", agentId: "other" },
}),
]);
});
it("hands a re-rendered row the same sheet", () => {
const row = seedParentWithChild();
useWorkspaceLayoutStore.getState().setLayoutMode("compact");
+10 -3
View File
@@ -4,6 +4,7 @@ import {
useWorkspaceLayoutStore,
type SheetTab,
} from "@/stores/workspace-layout-store";
import { buildDeterministicWorkspaceTabId } from "@/workspace-tabs/identity";
import type { WorkspaceTabTarget } from "@/workspace-tabs/model";
import type { SubagentRow } from "./select";
@@ -32,6 +33,9 @@ export function useSubagentSheetTab(
const sheets = useWorkspaceLayoutStore((state) =>
workspaceKey ? state.sheetsByWorkspace[workspaceKey] : undefined,
);
// Menu pages never enter the sheet stack. Each starts from the subagent's own tab id, so opening
// it as a tab lands on that id, and keeps the id it was given across layout updates.
const tabIds = useMemo(() => new Map<string, string>(), []);
return useMemo(() => {
// One answer per row until the state it reads changes, so a re-render of the list hands an
// open sheet the same tab rather than a fresh one.
@@ -43,16 +47,19 @@ export function useSubagentSheetTab(
layoutByWorkspace: layout ? { [workspaceKey]: layout } : {},
sheetsByWorkspace: sheets ? { [workspaceKey]: sheets } : {},
};
const key = `${row.kind}:${row.id}`;
const key = JSON.stringify([workspaceKey, parentTabId, row.kind, row.id]);
const known = answers.get(key);
if (known !== undefined) return known;
const target = subagentRowTarget(row);
const sheet = selectSheetTab(state, {
workspaceKey,
target: subagentRowTarget(row),
target,
parentTabId,
preferredTabId: tabIds.get(key) ?? buildDeterministicWorkspaceTabId(target),
});
if (sheet) tabIds.set(key, sheet.tab.tabId);
answers.set(key, sheet);
return sheet;
};
}, [layout, layoutMode, parentTabId, sheets, workspaceKey]);
}, [layout, layoutMode, parentTabId, sheets, tabIds, workspaceKey]);
}
@@ -5,9 +5,11 @@ import {
normalizeStoredHostProfile,
orderHostsLocalFirst,
pinRelayProtectedSecurityInProfiles,
readHostRegistry,
relayConnectionFromOffer,
resolveActiveHostServerId,
upsertHostConnectionInProfiles,
writeHostRegistry,
type HostConnection,
type HostProfile,
} from "./host-connection";
@@ -87,6 +89,25 @@ describe("normalizeStoredHostProfile", () => {
expect(profile?.connections[0]).not.toHaveProperty("password");
});
it("drops a connection kind this build doesn't know and keeps the host", () => {
const profile = normalizeStoredHostProfile({
serverId: "srv_mixed",
password: "secret",
connections: [
{ id: "future:1", type: "futureKind", address: "future.example.com" },
{ id: "direct:lan:6767", type: "directTcp", endpoint: "lan:6767", futureField: true },
{ id: "direct:remote:6767", type: "directTcp", endpoint: "remote:6767" },
],
preferredConnectionId: "direct:remote:6767",
});
expect(profile?.password).toBe("secret");
expect(profile?.connections).toEqual([
{ id: "direct:remote:6767", type: "directTcp", endpoint: "remote:6767", useTls: false },
]);
expect(profile?.preferredConnectionId).toBe("direct:remote:6767");
});
it("preserves legacy relay ids when TLS is absent", () => {
const profile = normalizeStoredHostProfile({
serverId: "srv_relay",
@@ -177,6 +198,59 @@ describe("normalizeStoredHostProfile", () => {
});
});
describe("readHostRegistry and writeHostRegistry", () => {
const direct: HostConnection = {
id: "direct:lan:6767",
type: "directTcp",
endpoint: "lan:6767",
useTls: false,
};
const future = { id: "future:1", type: "futureKind", address: "future.example.com" };
it("writes back every entry it could not read", () => {
const unreadableHost = { serverId: "srv_future", connections: [future] };
const hostWithFutureField = { serverId: "srv_field", connections: [direct], futureField: 1 };
const stored = [
{ ...makeHost("srv_a"), connections: [direct, future] },
unreadableHost,
hostWithFutureField,
"not a host",
];
const { hosts, unreadable } = readHostRegistry(stored);
expect(hosts.map((host) => host.serverId)).toEqual(["srv_a"]);
expect(hosts[0]?.connections).toEqual([direct]);
expect(writeHostRegistry(hosts, unreadable)).toEqual([
{ ...hosts[0], connections: [direct, future] },
unreadableHost,
hostWithFutureField,
"not a host",
]);
});
it("writes a host saved again by this build in place of the entry it could not read", () => {
const { hosts, unreadable } = readHostRegistry([{ serverId: "srv_a", connections: [future] }]);
expect(hosts).toEqual([]);
const saved = { ...makeHost("srv_a"), connections: [direct] };
expect(writeHostRegistry([saved], unreadable)).toEqual([saved]);
});
it("moves a stored direct TCP password to its host next to a connection it can't read", () => {
const registry = readHostRegistry([
{
serverId: "srv_legacy",
connections: [future, { type: "directTcp", endpoint: "lan:6767", password: "old-secret" }],
},
]);
expect(registry.movedConnectionPassword).toBe(true);
expect(registry.hosts[0]?.password).toBe("old-secret");
expect(registry.hosts[0]?.connections).toEqual([direct]);
});
});
describe("createRemoteSshHostConnection", () => {
it("keeps optional SSH settings absent", () => {
expect(createRemoteSshHostConnection({ host: "build-box" })).toEqual({
+102 -13
View File
@@ -522,12 +522,12 @@ const StoredHostProfileSchema = z.strictObject({
label: z.string().optional(),
appearance: HostAppearanceSchema.optional(),
lifecycle: z.strictObject({}).optional(),
connections: z.array(StoredHostConnectionSchema).min(1),
// Read one by one, so a connection kind another build wrote skips only that connection.
connections: z.array(z.unknown()).min(1),
preferredConnectionId: z.string().nullable().optional(),
createdAt: z.string().datetime({ offset: true }).optional(),
updatedAt: z.string().datetime({ offset: true }).optional(),
});
export const StoredHostRegistrySchema = z.array(StoredHostProfileSchema);
type StoredHostConnection = z.infer<typeof StoredHostConnectionSchema>;
function normalizeStoredConnection(connection: StoredHostConnection): HostConnection | null {
@@ -590,20 +590,37 @@ function normalizeStoredConnection(connection: StoredHostConnection): HostConnec
}
export function normalizeStoredHostProfile(entry: unknown): HostProfile | null {
return readStoredHost(entry)?.profile ?? null;
}
interface StoredHostRead {
profile: HostProfile;
unreadableConnections: unknown[];
movedConnectionPassword: boolean;
}
function readStoredHost(entry: unknown): StoredHostRead | null {
const result = StoredHostProfileSchema.safeParse(entry);
if (!result.success) {
return null;
}
const record = result.data;
const serverId = record.serverId;
const storedConnections: StoredHostConnection[] = [];
const unreadableConnections: unknown[] = [];
for (const stored of record.connections) {
const parsed = StoredHostConnectionSchema.safeParse(stored);
if (parsed.success) storedConnections.push(parsed.data);
else unreadableConnections.push(stored);
}
// COMPAT(connectionPassword): added in v0.9.1, remove after 2027-03-24 once stored direct passwords have migrated.
const legacyPassword = record.connections.find(
const legacyPassword = storedConnections.find(
(connection) => connection.type === "directTcp" && connection.password,
);
const password =
record.password ?? (legacyPassword?.type === "directTcp" ? legacyPassword.password : undefined);
const connections = record.connections
const connections = storedConnections
.map((connection) => normalizeStoredConnection(connection))
.filter((connection): connection is HostConnection => connection !== null);
if (connections.length === 0) {
@@ -620,18 +637,90 @@ export function normalizeStoredHostProfile(entry: unknown): HostProfile | null {
: (connections[0]?.id ?? null);
return {
serverId,
...(password ? { password } : {}),
label,
appearance: record.appearance ?? defaultHostAppearance(),
lifecycle: defaultLifecycle(),
connections,
preferredConnectionId,
createdAt: record.createdAt ?? now,
updatedAt: record.updatedAt ?? now,
profile: {
serverId,
...(password ? { password } : {}),
label,
appearance: record.appearance ?? defaultHostAppearance(),
lifecycle: defaultLifecycle(),
connections,
preferredConnectionId,
createdAt: record.createdAt ?? now,
updatedAt: record.updatedAt ?? now,
},
unreadableConnections,
movedConnectionPassword: legacyPassword !== undefined,
};
}
/**
* Stored registry entries this build can't read, such as a connection kind added by a newer
* build. `writeHostRegistry` writes them back so that build still finds them.
*/
export interface UnreadableHostEntries {
hosts: unknown[];
connectionsByServerId: Map<string, unknown[]>;
}
export function readHostRegistry(stored: unknown[]): {
hosts: HostProfile[];
unreadable: UnreadableHostEntries;
// COMPAT(connectionPassword): added in v0.9.1, remove after 2027-03-24 with stored-password migration.
movedConnectionPassword: boolean;
} {
const hosts: HostProfile[] = [];
const unreadable: UnreadableHostEntries = { hosts: [], connectionsByServerId: new Map() };
let movedConnectionPassword = false;
for (const entry of stored) {
const read = readStoredHost(entry);
if (!read) {
unreadable.hosts.push(entry);
continue;
}
hosts.push(read.profile);
if (read.unreadableConnections.length > 0) {
unreadable.connectionsByServerId.set(read.profile.serverId, read.unreadableConnections);
}
movedConnectionPassword ||= read.movedConnectionPassword;
}
return { hosts, unreadable, movedConnectionPassword };
}
export function writeHostRegistry(
hosts: HostProfile[],
unreadable: UnreadableHostEntries,
): unknown[] {
const savedServerIds = new Set(hosts.map((host) => host.serverId));
const written: unknown[] = hosts.map((host) => {
const kept = unreadable.connectionsByServerId.get(host.serverId);
return kept ? { ...host, connections: [...host.connections, ...kept] } : host;
});
for (const entry of unreadable.hosts) {
// A host this build saved again replaces the entry it couldn't read.
const serverId = readStoredServerId(entry);
if (serverId === null || !savedServerIds.has(serverId)) written.push(entry);
}
return written;
}
/** Drops the entries this build couldn't read for a host you removed. */
export function forgetUnreadableHost(
unreadable: UnreadableHostEntries,
serverId: string,
): UnreadableHostEntries {
const connectionsByServerId = new Map(unreadable.connectionsByServerId);
connectionsByServerId.delete(serverId);
return {
hosts: unreadable.hosts.filter((entry) => readStoredServerId(entry) !== serverId),
connectionsByServerId,
};
}
function readStoredServerId(entry: unknown): string | null {
if (typeof entry !== "object" || entry === null || !("serverId" in entry)) return null;
return typeof entry.serverId === "string" ? entry.serverId.trim() : null;
}
export function hostHasConnection(host: HostProfile, connection: HostConnection): boolean {
return host.connections.some((existing) => hostConnectionEquals(existing, connection));
}
@@ -0,0 +1,64 @@
import type { Page } from "@playwright/test";
import { test, expect } from "../../app/e2e/support/fixtures";
import { gotoAppShell } from "../../app/e2e/support/helpers/app";
// Windows and Linux draw their window controls top-right, so the desktop sidebar has no
// chrome row of its own. Its window-drag surface is the strip above the navigation rows.
const CUSTOM_CHROME_HOSTS = [
{ platform: "linux", windowChromeMode: "custom-linux" },
{ platform: "win32", windowChromeMode: "custom-windows" },
] as const;
async function installDesktopHost(
page: Page,
host: (typeof CUSTOM_CHROME_HOSTS)[number],
): Promise<void> {
await page.addInitScript((desktopHost) => {
window.paseoDesktop = {
...desktopHost,
events: { on: () => () => {} },
invoke: async (command: string) => {
if (command === "get_desktop_settings") {
return {
releaseChannel: "stable",
daemon: { manageBuiltInDaemon: true, keepRunningAfterQuit: true },
};
}
return null;
},
};
}, host);
}
async function sidebarDragGeometry(page: Page) {
const navScroll = page.locator('[data-testid="sidebar-nav-scroll"]:visible').first();
await expect(navScroll).toBeVisible();
return navScroll.evaluate((node) => {
const nav = node.getBoundingClientRect();
const dragRegions = [];
for (const element of document.querySelectorAll<HTMLElement>("*")) {
if (getComputedStyle(element).getPropertyValue("-webkit-app-region") !== "drag") continue;
const rect = element.getBoundingClientRect();
const overSidebar = rect.left < nav.right && rect.right > nav.left;
if (overSidebar && rect.height > 0) dragRegions.push({ top: rect.top, bottom: rect.bottom });
}
return { navTop: nav.top, navBottom: nav.bottom, dragRegions };
});
}
for (const host of CUSTOM_CHROME_HOSTS) {
test.describe(`Desktop sidebar on ${host.platform}`, () => {
test.use({ viewport: { width: 1280, height: 480 } });
test("keeps a window drag strip above the scrolling navigation", async ({ page }) => {
await installDesktopHost(page, host);
await gotoAppShell(page);
const geometry = await sidebarDragGeometry(page);
expect(geometry.dragRegions).not.toEqual([]);
for (const region of geometry.dragRegions) {
expect(region.bottom).toBeLessThanOrEqual(geometry.navTop + 1);
}
});
});
}
@@ -14,18 +14,19 @@ const BASE_RECORD: StoredAgentRecord = {
config: null,
};
const ARCHIVE = {
archivedAt: "2025-01-03T00:00:00.000Z",
updatedAt: "2025-01-03T00:00:00.000Z",
};
test("archives a stored agent without changing terminal statuses", () => {
const statuses: Array<StoredAgentRecord["lastStatus"]> = ["idle", "error", "closed"];
for (const status of statuses) {
const archived = buildArchivedAgentRecord(
{ ...BASE_RECORD, lastStatus: status },
{ archivedAt: "2025-01-03T00:00:00.000Z" },
);
const archived = buildArchivedAgentRecord({ ...BASE_RECORD, lastStatus: status }, ARCHIVE);
expect(archived.lastStatus).toBe(status);
expect(archived.archivedAt).toBe("2025-01-03T00:00:00.000Z");
expect(archived.updatedAt).toBe(BASE_RECORD.updatedAt);
}
});
@@ -33,10 +34,7 @@ test("archives busy stored agents as idle", () => {
const statuses: Array<StoredAgentRecord["lastStatus"]> = ["initializing", "running"];
for (const status of statuses) {
const archived = buildArchivedAgentRecord(
{ ...BASE_RECORD, lastStatus: status },
{ archivedAt: "2025-01-03T00:00:00.000Z" },
);
const archived = buildArchivedAgentRecord({ ...BASE_RECORD, lastStatus: status }, ARCHIVE);
expect(archived.lastStatus).toBe("idle");
}
@@ -50,7 +48,7 @@ test("clears persisted attention when archiving", () => {
attentionReason: "finished",
attentionTimestamp: "2025-01-02T12:00:00.000Z",
},
{ archivedAt: "2025-01-03T00:00:00.000Z" },
ARCHIVE,
);
expect(archived).toMatchObject({
@@ -60,11 +58,19 @@ test("clears persisted attention when archiving", () => {
});
});
test("can stamp updatedAt to the archive timestamp", () => {
const archived = buildArchivedAgentRecord(BASE_RECORD, {
archivedAt: "2025-01-03T00:00:00.000Z",
updatedAt: "2025-01-03T00:00:00.000Z",
});
test("moves updatedAt to the archive time", () => {
const archived = buildArchivedAgentRecord(BASE_RECORD, ARCHIVE);
expect(archived.updatedAt).toBe("2025-01-03T00:00:00.000Z");
});
test("keeps a later updatedAt when the archive time is earlier", () => {
// Putting an original archive back after a failed unarchive must not move updatedAt backwards.
const archived = buildArchivedAgentRecord(
{ ...BASE_RECORD, updatedAt: "2025-01-04T00:00:00.000Z" },
ARCHIVE,
);
expect(archived.archivedAt).toBe("2025-01-03T00:00:00.000Z");
expect(archived.updatedAt).toBe("2025-01-04T00:00:00.000Z");
});
@@ -3,19 +3,19 @@ import type { StoredAgentRecord } from "./agent-storage.js";
export type ArchivedStoredAgentRecord = StoredAgentRecord & { archivedAt: string };
interface BuildArchivedAgentRecordOptions {
archivedAt?: string;
updatedAt?: string;
archivedAt: string;
/** When this archive happened. Re-archiving keeps the original archivedAt but still records it. */
updatedAt: string;
}
export function buildArchivedAgentRecord(
record: StoredAgentRecord,
options?: BuildArchivedAgentRecordOptions,
options: BuildArchivedAgentRecordOptions,
): ArchivedStoredAgentRecord {
const archivedAt = options?.archivedAt ?? new Date().toISOString();
return {
...record,
archivedAt,
updatedAt: options?.updatedAt ?? record.updatedAt,
archivedAt: options.archivedAt,
updatedAt: latestTimestamp(record.updatedAt, options.updatedAt),
lastStatus: normalizeArchivedStatus(record.lastStatus),
requiresAttention: false,
attentionReason: null,
@@ -23,6 +23,13 @@ export function buildArchivedAgentRecord(
};
}
// Archiving is the agent's latest change. An earlier archive time (an original archive put back
// after a failed unarchive) keeps the newer updatedAt, since clients drop an agent update that is
// older than the one they hold.
function latestTimestamp(current: string, archiveTime: string): string {
return Date.parse(archiveTime) > Date.parse(current) ? archiveTime : current;
}
function normalizeArchivedStatus(
status: StoredAgentRecord["lastStatus"],
): StoredAgentRecord["lastStatus"] {
@@ -6494,6 +6494,114 @@ test("archiveSnapshot dispatches archived state for stored-only agents", async (
expect(last.lifecycle).toBe("closed");
});
test("archiveSnapshot moves a stored-only agent's updatedAt to its archive time, as a live archive does", async () => {
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-archive-snapshot-updated-at-"));
const storage = new AgentStorage(join(workdir, "agents"), logger);
const manager = new AgentManager({
clients: { codex: new TestAgentClient() },
registry: storage,
logger,
});
const created = await manager.createAgent(
{ provider: "codex", cwd: workdir, title: "Stored archive updatedAt" },
undefined,
{ workspaceId: undefined },
);
await manager.closeAgent(created.id);
const before = await storage.get(created.id);
expect(before?.updatedAt).toEqual(expect.any(String));
// Later than anything the agent did: lists sorted by updated_at put it first, as they do
// for an agent archived while loaded.
const archivedAt = new Date(Date.parse(before!.updatedAt) + 60_000).toISOString();
const archived = await manager.archiveSnapshot(created.id, archivedAt);
expect(archived.updatedAt).toBe(archivedAt);
expect((await storage.get(created.id))?.updatedAt).toBe(archivedAt);
});
test("archiveSnapshot restoring an earlier archive time keeps updatedAt at the unarchive", async () => {
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-archive-snapshot-restore-"));
const storage = new AgentStorage(join(workdir, "agents"), logger);
const manager = new AgentManager({
clients: { codex: new TestAgentClient() },
registry: storage,
logger,
});
const created = await manager.createAgent(
{ provider: "codex", cwd: workdir, title: "Restore archive updatedAt" },
undefined,
{ workspaceId: undefined },
);
await manager.closeAgent(created.id);
const originalArchivedAt = (await manager.archiveSnapshot(created.id, new Date().toISOString()))
.archivedAt!;
await new Promise((resolve) => setTimeout(resolve, 5));
await manager.unarchiveSnapshot(created.id);
const unarchivedAt = (await storage.get(created.id))!.updatedAt;
const events: ManagedAgent[] = [];
manager.subscribe(
(event) => {
if (event.type === "agent_state" && event.agent.id === created.id) {
events.push(event.agent);
}
},
{ agentId: created.id, replayState: false },
);
// A send that could not load the agent puts its original archive back.
await manager.archiveSnapshot(created.id, originalArchivedAt);
// Clients keep the newer of two updates, so an older updatedAt would leave them showing it active.
const stored = await storage.get(created.id);
expect(stored?.archivedAt).toBe(originalArchivedAt);
expect(stored?.updatedAt).toBe(unarchivedAt);
expect(events.at(-1)?.updatedAt.toISOString()).toBe(unarchivedAt);
});
test("archiveSnapshot restoring an earlier archive time on a loaded agent keeps updatedAt at the unarchive", async () => {
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-archive-snapshot-restore-loaded-"));
const storage = new AgentStorage(join(workdir, "agents"), logger);
const manager = new AgentManager({
clients: { codex: new TestAgentClient() },
registry: storage,
logger,
});
const created = await manager.createAgent(
{ provider: "codex", cwd: workdir, title: "Restore loaded archive updatedAt" },
undefined,
{ workspaceId: undefined },
);
const { archivedAt: originalArchivedAt } = await manager.archiveAgent(created.id);
await new Promise((resolve) => setTimeout(resolve, 5));
await manager.unarchiveSnapshot(created.id);
const unarchivedAt = Date.parse((await storage.get(created.id))!.updatedAt);
// The send resumed the agent before a later loading step failed, so it is still loaded.
await ensureAgentLoaded(created.id, { agentManager: manager, agentStorage: storage, logger });
expect(manager.getAgent(created.id)).not.toBeNull();
const events: ManagedAgent[] = [];
manager.subscribe(
(event) => {
if (event.type === "agent_state" && event.agent.id === created.id) {
events.push(event.agent);
}
},
{ agentId: created.id, replayState: false },
);
await manager.archiveSnapshot(created.id, originalArchivedAt);
const stored = await storage.get(created.id);
expect(stored?.archivedAt).toBe(originalArchivedAt);
expect(Date.parse(stored!.updatedAt)).toBeGreaterThanOrEqual(unarchivedAt);
expect(events.at(-1)?.updatedAt.getTime()).toBeGreaterThanOrEqual(unarchivedAt);
});
test("markAgentUnread restores error attention on a read errored agent", async () => {
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-mark-unread-error-"));
const storage = new AgentStorage(join(workdir, "agents"), logger);
@@ -14606,14 +14714,16 @@ test("workspace archive preserves a loaded history agent stamp and stamps cascad
labels: { [PARENT_AGENT_ID_LABEL]: parent.id },
workspaceId: undefined,
});
const stamp = "2026-11-09T00:00:00.000Z";
// Archive stamps are taken when the archive happens, so they follow the agents' activity.
const stamp = new Date(Date.now() + 60_000).toISOString();
const laterStamp = new Date(Date.now() + 120_000).toISOString();
await manager.archiveAgent(parent.id, stamp);
expect((await storage.get(parent.id))?.archivedAt).toBe(stamp);
expect((await storage.get(child.id))?.archivedAt).toBe(stamp);
await ensureAgentLoaded(parent.id, { agentManager: manager, agentStorage: storage, logger });
await manager.archiveAgent(parent.id, "2026-11-09T01:00:00.000Z");
await manager.archiveAgent(parent.id, laterStamp);
expect((await storage.get(parent.id))?.archivedAt).toBe(stamp);
expect((await storage.get(parent.id))?.updatedAt).toBe("2026-11-09T01:00:00.000Z");
expect((await storage.get(parent.id))?.updatedAt).toBe(laterStamp);
} finally {
await storage.flush();
rmSync(workdir, { recursive: true, force: true });
@@ -2350,7 +2350,7 @@ export class AgentManager {
private async persistArchivedRecord(
record: StoredAgentRecord,
options: { archivedAt: string; updatedAt?: string },
options: { archivedAt: string; updatedAt: string },
): Promise<ArchivedStoredAgentRecord> {
const archivedRecord = buildArchivedAgentRecord(record, options);
await this.requireRegistry().upsert(archivedRecord);
@@ -2870,7 +2870,11 @@ export class AgentManager {
throw new Error(`Agent not found: ${agentId}`);
}
const nextRecord = await this.persistArchivedRecord(record, { archivedAt });
// Archiving is the agent's latest change, as markRecordArchived records it for a loaded agent.
const nextRecord = await this.persistArchivedRecord(record, {
archivedAt,
updatedAt: archivedAt,
});
await this.syncNativeArchiveState(record.provider, record.persistence, "archive");
@@ -2437,6 +2437,36 @@ describe("Codex app-server provider", () => {
appServer.assertNoErrors();
});
test("lets idle cleanup release a session opened only to read its history", async () => {
let spawns = 0;
const appServer = createFakeCodexAppServer({
"thread/resume": () =>
Promise.reject(new Error(archivedThreadErrorMessage("archived-thread-id"))),
"thread/read": () => ({ thread: { turns: [] } }),
});
const provider = new CodexAppServerAgentClient(createTestLogger(), undefined, {
appServerProcess: createFakeCodexAppServerProcess(() => {
spawns += 1;
return appServer.child;
}),
});
const internals = castInternals<{
goalsEnabledPromise: Promise<boolean> | null;
autoReviewEnabledPromise: Promise<boolean> | null;
}>(provider);
internals.goalsEnabledPromise = Promise.resolve(false);
internals.autoReviewEnabledPromise = Promise.resolve(false);
const session = await provider.resumeSession(archivedThreadHandle(), undefined, undefined, {
purpose: "history",
});
expect(await session.canStopRuntime!()).toBe(true);
expect(spawns).toBe(1);
await session.close();
appServer.assertNoErrors();
});
test("unarchives Codex when an active Paseo agent resumes an archived thread", async () => {
const threadRequests: string[] = [];
let resumeAttempts = 0;
@@ -5385,6 +5385,8 @@ export class CodexAppServerAgentSession implements AgentSession {
}
async canStopRuntime(): Promise<boolean> {
// A history session released its app-server once it read the thread, so nothing runs.
if (this.connectionState === "history-ready") return true;
if (
!this.client ||
this.client.hasPendingRequests() ||
@@ -2477,6 +2477,42 @@ describe("OpenCode adapter startTurn error handling", () => {
await session.close();
});
test("reports a question rejected by a human steer as resolved", async () => {
const { parent: session, openCode } = await createParentSession("ses_steer_question");
openCode.sessionPromptAsyncEvents = [];
const events: AgentStreamEvent[] = [];
session.subscribe((event) => events.push(event));
const { turnId } = await session.startTurn("first");
openCode.emitEvent({
type: "question.asked",
properties: {
id: "question-steer",
sessionID: "ses_steer_question",
questions: [{ question: "Which color?", header: "Color", options: [] }],
},
});
await vi.waitFor(() => expect(session.getPendingPermissions()).toHaveLength(1));
await expect(
session.steerActiveTurn?.("never mind", {
expectedTurnId: turnId,
clearPendingPermissions: true,
}),
).resolves.toEqual({ status: "accepted" });
expect(openCode.calls.questionReject).toContainEqual(
expect.objectContaining({ requestID: "question-steer" }),
);
expect(events).toContainEqual(
expect.objectContaining({
type: "permission_resolved",
requestId: "question-steer",
resolution: expect.objectContaining({ behavior: "deny" }),
}),
);
await session.close();
});
test("keeps multiple native steers correlated in admission order", async () => {
const { parent: session, openCode } = await createParentSession("ses_native_steer_fifo");
openCode.sessionPromptAsyncEvents = [];
@@ -5049,22 +5049,24 @@ class OpenCodeAgentSession implements AgentSession {
answers,
});
}
this.pendingPermissions.delete(requestId);
this.pendingPermissionDirectories.delete(requestId);
return;
} else {
const reply = resolveOpenCodePermissionReply(response);
await this.client.permission.reply({
requestID: requestId,
directory,
reply,
message: response.behavior === "deny" ? response.message : undefined,
});
}
const reply = resolveOpenCodePermissionReply(response);
await this.client.permission.reply({
requestID: requestId,
directory,
reply,
message: response.behavior === "deny" ? response.message : undefined,
});
this.pendingPermissions.delete(requestId);
this.pendingPermissionDirectories.delete(requestId);
this.notifySubscribers({
type: "permission_resolved",
provider: "opencode",
requestId,
resolution: response,
});
}
describePersistence(): AgentPersistenceHandle | null {
@@ -31,6 +31,7 @@ function createPullRequest(
baseRefName: "main",
headRefName: "feature",
headSha: "same-head",
commitOids: ["same-head"],
isMerged: true,
...overrides,
};
@@ -349,7 +350,7 @@ afterEach(() => {
describe("archiveIfSafe", () => {
test("denies archive when checkout facts do not establish safety", async () => {
for (const git of [{ headSha: undefined }, { behindOfOrigin: 1 }, { isDirty: null }]) {
for (const git of [{ headSha: undefined }, { isDirty: null }]) {
const harness = createHarness({ snapshot: createSnapshot({ git }) });
await runArchiveIfSafe(harness);
expect(harness.deps.archiveByScope).not.toHaveBeenCalled();
@@ -1,3 +1,4 @@
import { pullRequestContainsCommit } from "../../services/pull-request-contains-commit.js";
import type { Logger } from "pino";
import type { AgentManager } from "../agent/agent-manager.js";
@@ -65,8 +66,8 @@ export async function archiveIfSafe(input: {
if (
!pullRequest?.isMerged ||
!pullRequest.headSha ||
!snapshot.git.headSha ||
snapshot.git.headSha !== pullRequest.headSha ||
snapshot.forge.error
) {
return;
@@ -74,13 +75,18 @@ export async function archiveIfSafe(input: {
if (snapshot.git.isDirty !== false) {
return;
}
if (
(snapshot.git.aheadOfOrigin !== null && snapshot.git.aheadOfOrigin !== 0) ||
(snapshot.git.behindOfOrigin !== null && snapshot.git.behindOfOrigin !== 0)
) {
if (snapshot.git.aheadOfOrigin !== null && snapshot.git.aheadOfOrigin !== 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,6 +179,7 @@ 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;
@@ -194,6 +195,7 @@ async function createUnobservedWorkspace(journeyOptions?: {
status: observation && {
...observation,
headSha: remoteHeadSha,
commitOids: [workspaceHeadSha, remoteHeadSha],
title: observation.headRefName,
baseRefName: "main",
isMerged: observation.state === "merged",
@@ -260,7 +262,23 @@ async function createUnobservedWorkspace(journeyOptions?: {
metrics: () => service.getMetrics(),
isActive: () => active,
advanceRemoteHead: () => {
remoteHeadSha = "a".repeat(40);
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]);
},
makeDirty: () => writeFileSync(path.join(cwd, "README.md"), "uncommitted work\n"),
commitUnpushed: () => {
@@ -307,7 +325,7 @@ describe("workspace auto-archive behavior", () => {
expect(workspace.isActive()).toBe(true);
});
test("keeps a merged PR visible and the workspace active when its remote head advances", async () => {
test("archives a clean workspace contained in the advanced merged PR head", async () => {
const workspace = await createUnobservedWorkspace();
const open = await workspace.observe("open");
workspace.advanceRemoteHead();
@@ -315,8 +333,9 @@ 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(workspace.isActive()).toBe(true);
expect(workspace.archives).toEqual([]);
expect(merged.git.behindOfOrigin).toBe(1);
expect(workspace.isActive()).toBe(false);
expect(workspace.archives).toHaveLength(1);
});
test("archives a clean owned workspace on an unobserved open-to-merged transition only once", async () => {
@@ -51,6 +51,7 @@ 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",
@@ -76,6 +77,7 @@ 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");
@@ -0,0 +1,87 @@
import { beforeAll, beforeEach, describe, test, expect } from "vitest";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import pino from "pino";
import { createTestPaseoDaemon } from "../test-utils/paseo-daemon.js";
import { DaemonClient } from "../test-utils/daemon-client.js";
import {
canRunRealProvider,
createRealProviderClients,
getRealProviderConfig,
} from "./real-provider-test-config.js";
async function readStatusAndPendingIds(
client: DaemonClient,
agentId: string,
): Promise<{ status: string; pendingIds: string[] }> {
const fetched = await client.fetchAgent(agentId);
const snapshot = fetched!.agent;
const pendingIds = (snapshot.pendingPermissions ?? []).map((pending) => pending.id);
return { status: snapshot.status, pendingIds };
}
describe("daemon E2E (real opencode) - a message sent instead of answering a question", () => {
let canRun = false;
beforeAll(async () => {
canRun = await canRunRealProvider("opencode");
});
beforeEach((context) => {
if (!canRun) {
context.skip();
}
});
test("removes the superseded question from the pending list", async () => {
const cwd = mkdtempSync(path.join(tmpdir(), "daemon-real-opencode-question-"));
const logger = pino({ level: "silent" });
const daemon = await createTestPaseoDaemon({
agentClients: createRealProviderClients(["opencode"], logger),
logger,
});
const client = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws` });
await client.connect();
await client.fetchAgents({ subscribe: {} });
try {
const agent = await client.createAgent({
...getRealProviderConfig("opencode"),
cwd,
title: "OpenCode superseded question",
});
await client.sendMessage(
agent.id,
[
"Use the question tool to ask me exactly one clarifying question:",
"What color should the button be?",
"Wait for my answer before doing anything else.",
].join(" "),
);
await client.waitForAgentUpsert(
agent.id,
(snapshot) => snapshot.pendingPermissions?.[0]?.kind === "question",
120_000,
);
// The app sends with the default send setting, which steers the running turn.
await client.sendMessage(agent.id, "Never mind the question. Reply with the word done.", {
activeTurnBehavior: "steer",
});
// OpenCode rejects the question and runs the steer message to completion.
await expect
.poll(() => readStatusAndPendingIds(client, agent.id), {
timeout: 120_000,
interval: 1_000,
})
.toEqual({ status: "idle", pendingIds: [] });
} finally {
await client.close().catch(() => undefined);
await daemon.close();
rmSync(cwd, { recursive: true, force: true });
}
}, 300_000);
});
@@ -193,10 +193,11 @@ test("classifies a removed file as deleted", async () => {
});
await rm(target);
// Native recursive delivery can be coalesced before the backend's deletion audit.
// Assert eventual classification without imposing Vitest's one-second default.
// macOS FSEvents can replay the write above as a create after the subscription starts,
// so the delete is the latest event for the path, not the first. Native recursive delivery
// can also be coalesced before the backend's deletion audit, hence the longer timeout.
await expect
.poll(() => events.find((event) => event.path === target)?.type, { timeout: 10_000 })
.poll(() => events.findLast((event) => event.path === target)?.type, { timeout: 10_000 })
.toBe("delete");
await subscription.unsubscribe();
});
+9 -1
View File
@@ -6188,9 +6188,17 @@ 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: snapshot.forge.pullRequest,
pullRequest,
error: snapshot.forge.error,
};
}
@@ -201,6 +201,8 @@ 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,6 +129,8 @@ 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,3 +1,5 @@
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";
@@ -2048,6 +2050,8 @@ 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]));
}
@@ -2067,6 +2071,38 @@ 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({
@@ -2078,6 +2114,8 @@ 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]));
}
@@ -2100,15 +2138,20 @@ 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: "1111111111111111111111111111111111111111",
headSha: pullRequestCommit,
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]));
}
@@ -2117,9 +2160,9 @@ describe("createGiteaService", () => {
await expect(
service.getCurrentPullRequestStatus({
cwd: "/repo",
cwd,
headRef: "dev",
headSha: "2222222222222222222222222222222222222222",
headSha: workspaceCommit,
}),
).resolves.toMatchObject({ number: 8, state: "merged" });
});
+57 -15
View File
@@ -1,3 +1,7 @@
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";
@@ -163,6 +167,7 @@ const GiteaPrListItemSchema = z
labels: z.string().optional(),
ci: z.string().optional(),
headSha: z.string().optional(),
commitOids: z.array(z.string()).optional(),
})
.passthrough();
@@ -1399,6 +1404,7 @@ 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;
@@ -1406,19 +1412,25 @@ export function createGiteaService(options: CreateGiteaServiceOptions = {}): For
const now = options.now ?? Date.now;
const currentPrHeadShaCache = new Map<string, { sha: string; expiresAt: number }>();
async function run(args: string[], runOptions: TeaCommandRunnerOptions): Promise<string> {
async function runResult(
args: string[],
runOptions: TeaCommandRunnerOptions,
): Promise<TeaCommandResult> {
const teaPath = await resolveTea();
if (!teaPath) {
throw new TeaCliMissingError();
}
try {
const result = await runner(args, runOptions);
return result.stdout.trim();
return await runner(args, runOptions);
} catch (error) {
throw teaCliRunner.normalizeError(error, { args: redactTeaArgs(args), cwd: runOptions.cwd });
}
}
async function run(args: string[], runOptions: TeaCommandRunnerOptions): Promise<string> {
return (await runResult(args, runOptions)).stdout.trim();
}
function runJsonParse<T>(
args: string[],
runOptions: TeaCommandRunnerOptions,
@@ -1594,7 +1606,7 @@ export function createGiteaService(options: CreateGiteaServiceOptions = {}): For
if (!match) {
return null;
}
const status = toCurrentPullRequestStatus(match);
const status = { ...toCurrentPullRequestStatus(match), commitOids: match.commitOids };
return loadCurrentPullRequestChecks(input.cwd, match, status);
}
@@ -1656,17 +1668,47 @@ export function createGiteaService(options: CreateGiteaServiceOptions = {}): For
// owner gate.
return input.headSha !== undefined && item.head.sha === input.headSha;
});
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;
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;
}
async function findOpenPullRequestForHeadRef(
@@ -1,3 +1,6 @@
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";
@@ -218,6 +221,21 @@ 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: {
@@ -1111,6 +1129,252 @@ 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([
@@ -1132,6 +1396,7 @@ describe("ForgeService", () => {
}),
]),
}),
batchPollStatusJson({ t0: commitPageJson(["oid-a"]), t1: commitPageJson(["oid-b"]) }),
batchPollStatusJson({
t0: batchPollChecksAliasJson([
{ __typename: "StatusContext", context: "ci", state: "SUCCESS" },
@@ -1187,7 +1452,7 @@ describe("ForgeService", () => {
await flushMicrotasks();
expect(currentPullRequestStatusCalls(runner.calls)).toHaveLength(0);
expect(runner.calls).toHaveLength(2);
expect(runner.calls).toHaveLength(3);
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")');
@@ -1214,7 +1479,7 @@ describe("ForgeService", () => {
await vi.advanceTimersByTimeAsync(EXPECTED_GITHUB_SLOW_POLL_MS);
await flushMicrotasks();
expect(runner.calls).toHaveLength(3);
expect(runner.calls).toHaveLength(4);
expect(statusesA).toHaveLength(2);
expect(statusesA[1]).toEqual(expect.objectContaining({ number: 41, checksStatus: "success" }));
@@ -1248,6 +1513,7 @@ describe("ForgeService", () => {
}),
]),
}),
batchPollStatusJson({ t0: commitPageJson(["oid-a"]), t1: commitPageJson(["oid-b"]) }),
batchPollStatusJson({
t0: batchPollChecksAliasJson([]),
t1: batchPollChecksAliasJson([]),
@@ -1291,7 +1557,7 @@ describe("ForgeService", () => {
await flushMicrotasks();
expect(currentPullRequestStatusCalls(runner.calls)).toHaveLength(0);
expect(runner.calls).toHaveLength(2);
expect(runner.calls).toHaveLength(3);
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")');
@@ -1491,6 +1757,7 @@ 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" },
@@ -1532,7 +1799,7 @@ describe("ForgeService", () => {
await vi.advanceTimersByTimeAsync(EXPECTED_GITHUB_SLOW_POLL_MS);
await flushMicrotasks();
expect(runner.calls[3]?.args[3]).toContain(
expect(runner.calls[4]?.args[3]).toContain(
't0: repository(owner: "upstream", name: "widgets")',
);
@@ -1611,6 +1878,83 @@ 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();
@@ -1717,6 +2061,7 @@ describe("ForgeService", () => {
});
const runner = createScriptedRunner([
batchPollStatusJson({ t0: batchPollRepositoryJson([closedNode]) }),
batchPollStatusJson({ t0: commitPageJson(["oid-closed"]) }),
batchPollStatusJson({
t0: batchPollChecksAliasJson([
{ __typename: "StatusContext", context: "ci", state: "PENDING" },
@@ -1748,7 +2093,7 @@ describe("ForgeService", () => {
await vi.advanceTimersByTimeAsync(0);
await flushMicrotasks();
expect(runner.calls).toHaveLength(2);
expect(runner.calls).toHaveLength(3);
expect(statuses).toEqual([expect.objectContaining({ number: 9, checksStatus: "pending" })]);
// Pending checks are never frozen, so the next cycle re-runs the checks
@@ -1757,7 +2102,7 @@ describe("ForgeService", () => {
await vi.advanceTimersByTimeAsync(EXPECTED_GITHUB_FAST_POLL_MS);
await flushMicrotasks();
expect(runner.calls).toHaveLength(4);
expect(runner.calls).toHaveLength(5);
expect(statuses[1]).toEqual(expect.objectContaining({ number: 9, checksStatus: "success" }));
subscription?.unsubscribe();
@@ -1870,6 +2215,7 @@ describe("ForgeService", () => {
stderr: "GraphQL: Could not resolve to a Repository",
}),
},
batchPollStatusJson({ t0: commitPageJson(["oid-a"]) }),
batchPollStatusJson({
t0: batchPollChecksAliasJson([
{ __typename: "StatusContext", context: "ci", state: "SUCCESS" },
@@ -1902,7 +2248,7 @@ describe("ForgeService", () => {
await vi.advanceTimersByTimeAsync(0);
await flushMicrotasks();
expect(runner.calls).toHaveLength(2);
expect(runner.calls).toHaveLength(3);
expect(statuses).toEqual([
expect.objectContaining({ number: 41, state: "merged", checksStatus: "success" }),
]);
@@ -3138,6 +3484,42 @@ 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([
{
@@ -3280,12 +3662,16 @@ describe("ForgeService", () => {
it("keeps a merged PR when headRefOid matches the checkout HEAD", async () => {
const headSha = "2222222222222222222222222222222222222222";
const runner = createRunner([
currentPullRequestJson({
state: "MERGED",
mergedAt: "2026-07-17T12:00:00Z",
headRefOid: headSha,
}),
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 service = createGitHubService({
runner: runner.runner,
@@ -3296,6 +3682,7 @@ describe("ForgeService", () => {
cwd: "/repo",
headRef: "feature/fork",
headSha,
headRepositoryOwner: "forkOwner",
});
expect(status?.number).toBe(42);
@@ -3303,16 +3690,20 @@ 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: "1111111111111111111111111111111111111111",
headRefOid: pullRequestCommit,
});
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,
@@ -3321,9 +3712,9 @@ describe("ForgeService", () => {
await expect(
service.getCurrentPullRequestStatus({
cwd: "/repo",
cwd,
headRef: "feature/fork",
headSha: "2222222222222222222222222222222222222222",
headSha: workspaceCommit,
}),
).resolves.toMatchObject({ state: "merged" });
expect(runner.calls.some((call) => call.args[0] === "pr" && call.args[1] === "list")).toBe(
@@ -3331,7 +3722,117 @@ describe("ForgeService", () => {
);
});
it("prefers an exact terminal head and otherwise the most recently updated terminal PR", async () => {
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 () => {
const owner = { login: "forkOwner" };
const terminal = ({
number,
@@ -3368,9 +3869,15 @@ describe("ForgeService", () => {
});
for (const [headSha, expected] of [
["old", 41],
["other", 42],
["other", undefined],
] as const) {
const runner = createScriptedRunner([JSON.stringify(older), JSON.stringify([older, newer])]);
const runner = createScriptedRunner([
JSON.stringify(older),
JSON.stringify([older, newer]),
...(headSha === "old"
? [directCommitsJson(["old"])]
: [directCommitsJson(["old"]), directCommitsJson(["new"])]),
]);
const service = createGitHubService({
runner: runner.runner,
resolveGhPath: async () => "/usr/bin/gh",
@@ -3410,6 +3917,7 @@ describe("ForgeService", () => {
const runner = createScriptedRunner([
JSON.stringify(closedDraft),
JSON.stringify([closedDraft, merged]),
directCommitsJson(["exact"]),
]);
const service = createGitHubService({
runner: runner.runner,
@@ -3482,6 +3990,7 @@ describe("ForgeService", () => {
parent: { owner: { login: "acme" }, name: "app" },
}),
"[]",
directCommitsJson(["checkout-head"]),
]);
const service = createGitHubService({
runner: runner.runner,
@@ -3510,7 +4019,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", 8],
["CLOSED", "other", "2026-07-18T12:00:00Z", undefined],
] as const) {
const parent = {
...local,
@@ -3521,6 +4030,11 @@ 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({
@@ -3530,6 +4044,7 @@ describe("ForgeService", () => {
}),
JSON.stringify([{ number: 8 }]),
JSON.stringify(parent),
...commitResponses,
]);
const service = createGitHubService({
runner: runner.runner,
@@ -3626,6 +4141,8 @@ 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 {
+346 -59
View File
@@ -1,3 +1,7 @@
import {
pullRequestContainsCommit,
createPullRequestCommitReader,
} from "./pull-request-contains-commit.js";
import { z } from "zod";
import {
isGitHubHost,
@@ -633,6 +637,22 @@ 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(""),
@@ -1125,6 +1145,7 @@ interface GitHubBatchDistribution {
}
interface ResolvedPullRequestCandidate {
membership: PullRequestMembership;
status: CurrentPullRequestStatus;
headSha?: string;
headRepositoryOwner?: string;
@@ -1173,6 +1194,9 @@ 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 }
@@ -1661,15 +1685,32 @@ 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,
aliases: response.aliases,
repositories,
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);
@@ -1680,6 +1721,7 @@ 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 });
@@ -1688,7 +1730,7 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G
const isPaused = await pauseGitHubPollsAfterRateLimit(input.firstEntry, error);
const partial = extractGraphqlBatchAliasesFromError(error);
if (isPaused || !partial) {
reportGitHubBatchError(input.entries, error);
(input.onError ?? reportGitHubBatchError)(input.entries, error);
return null;
}
const stdout = error instanceof GitHubCommandError ? (error.stdout ?? "") : "";
@@ -1702,21 +1744,145 @@ 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[];
aliases: Record<string, unknown>;
repositories: Map<GitHubBatchPollEntry, BatchPollRepository>;
args: string[];
startedAt: number;
failedCommitEntries: ReadonlySet<GitHubBatchPollEntry>;
}): GitHubBatchDistribution {
const distribution: GitHubBatchDistribution = {
pendingChecks: [],
legacyFallback: [],
redirected: [],
};
for (const [index, entry] of input.entries.entries()) {
const aliasValue = input.aliases[batchAlias(index)];
const repository = aliasValue ? BatchPollRepositorySchema.safeParse(aliasValue) : null;
if (!repository?.success) {
for (const entry of input.entries) {
if (input.failedCommitEntries.has(entry)) continue;
const repository = input.repositories.get(entry);
if (!repository) {
updatePollTargetAfterError(
entry.target,
new GitHubCommandError({
@@ -1728,32 +1894,29 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G
);
continue;
}
if (repository.data.isFork && repository.data.parent) {
const forkOwner = repository.data.owner?.login ?? entry.owner;
if (repository.isFork && repository.parent) {
const forkOwner = repository.owner?.login ?? entry.owner;
pollRepositoryRedirects.set(batchRepositoryRedirectKey(entry), {
owner: repository.data.parent.owner.login,
name: repository.data.parent.name,
owner: repository.parent.owner.login,
name: repository.parent.name,
headRepositoryOwner: forkOwner,
});
distribution.redirected.push(entry);
continue;
}
const node = selectBatchPollNode(entry, repository.data);
const node = selectBatchPollNode(entry, repository);
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.data.isFork ||
repository.data.pullRequests.nodes.length >= BATCH_PR_CANDIDATE_LIMIT
) {
if (repository.isFork || repository.pullRequests.nodes.length >= BATCH_PR_CANDIDATE_LIMIT) {
distribution.legacyFallback.push(entry.target);
} else {
finalizeBatchPollTarget({
entry,
node: null,
repository: repository.data,
repository: repository,
rollup: null,
startedAt: input.startedAt,
});
@@ -1770,7 +1933,7 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G
finalizeBatchPollTarget({
entry,
node,
repository: repository.data,
repository: repository,
rollup: cachedRollup,
startedAt: input.startedAt,
});
@@ -1778,7 +1941,7 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G
distribution.pendingChecks.push({
entry,
node,
repository: repository.data,
repository: repository,
cacheKey: frozenKey,
});
}
@@ -1802,41 +1965,59 @@ 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 {
// 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 resolution = inspectBatchPollCandidates(
entry,
batchPollNodesForWorkspace(entry, repository),
);
return resolution.pending.length ? null : resolution.match;
}
function inspectBatchPollCandidates(
entry: GitHubBatchPollEntry,
nodes: BatchPollPrNode[],
): { match: BatchPollPrNode | null; pending: BatchPollPrNode[] } {
const nodeByCandidate = new Map<ResolvedPullRequestCandidate, BatchPollPrNode>();
const candidates: ResolvedPullRequestCandidate[] = [];
for (const node of repository.pullRequests.nodes) {
for (const node of nodes) {
const candidate = toCurrentPullRequestCandidate(
toBatchCurrentPullRequestItem(node, undefined),
entry.target.headRef,
);
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;
}
if (!candidate) continue;
candidate.membership = batchMembership.get(node) ?? { kind: "unknown" };
nodeByCandidate.set(candidate, node);
candidates.push(candidate);
}
const match = pickPullRequestCandidate({
const resolution = inspectPullRequestCandidates({
candidates,
headRef: entry.target.headRef,
headSha: entry.target.headSha,
headRepositoryOwner,
headRepositoryOwner: entry.target.headRepositoryOwner ?? entry.headRepositoryOwner,
});
return match ? (nodeByCandidate.get(match) ?? null) : null;
return {
match: resolution.match ? nodeByCandidate.get(resolution.match)! : null,
pending: resolution.pending.map((candidate) => nodeByCandidate.get(candidate)!),
};
}
async function loadBatchPullRequestChecks(
@@ -1961,7 +2142,14 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G
toBatchCurrentPullRequestItem(node, input.rollup ?? undefined),
entry.target.headRef,
);
status = built ? { ...built, forgeSpecific: { forge: "github", ...facts } } : null;
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;
}
const cacheKey = buildCacheKey({
cwd: entry.target.cwd,
@@ -2177,6 +2365,7 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G
readOptions: input,
load: async () => {
const status = await resolveCurrentPullRequestView({
readCommits,
cwd: input.cwd,
headRef: input.headRef,
headSha: input.headSha,
@@ -2989,20 +3178,13 @@ 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 viewMatch = viewCandidate
? pickPullRequestCandidate({
candidates: [viewCandidate],
headRef: options.headRef,
headSha: options.headSha,
headRepositoryOwner: options.headRepositoryOwner,
})
: null;
if (viewMatch?.status.state === "open") {
return viewMatch.status;
}
const viewCandidates = viewCandidate ? [viewCandidate] : [];
const open = pickPullRequestCandidate({ ...options, candidates: viewCandidates });
if (open?.status.state === "open") return open.status;
let headRepositoryOwner = options.headRepositoryOwner;
@@ -3012,13 +3194,17 @@ async function resolveCurrentPullRequestView(options: {
const parentOwner = repo?.parent?.owner?.login;
const parentName = repo?.parent?.name;
if (!forkOwner) {
return viewMatch?.status ?? null;
const match = await loadAndPickPullRequestCandidate({
...options,
candidates: viewCandidates,
});
return match?.status ?? null;
}
if (parentOwner && parentName) {
return resolveForkPullRequestView({
...options,
forkOwner,
viewMatch,
viewCandidate,
repo: `${parentOwner}/${parentName}`,
});
}
@@ -3028,10 +3214,14 @@ async function resolveCurrentPullRequestView(options: {
const candidates = await listCurrentPullRequestCandidates({
cwd: options.cwd,
headRef: options.headRef,
headRepositoryOwner,
run: options.run,
});
const match = pickPullRequestCandidate({
candidates: viewMatch ? [...candidates, viewMatch] : candidates,
const match = await loadAndPickPullRequestCandidate({
readCommits: options.readCommits,
cwd: options.cwd,
run: options.run,
candidates: [...candidates, ...viewCandidates],
headRef: options.headRef,
headSha: options.headSha,
headRepositoryOwner,
@@ -3052,8 +3242,9 @@ async function resolveForkPullRequestView(options: {
headRef: string;
headSha?: string;
forkOwner: string;
viewMatch: ResolvedPullRequestCandidate | null;
viewCandidate: ResolvedPullRequestCandidate | null;
repo: string;
readCommits: ReturnType<typeof createPullRequestCommitReader>;
run: (args: string[], options: GitHubCommandRunnerOptions) => Promise<string>;
}): Promise<CurrentPullRequestStatus | null> {
const numbers = await listForkPullRequestNumbers(options);
@@ -3067,16 +3258,20 @@ async function resolveForkPullRequestView(options: {
}),
),
);
const match = pickPullRequestCandidate({
const match = await loadAndPickPullRequestCandidate({
readCommits: options.readCommits,
cwd: options.cwd,
run: options.run,
candidates: [
...candidates.filter(
(candidate): candidate is ResolvedPullRequestCandidate =>
candidate !== null && candidate.headRepositoryOwner === options.forkOwner,
),
...(options.viewMatch ? [options.viewMatch] : []),
...(options.viewCandidate ? [options.viewCandidate] : []),
],
headRef: options.headRef,
headSha: options.headSha,
headRepositoryOwner: options.forkOwner,
});
return match?.status ?? null;
}
@@ -3170,6 +3365,62 @@ 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;
@@ -3183,10 +3434,11 @@ async function tryCurrentPullRequestView(options: {
run: options.run,
args,
});
return parseCurrentPullRequestCandidate(stdout, options.headRef, {
const candidate = parseCurrentPullRequestCandidate(stdout, options.headRef, {
args: [...args, "--json", CURRENT_PR_STATUS_FIELDS],
cwd: options.cwd,
});
return candidate;
} catch (error) {
if (isNoPullRequestFoundError(error)) {
return null;
@@ -3198,6 +3450,7 @@ 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"];
@@ -3207,10 +3460,11 @@ async function listCurrentPullRequestCandidates(options: {
run: options.run,
args,
});
return parseCurrentPullRequestCandidateList(stdout, options.headRef, {
const candidates = parseCurrentPullRequestCandidateList(stdout, options.headRef, {
args: [...args, "--json", CURRENT_PR_STATUS_FIELDS],
cwd: options.cwd,
});
return candidates;
} catch (error) {
if (isNoPullRequestFoundError(error)) {
return [];
@@ -3428,6 +3682,7 @@ function toCurrentPullRequestCandidate(
const headSha = item.headRefOid;
return {
status,
membership: { kind: "unknown" },
updatedAt: item.updatedAt,
...(headSha ? { headSha } : {}),
...(headRepositoryOwner ? { headRepositoryOwner } : {}),
@@ -3448,6 +3703,38 @@ 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;
@@ -3460,7 +3747,7 @@ function pickPullRequestCandidate(options: {
matching.sort((left, right) =>
comparePullRequestCandidatePreference(left, right, options.headSha),
);
return matching[0] ?? null;
return matching;
}
function comparePullRequestCandidatePreference(
@@ -1,3 +1,5 @@
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";
@@ -375,6 +377,7 @@ 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(" ")}`);
});
@@ -386,25 +389,93 @@ describe("createGitLabService", () => {
});
expect(status?.number).toBe(270);
expect(calls[1]).toEqual(["mr", "view", "270", "-F", "json"]);
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 });
});
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: "1111111111111111111111111111111111111111",
sha: pullRequestCommit,
};
const { service, calls } = makeService((args) =>
ok(JSON.stringify(args[1] === "list" ? [stale] : stale)),
);
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));
});
await expect(
service.getCurrentPullRequestStatus({
cwd: "/repo",
cwd,
headRef: "dev",
headSha: "2222222222222222222222222222222222222222",
headSha: workspaceCommit,
}),
).resolves.toMatchObject({ state: "merged" });
expect(calls[0]).toEqual(currentMrListArgs("dev"));
+33 -9
View File
@@ -1,3 +1,7 @@
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";
@@ -153,6 +157,7 @@ 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(),
@@ -739,6 +744,7 @@ 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),
@@ -919,6 +925,7 @@ 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;
@@ -992,15 +999,32 @@ 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 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;
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;
}
/**
@@ -0,0 +1,23 @@
/** 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;
};
}
@@ -355,13 +355,22 @@ it.each(["detach", "closeTerminals"] as const)(
...nodeTerminalCommand("setInterval(() => {}, 1000)"),
});
const [record] = await workerRecords(paseoHome);
process.kill(record!.pid, "SIGKILL");
await manager[operation]();
await expect(
manager.createTerminal({ workspaceId: "ws-stop-recovery", cwd: paseoHome }),
).rejects.toBeInstanceOf(NoTerminalWorkerAvailableError);
await manager.closeTerminals();
expect(await workerRecords(paseoHome)).toEqual([]);
const programPid = record!.terminals[0]!.pid;
try {
process.kill(record!.pid, "SIGKILL");
await manager[operation]();
await expect(
manager.createTerminal({ workspaceId: "ws-stop-recovery", cwd: paseoHome }),
).rejects.toBeInstanceOf(NoTerminalWorkerAvailableError);
await manager.closeTerminals();
expect(await workerRecords(paseoHome)).toEqual([]);
} finally {
// A hard-crashed Windows worker can leave its terminal program alive.
// The test owns that program even after the manager retires its record.
if (isProcessAlive(programPid)) process.kill(programPid, "SIGKILL");
await waitForCondition(() => !isProcessAlive(programPid), 5000);
await waitForCondition(() => !isProcessAlive(record!.pid), 5000);
}
},
30000,
);
@@ -0,0 +1,44 @@
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 }),
};
}