Compare commits

..
Author SHA1 Message Date
paseo-bot[bot]andClaude Opus 5.5 99ab18c473 Publish running provider subagents on the agent snapshot
The tab close asked the daemon for the agent's subagent list before
deciding, and that request resumes a released agent's provider session
only for the close to archive it. The daemon now reports how many of an
agent's provider subagents are running on its snapshot, and re-sends the
parent's snapshot when a subagent changes. The close policy reads that
field synchronously, so the request, the client cache read and the
descriptors parameter are gone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 05:48:30 +00:00
paseo-bot[bot]andClaude Opus 5.5 3e34be1228 Check the daemon's subagent list before closing an agent tab
The app only holds provider subagents for agents it has rendered or
heard about while connected. After a reload, a restored tab that was
never activated had no subagents loaded, so closing it still archived
the agent without asking while its background subagent ran. Before
deciding, the tab close now refreshes that agent's subagent list from
the daemon, and falls back to the loaded list if the request fails.

Refs #10038

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 05:09:17 +00:00
paseo-bot[bot]andClaude Opus 5.5 20d7ae6cd5 Count running background subagents when closing an agent tab
Claude reports background subagents in the subagents track, not in the
agent's background work count. An agent whose turn ended while a
background subagent was still working was idle with no background work,
so closing its tab still archived it without asking and stopped the
subagent. The close-tab policy now also asks when the agent has a
running provider subagent.

Refs #10038

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 04:56:50 +00:00
paseo-bot[bot]andClaude Opus 5.5 32e7df0554 Ask before closing a tab archives an agent with background work
Closing a root agent's tab archives it, and archiving stops background
work the agent left running after its turn ended, such as a background
subagent. The "Archive running agent?" confirmation only checked
status === "running", so an idle agent with background work was
archived without asking. The close-tab policy now decides whether to
confirm, and counts background work as running.

Closes #10038

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 04:48:35 +00:00
Mohamed Boudra 91e7293773 Hide historical PR badges on the default branch (#10053)
Hide closed and merged requests on the origin repository’s default branch. Keep branch-based status matching for feature workspaces.

Closes #9908.
2026-11-18 11:08:44 +07:00
paseo-bot[bot]andClaude Opus 5.5 63a33ac3fd Let plugin screens use the plugin state hooks (#10049)
* Let plugin screens use the plugin state hooks

A plugin screen opened from the Command Center or the sidebar showed
"Plugin failed: Plugin state hooks must run inside a plugin host" as soon
as it called useWorkspaces, useAgents or another state hook. Every plugin
host paired the installation provider with its own state provider, and
the screen host and the plugin settings host did not.

The installation provider now supplies the state source for the
installation's host, so every surface rendered under it can read state,
and the hosts no longer wrap a second provider of their own.

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

* Keep a sidebar view's cross-host state in its hooks

A sidebar view renders once across every connected host and builds an
unscoped state source for that. After the installation provider took
over the state source, the environment provider dropped the view's own
source, so its hooks read state scoped to one host. The installation
provider now takes the surface's source when one is passed and falls
back to the installation's host.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.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-18 04:01:21 +00:00
paseo-bot[bot]andClaude Opus 5.5 a5edd91f91 Delete a stopped terminal worker's copy on Windows (#10039)
* fix(terminal): delete a stopped worker's copy on Windows

Windows keeps a just-exited worker's files open for a moment, so the
single rm in pruneTerminalWorkerRuntimes failed and left the copy until
the next daemon start. Retry the delete for up to 5.5s.

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

* fix(terminal): bound the Windows retry of a worker copy delete

rm's maxRetries repeats at every directory level, so a file that stays
locked deep in node-pty would hold daemon start and stop far past the
intended window. Retry one rm per attempt for up to 3s instead.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.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-18 03:26:42 +00:00
paseo-bot[bot]andClaude Opus 5.5 e44edf5b35 Keep the sidebar's projects when the app renders while restoring hosts (#10042)
* fix(app): publish restored hosts together with their directory sync

A component that rendered while the host registry restored the project
icon cache saw the host but found no directory sync for it, so its
directory demand was dropped and the sidebar stayed on No projects yet
for the session. Hosts are now published in the same step that creates
their runtimes.

Fixes #9996

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

* refactor(app): publish restored hosts through setHostsAndSync

Every host-list change now goes through the one method that assigns the
hosts, creates their runtimes, and notifies listeners in a single step.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.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-18 03:16:36 +00:00
Mohamed BoudraandOkan YILDIRIM 59d6018dac Preserve commits when archiving workspaces (#10009)
* fix(workspaces): preserve commits when archiving worktrees

A removed worktree can be the only reference to its HEAD. Keep that commit before deletion and record the checkout so detached workspaces restore at the same commit.

Co-authored-by: Okan YILDIRIM <63511519+ragokan@users.noreply.github.com>

* fix(workspaces): restore saved checkouts through one git path

Keep existing archive and deletion behavior when Git cannot read a worktree HEAD, and record every readable checkout for a common restore path.

* fix(workspaces): preserve git HEAD identity through restore

Record Git’s full HEAD ref or commit so restore can pass branch and detached checkouts to Git without guessing from a short name.

* fix(workspaces): scope saved HEAD to each archive

An archive with no readable checkout must not retain the HEAD saved by an earlier archive.

* test(workspaces): verify detached checkout after restore

Update the browser journey for detached restore and allow the daemon restart test enough time on Windows runners.

---------

Co-authored-by: Okan YILDIRIM <63511519+ragokan@users.noreply.github.com>
2026-11-18 10:10:45 +07:00
paseo-bot[bot]andClaude Opus 5.5 b24eab785b Reload the desktop window when its renderer exits (#10035)
* Reload the desktop window when its renderer exits

When the renderer process of the main window exits without a clean
shutdown (killed by an out-of-memory killer, crashed, or out of memory),
Electron keeps the window frame but shows nothing until the user presses
Ctrl+R. The main process had no handler for render-process-gone, so it
neither recovered nor logged the exit.

The window now reloads itself and logs the exit reason to main.log. If
the renderer exits three times within a minute, it stops reloading and
logs that, so a page that crashes on load does not restart in a loop.

Fixes #9999

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

* Leave a renderer exit before the first page commits to Chromium

Before the window's first navigation commits, Chromium finishes it in a
new renderer by itself. Reloading at that point aborted the initial
loadURL with ERR_ABORTED, which fails desktop startup. Skip the reload
while the window has no committed URL.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.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-18 02:04:06 +00:00
1821ac3f93 Let a steered message wait out a Claude compaction instead of cancelling it (#10028)
* Let a steer wait out a Claude compaction instead of cancelling it

While Claude compacted, the Claude session answered every steer with
"unavailable". The agent manager reads that as "replace the turn", so
it interrupted the turn and Claude Code printed "Compaction canceled.".
Claude Code already holds a `next`-priority message until compaction
finishes, so the session now accepts the steer during compaction.

Co-authored-by: NightMachinery <36224762+NightMachinery@users.noreply.github.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Steer only while the compaction is still running in the real Claude test

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

---------

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: NightMachinery <36224762+NightMachinery@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 01:06:23 +00:00
a1088a787d Report background work from get_agent_status and list_agents (#10022)
The MCP agent tools serialized live agents without the background work
summary that the WebSocket snapshot carries, so a parent agent saw an
idle worker with a running background shell as plain idle. Both tools now
add the same summary the session adds, omitted when the agent has none.

Co-authored-by: Orcun Simsek <1612171+ortschun@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 22:54:59 +00:00
JIHUN LEEandClaude Opus 5.5 576d0320c8 Keep Android text at the window's density on Samsung DeX (#9995)
React Native 0.86 converts between px and dp with the density of the
phone's built-in display, while Fabric lays out at the window's density.
In a DeX window (240 dpi on a 360 dpi phone) every text box came out at
two thirds of the height its text needed, so the text was clipped.

Backport the rule from react/react-native#59087: right after React
Native reads the display (when it creates the root view and on each
configuration change), restore the window's density and keep only the
display's size. Remove once the app runs React Native 0.89 or later
with useWindowDensityForDisplayMetricsAndroid on.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 21:08:05 +00:00
paseo-bot[bot]andClaude Opus 5.5 c8e3d67e29 Wait for each plugin content subscription id before checking its release (#10012)
The plugin-buttons journey reads the details' event subscription id to
check that closing, crashing and disabling the content releases it. The
id arrives with the daemon's subscription response, after the details
render. The first open already waited for it; the reopens read it as
soon as the cached summary showed, so the id could still be empty and
the release poll then waited for an id that never exists.

Every read now waits for a non-empty id.

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 18:01:24 +00:00
95f2c7d16a Keep a Claude agent's process and background work when its effort level changes (#10008)
Changing the thinking level of a running Claude agent marked its query for a
restart. The next turn, mode change or model change then retired the Claude
process, which ended every background shell, workflow and subagent it ran with
"connection lost".

A move between two effort levels now goes to the running query through
applyFlagSettings({ effortLevel }), as Fast mode already does, and marks no
restart. Switching thinking off, to ultracode or back to the default still
restarts, because those change how the query is launched. If the running
process does not take the change, the old restart path runs, so the change is
never lost.


Row: app-built-from-one-set
Paseo: c6210e21-fc13-4dfa-adfc-43a050c7d75a

Co-authored-by: gilad-rubin <6134299+gilad-rubin@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 16:57:22 +00:00
paseo-bot[bot]andClaude Opus 5.5 2c2385f362 Create the workspace in the caller's directory when --path is relative (#10010)
* Create the workspace in the caller's directory when --path is relative

`paseo workspace create --path .` adopted the daemon's working directory
instead of the directory the command ran in. The CLI sent the relative
path unchanged, and the daemon resolved it against its own cwd. The CLI
now resolves a relative --path against the caller's directory before it
sends the request, as it already does when --path is omitted. Absolute
POSIX and Windows paths pass through unchanged so a remote daemon on
another operating system still gets the path as written.

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

* Leave a home-relative --path for the daemon to expand

Resolving every non-absolute --path against the caller's directory turned
`--path=~/repo` (and a quoted "~/repo") into `<cwd>/~/repo`. Before this
change the daemon expanded the leading ~ itself. `~` and `~/…` now pass
through unchanged again.

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

* Send a relative --path to an explicit daemon endpoint as written

The CLI already resolves caller paths only for a local daemon and sends
them unchanged to an explicit --host endpoint (resolveRepositoryDirectory,
project create). workspace create, and paseo run, which builds its
workspace source through it, now follow the same rule instead of turning
a relative path into a path on the caller's machine for a remote daemon.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.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 15:51:43 +00:00
paseo-bot[bot]andDominic Anaeto 7f0fe57c48 Settle a stuck agent run after a repeated cancel (#9774)
A force-cancel finalizes turn X in the daemon while the provider keeps
running it, so the next run can be bound to the same X. handleStreamEvent
dropped every terminal for a finalized turn id, including the synthetic
turn_canceled that cancelAgentRunNow dispatches for the tracked run and
the provider's own terminal. The run never settled, cancelAgentRunNow
waited on it forever, and every later cancel, reload and send queued
behind it until the daemon restarted.

A terminal for the tracked run's own turn id is no longer dropped.

Fixes #6355
Supersedes #8405

Co-authored-by: Dominic Anaeto <dominic.anaeto@gmail.com>
2026-11-17 15:08:26 +00:00
paseo-bot[bot]andClaude Opus 5.5 94f2df6263 Keep the Import Session list in place when Load more fetches the next page (#9974)
Tapping Load more emptied the list until the larger page arrived: the sheet
showed "Loading sessions...", unmounted the virtualized list, and brought it
back scrolled to the top. The sessions queries set keepPreviousData, but
useQueries gives a changed key a new observer with no previous data, so the
placeholder was always empty. The placeholder is now the cached page that
Load more grew from, for the same scope, search, and provider.

The compact import-session journey flaked on this in CI: its scroll helper
resolved a row, the list was replaced before the helper ran, and the walk
up from the detached row found no scroller. The helper now scrolls the list
itself, and the journey checks that Load more keeps the reader down the
list.

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 12:00:55 +00:00
paseo-bot[bot]andpanta82 02124454bc Keep failed downloads inside the app on web and desktop (#9937)
On web and desktop, Download over a direct connection now fetches the file and saves it from a blob instead of navigating the window to the host URL. A rejected or unreachable download shows an error in the download toast and the app stays on the workspace. The daemon's HTTP CORS check uses the same origin rule as the WebSocket upgrade.

Closes #9895

Co-authored-by: panta82 <4291324+panta82@users.noreply.github.com>
2026-11-17 08:04:50 +00:00
94 changed files with 2290 additions and 538 deletions
+8
View File
@@ -121,6 +121,14 @@ from `packages/app/android`:
These check terminal arrow ownership, held-key repeats and modifiers, and ordinary text-field editing.
Run the display density regression tests the same way:
```bash
./gradlew :paseo-display-metrics:connectedDebugAndroidTest --no-daemon --max-workers=2 -Dorg.gradle.parallel=false
```
These check that React Native sizes text at the window's density when the window is on another display, such as Samsung DeX.
### Diagnostic logs without ADB
In a dogfood build, open Android's Files app → Downloads → **Paseo diagnostics** and share all
+4 -2
View File
@@ -99,8 +99,10 @@ Register the adapter in `defaultForgeRegistry` with:
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
HEAD, then the most recently updated terminal request. When the forge identifies
the checkout's branch as the origin repository's default branch, only open
requests are eligible. A reused feature 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.
+2
View File
@@ -7,6 +7,7 @@ const withAndroidProfileable = require("./plugins/with-android-profileable");
const withFdroidAutolinking = require("./plugins/with-fdroid-autolinking");
const withPasteInput = require("./plugins/with-paste-input");
const withAndroidScroll = require("./modules/paseo-scroll/app.plugin");
const withAndroidDisplayMetrics = require("./modules/paseo-display-metrics/app.plugin");
const { getNativeReleaseVersion } = require("./native-release-version");
const appVariant = process.env.APP_VARIANT ?? "production";
const isFdroidBuild = process.env.PASEO_FDROID_BUILD === "1";
@@ -146,6 +147,7 @@ export default {
"expo-router",
withPasteInput,
withAndroidScroll,
withAndroidDisplayMetrics,
[withAndroidAsyncStorageSize, 64],
...buildProfile.cameraPlugins,
withAndroidOptionalCamera,
@@ -466,12 +466,12 @@ test("downloads a file over direct TCP with its original filename and bytes", as
await gotoWorkspace(page, workspace.workspaceId);
await openFileExplorer(page);
const daemonRequest = page.waitForRequest("**/api/files/download?*");
const downloaded = await downloadFileFromExplorer(page, fileName);
const url = new URL(downloaded.url());
expect(url.protocol).toBe("http:");
expect(url.port).toBe(getE2EDaemonPort());
expect(url.pathname).toBe("/api/files/download");
expect(url.searchParams.get("token")).toBeTruthy();
const requestUrl = new URL((await daemonRequest).url());
expect(requestUrl.port).toBe(getE2EDaemonPort());
expect(requestUrl.searchParams.get("token")).toBeTruthy();
expect(new URL(downloaded.url()).protocol).toBe("blob:");
expect(downloaded.suggestedFilename()).toBe(fileName);
const savedFile = testInfo.outputPath(fileName);
await downloaded.saveAs(savedFile);
@@ -479,6 +479,45 @@ test("downloads a file over direct TCP with its original filename and bytes", as
expect(await readFile(savedFile)).toEqual(source);
});
test("keeps the app open and shows the error when the host rejects a download", async ({
page,
}, testInfo) => {
const fileName = "removed-during-download.bin";
const filePath = path.join(workspace.workspaceDirectory, fileName);
const source = Buffer.from([0, 1, 2, 255]);
await writeFile(filePath, source);
await gotoWorkspace(page, workspace.workspaceId);
await openFileExplorer(page);
const workspaceUrl = page.url();
// The file disappears after the token is issued, so the real daemon answers 404.
await page.route(
"**/api/files/download?*",
async (route) => {
await rm(filePath);
await route.continue();
},
{ times: 1 },
);
await page
.getByTestId("file-explorer-tree-scroll")
.getByText(fileName, { exact: true })
.click({ button: "right" });
await page.getByRole("menuitem", { name: "Download", exact: true }).click();
await expect(
page.getByText("Failed to download file (HTTP 404).", { exact: true }),
).toBeVisible();
expect(page.url()).toBe(workspaceUrl);
await writeFile(filePath, source);
const downloaded = await downloadFileFromExplorer(page, fileName);
const savedFile = testInfo.outputPath(fileName);
await downloaded.saveAs(savedFile);
expect(await readFile(savedFile)).toEqual(source);
expect(page.url()).toBe(workspaceUrl);
});
test("downloads an unsupported binary from its preview with original filename and bytes", async ({
page,
}, testInfo) => {
@@ -362,6 +362,16 @@ test.describe("Plugin sidebar items", () => {
});
});
test("a plugin screen reads workspaces through the state hooks", async ({ page }) => {
await page.setViewportSize(WIDE);
await gotoWorkspace(page, workspaceId);
await expect(headerRow(page, SHOWCASE_PLUGIN_ID, "deploys")).toBeVisible({ timeout: 30_000 });
await runCommand(page, "Open plugin workspaces");
await expect(screenTitle(page)).toHaveText("Workspaces");
await expect(page.getByText(`Workspace ${workspaceId}`, { exact: true })).toBeVisible();
await expect(page.getByText("Plugin failed", { exact: false })).toHaveCount(0);
});
test("a header row's shortcut hint presses the row", async ({ page }) => {
await page.setViewportSize(WIDE);
await gotoWorkspace(page, workspaceId);
@@ -361,6 +361,10 @@ test.describe("Worktree restore", () => {
cwd: backingWorktree.workspaceDirectory,
stdio: "pipe",
});
const originalHead = execFileSync("git", ["rev-parse", "HEAD"], {
cwd: backingWorktree.workspaceDirectory,
encoding: "utf8",
}).trim();
const created = await worktreeClient.createWorkspace({
source: { kind: "directory", path: backingWorktree.workspaceDirectory },
title: "Sample workspace",
@@ -389,10 +393,7 @@ test.describe("Worktree restore", () => {
await page.getByTestId(`agent-row-${getServerId()}-${agent.id}`).click();
await expect(page.getByText("Workspace archived", { exact: true })).toBeVisible();
await expect(
page.getByText(
"Restore Sample workspace to return to its agents. A new branch will start from the saved base or the repository default.",
{ exact: true },
),
page.getByText("Restore Sample workspace to return to its agents.", { exact: true }),
).toBeVisible();
await captureBranchlessRestoreStep(page, "01-restore-workspace.png");
@@ -409,17 +410,13 @@ test.describe("Worktree restore", () => {
cwd: backingWorktree.workspaceDirectory,
encoding: "utf8",
}).trim();
const defaultHead = execFileSync("git", ["rev-parse", "main"], {
cwd: tempRepo.path,
encoding: "utf8",
}).trim();
expect(restoredHead).toBe(defaultHead);
expect(restoredHead).toBe(originalHead);
expect(
execFileSync("git", ["branch", "--show-current"], {
cwd: backingWorktree.workspaceDirectory,
encoding: "utf8",
}).trim(),
).toMatch(/^restored\//);
).toBe("");
});
test("restore failure stays visible and permits a successful retry", async ({ page }) => {
@@ -97,18 +97,15 @@ export class ImportSessionFlow {
await target.scrollIntoViewIfNeeded();
await expect(target).toBeInViewport();
}
/**
* Scrolls the virtualized list, the only one that leaves rows unmounted. A row handle is no way
* in: the list unmounts rows as it scrolls, and a detached row has no scroller above it.
*/
private async scrollList(forward: boolean) {
await this.page
.locator('[data-testid^="import-session-session-"]')
.first()
.evaluate((row, advance) => {
let element = row.parentElement;
while (element && !["auto", "scroll"].includes(getComputedStyle(element).overflowY))
element = element.parentElement;
if (!element) throw new Error("Import list has no scroll owner");
element.scrollTop = advance ? element.scrollTop + element.clientHeight * 0.8 : 0;
element.dispatchEvent(new Event("scroll"));
}, forward);
await this.page.getByTestId("import-session-list").evaluate((list, advance) => {
list.scrollTop = advance ? list.scrollTop + list.clientHeight * 0.8 : 0;
list.dispatchEvent(new Event("scroll"));
}, forward);
}
async search(query: string) {
await this.page.getByTestId("import-session-search").fill(query);
@@ -120,11 +117,18 @@ export class ImportSessionFlow {
await this.page.getByTestId("import-session-search").fill("");
await expect(this.page.getByTestId("import-session-load-more")).toBeVisible();
}
/** Load more keeps the reader down the list instead of sending them back to the top. */
async loadMore() {
await this.page.getByTestId("import-session-load-more").click();
const loadMore = this.page.getByTestId("import-session-load-more");
const topRow = this.page.getByTestId((await this.rowIds())[0]!);
await expect(topRow).toBeInViewport();
await loadMore.click();
// The next page is the last and short, so the button leaves once it lands.
await expect(loadMore).toHaveCount(0);
await expect(this.page.getByText("Loading sessions...", { exact: true })).toHaveCount(0);
await expect(topRow).not.toBeInViewport();
await this.revealSession("fixture-root-20");
await expect(this.page.getByText("Root session 20", { exact: true })).toBeInViewport();
await expect(this.page.getByTestId("import-session-load-more")).toHaveCount(0);
}
async retryProvider(provider: string, label: string) {
await this.expectProviderError(label);
@@ -198,6 +198,14 @@ async function expectDetails(page: Page) {
await expect(page.getByText("All systems operational", { exact: true })).toBeInViewport();
}
// The details render before the daemon answers their event subscription, and reopened
// details show the cached summary at once, so wait for the subscription id to arrive.
async function readContentObservation(page: Page): Promise<string> {
const observation = page.getByLabel("Content observation", { exact: true });
await expect(observation).not.toHaveText("");
return (await observation.textContent())!;
}
function workspaceMenuRow(page: Page, title: string): Locator {
return compactWorkspaceMenu(page).getByRole("menuitem", { name: title, exact: true });
}
@@ -354,14 +362,12 @@ export async function withButtonShowcase(
test.step("closing and crashing content release its owner while sibling buttons and app remain live", async () => {
await press(page, "Header status");
await expectDetails(page);
const observation = page.getByLabel("Content observation", { exact: true });
await expect(observation).not.toHaveText("");
const first = (await observation.textContent())!;
const first = await readContentObservation(page);
await press(page, "Close deployment details");
await expect.poll(() => released.has(first)).toBe(true);
await press(page, "Composer status");
await expectDetails(page);
const second = (await observation.textContent())!;
const second = await readContentObservation(page);
expect(second).not.toBe(first);
await workspace.client.renameProject(workspace.projectId, "Observer control");
await expect(page.getByText("Observed updates: 1", { exact: true })).toBeVisible();
@@ -373,7 +379,7 @@ export async function withButtonShowcase(
await page.keyboard.press("Escape");
await press(page, "Header status");
await expectDetails(page);
const recovered = (await observation.textContent())!;
const recovered = await readContentObservation(page);
expect([first, second]).not.toContain(recovered);
await showcase.setTitle("Healthy app after button failure");
await expect(page.getByTestId("workspace-header-title")).toHaveText(
@@ -687,9 +693,7 @@ export async function withButtonShowcase(
page,
page.getByRole("button", { name: "Close deployment details", exact: true }),
);
const observation = page.getByLabel("Content observation", { exact: true });
await expect(observation).not.toHaveText("");
const owner = (await observation.textContent())!;
const owner = await readContentObservation(page);
await showcase.disable();
await expect.poll(() => released.has(owner)).toBe(true);
await expect(
@@ -15,8 +15,18 @@ export const COMPACT = { width: 390, height: 844 };
/** A plugin written against the current API: a screen, header and footer items, a command. */
const SHOWCASE_SOURCE = `import React from "react";
import { Pressable, Text, View } from "react-native";
import { useWorkspaces } from "@getpaseo/plugin/client";
import { SidebarRow } from "@getpaseo/plugin/client/ui";
function WorkspacesScreen({ theme }) {
const workspaces = useWorkspaces();
return (
<View style={{ flex: 1, padding: 24, gap: 8 }}>
{workspaces.map((ref) => <Text key={ref.id} style={{ color: theme.colors.foreground }}>{"Workspace " + ref.id}</Text>)}
</View>
);
}
function DeploysScreen({ theme }) {
return <View style={{ flex: 1, padding: 24 }}><Text style={{ color: theme.colors.foreground }}>Deploys screen body</Text></View>;
}
@@ -63,11 +73,13 @@ function Broken() {
export default function contribute(client) {
client.addScreen({ id: "deploys", title: "Deploys", Component: DeploysScreen });
client.addScreen({ id: "workspaces", title: "Workspaces", Component: WorkspacesScreen });
client.addSidebarHeaderItem({ id: "deploys", title: "Deploys", Component: DeploysItem });
client.addSidebarHeaderItem({ id: "broken", title: "Broken header", Component: Broken });
client.addSidebarFooterItem({ id: "sync", title: "Sync", Component: SyncItem });
client.addSidebarFooterItem({ id: "broken", title: "Broken footer", Component: Broken });
client.addCommandCenterItem({ id: "open-deploys", title: "Open deploys", icon: "Rocket", context: "global", onSelect: (ctx) => ctx.openScreen({ screenId: "deploys" }) });
client.addCommandCenterItem({ id: "open-workspaces", title: "Open plugin workspaces", icon: "List", context: "global", onSelect: (ctx) => ctx.openScreen({ screenId: "workspaces" }) });
return () => {};
}
`;
@@ -0,0 +1,2 @@
/android/.cxx/
/android/build/
@@ -0,0 +1,23 @@
apply plugin: 'com.android.library'
group = 'sh.paseo.displaymetrics'
version = '0.1.0'
def expoModulesCorePlugin = new File(project(":expo-modules-core").projectDir.absolutePath, "ExpoModulesCorePlugin.gradle")
apply from: expoModulesCorePlugin
applyKotlinExpoModulesCorePlugin()
useCoreDependencies()
useDefaultAndroidSdkVersions()
android {
namespace "sh.paseo.displaymetrics"
defaultConfig {
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
}
dependencies {
implementation "com.facebook.react:react-android"
androidTestImplementation 'androidx.test:runner:1.6.2'
androidTestImplementation 'androidx.test.ext:junit:1.2.1'
}
@@ -0,0 +1,86 @@
package sh.paseo.displaymetrics
import android.util.DisplayMetrics
import android.util.TypedValue
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import com.facebook.react.uimanager.DisplayMetricsHolder
import com.facebook.react.uimanager.PixelUtil
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertSame
import org.junit.Assert.assertThrows
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class PaseoDisplayMetricsTest {
private lateinit var display: DisplayMetrics
@Before
fun readDisplayLikeReactNative() {
DisplayMetricsHolder.initDisplayMetrics(InstrumentationRegistry.getInstrumentation().targetContext)
display = DisplayMetricsHolder.getScreenDisplayMetrics()
}
@After
fun forgetDisplay() {
DisplayMetricsHolder.setScreenDisplayMetrics(null)
}
@Test
fun reservesRoomForTextAtTheWindowDensity() {
// A DeX window at two thirds of the phone's density (240 dpi on a 360 dpi phone). React Native
// reads the font scale from the window but the density from the phone's display.
val window = windowAt(display.densityDpi * 2 / 3)
DisplayMetricsHolder.setScreenDisplayMetrics(
DisplayMetrics().apply {
setTo(display)
scaledDensity = window.scaledDensity
},
)
assertTrue(reservedTextPx(window) < drawnTextPx())
PaseoDisplayMetrics.syncWithWindow(window)
assertEquals(drawnTextPx(), reservedTextPx(window), 0.01f)
assertEquals(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 16f, window), drawnTextPx(), 0.01f)
val synced = DisplayMetricsHolder.getScreenDisplayMetrics()
assertEquals(window.densityDpi, synced.densityDpi)
assertEquals(display.widthPixels, synced.widthPixels)
assertEquals(display.heightPixels, synced.heightPixels)
}
@Test
fun leavesTheBuiltInDisplayAlone() {
PaseoDisplayMetrics.syncWithWindow(windowAt(display.densityDpi))
assertSame(display, DisplayMetricsHolder.getScreenDisplayMetrics())
}
@Test
fun waitsForReactNativeToReadTheDisplay() {
DisplayMetricsHolder.setScreenDisplayMetrics(null)
PaseoDisplayMetrics.syncWithWindow(windowAt(display.densityDpi / 2))
assertThrows(IllegalStateException::class.java) { DisplayMetricsHolder.getScreenDisplayMetrics() }
}
private fun windowAt(densityDpi: Int): DisplayMetrics =
DisplayMetrics().apply {
setTo(display)
this.densityDpi = densityDpi
density = densityDpi.toFloat() / DisplayMetrics.DENSITY_DEFAULT
scaledDensity = density * display.scaledDensity / display.density
}
/** A 16sp font as React Native draws it, in pixels. */
private fun drawnTextPx(): Float = PixelUtil.toPixelFromSP(16f)
/** The box React Native lays out for that font, once the window renders it in pixels. */
private fun reservedTextPx(window: DisplayMetrics): Float =
PixelUtil.toDIPFromPixel(drawnTextPx()) * window.density
}
@@ -0,0 +1,43 @@
package sh.paseo.displaymetrics
import android.app.Activity
import android.util.DisplayMetrics
import com.facebook.react.uimanager.DisplayMetricsHolder
/**
* React Native 0.86 converts between px and dp, and so sizes text, with the density of the
* device's built-in display, because `DisplayMetricsHolder` reads `Display.getRealMetrics()`.
* Fabric lays out at the window's density. On a display with another density, such as a Samsung
* DeX monitor, text boxes come out too small and clip their text.
*
* Backports react/react-native#59087 (`useWindowDensityForDisplayMetricsAndroid`): keep the
* window's density and take only the size from the display. Remove once the app runs React Native
* 0.89 or later with that flag on.
*/
object PaseoDisplayMetrics {
/** Call right after React Native reads the display, which it does again on each configuration change. */
@JvmStatic
fun syncWithWindow(activity: Activity) {
syncWithWindow(activity.resources.displayMetrics)
}
@JvmStatic
fun syncWithWindow(window: DisplayMetrics) {
val screen =
try {
DisplayMetricsHolder.getScreenDisplayMetrics()
} catch (_: IllegalStateException) {
// React Native hasn't read the display yet, so there is nothing to correct.
return
}
if (screen.densityDpi == window.densityDpi) return
DisplayMetricsHolder.setScreenDisplayMetrics(
DisplayMetrics().apply {
setTo(screen)
density = window.density
densityDpi = window.densityDpi
},
)
}
}
@@ -0,0 +1,35 @@
const { withMainActivity } = require("expo/config-plugins");
const ACTIVITY_CLASS = "class MainActivity : ReactActivity() {";
const SYNC = "sh.paseo.displaymetrics.PaseoDisplayMetrics.syncWithWindow(this)";
// React Native re-reads the built-in display's density when it creates the root view and on every
// configuration change, so the window's density has to be restored right after each `super` call.
const OVERRIDES = `
override fun onContentChanged() {
super.onContentChanged()
${SYNC}
}
override fun onConfigurationChanged(newConfig: android.content.res.Configuration) {
super.onConfigurationChanged(newConfig)
${SYNC}
}
`;
function configureDisplayMetricsActivity(contents) {
if (contents.includes(SYNC)) return contents;
if (
!contents.includes(ACTIVITY_CLASS) ||
/override fun on(ContentChanged|ConfigurationChanged)\(/.test(contents)
) {
throw new Error("Could not keep React Native text at the window's density in MainActivity");
}
return contents.replace(ACTIVITY_CLASS, `${ACTIVITY_CLASS}${OVERRIDES}`);
}
module.exports = (config) =>
withMainActivity(config, (mod) => {
mod.modResults.contents = configureDisplayMetricsActivity(mod.modResults.contents);
return mod;
});
module.exports.configureDisplayMetricsActivity = configureDisplayMetricsActivity;
@@ -0,0 +1,29 @@
import { describe, expect, it } from "vitest";
const { configureDisplayMetricsActivity } = require("./app.plugin");
const SYNC = "sh.paseo.displaymetrics.PaseoDisplayMetrics.syncWithWindow(this)";
describe("Android display metrics", () => {
it("restores the window's density after React Native reads the display", () => {
const source = "class MainActivity : ReactActivity() {\n}";
const result = configureDisplayMetricsActivity(source);
expect(result).toContain(`super.onContentChanged()\n ${SYNC}`);
expect(result).toContain(`super.onConfigurationChanged(newConfig)\n ${SYNC}`);
expect(configureDisplayMetricsActivity(result)).toBe(result);
});
it("fails prebuild when the template no longer has a place for the overrides", () => {
expect(() => configureDisplayMetricsActivity("changed template")).toThrow(
"Could not keep React Native text at the window's density",
);
});
it("fails prebuild rather than replace another plugin's configuration handler", () => {
const source =
"class MainActivity : ReactActivity() {\n override fun onConfigurationChanged(newConfig: Configuration) {}\n}";
expect(() => configureDisplayMetricsActivity(source)).toThrow(
"Could not keep React Native text at the window's density",
);
});
});
@@ -0,0 +1,6 @@
{
"platforms": ["android"],
"android": {
"modules": []
}
}
@@ -0,0 +1,5 @@
{
"name": "paseo-display-metrics",
"version": "0.1.0",
"private": true
}
@@ -17,6 +17,11 @@ export function nextPageLimit(limit: number): number {
return PAGE_LIMITS.find((candidate) => candidate > limit) ?? limit;
}
/** The page Load more grew this limit from, or null for the first page. */
export function previousPageLimit(limit: number): number | null {
return PAGE_LIMITS.findLast((candidate) => candidate < limit) ?? null;
}
export function requiresImportSessionsHostUpgrade(input: {
supportsSnapshot: boolean;
workspaceId?: string | null;
@@ -1172,6 +1172,44 @@ describe("ImportSessionSheet", () => {
});
});
it("keeps the loaded list in place while Load more fetches the next page", async () => {
let releaseNextPage: () => void = () => undefined;
const nextPage = new Promise<void>((resolve) => {
releaseNextPage = resolve;
});
const fetchRecentProviderSessions = vi.fn(async (options: { limit?: number } | undefined) => {
if (options?.limit !== 15) await nextPage;
return {
requestId: "recent-provider-sessions",
entries: createPageOfEntries(options?.limit === 15 ? 15 : 20),
};
});
renderSheet(createRecentSessionsClient(fetchRecentProviderSessions, vi.fn()), {
cwd: null,
snapshot: { supportsSnapshot: true, entries: [createSnapshotEntry("claude")] },
});
fireEvent.click(await screen.findByTestId("import-session-load-more"));
// The list the user scrolled to Load more is the one they keep: replacing it would drop
// them back at the top, behind a loading state, until the larger page lands.
const list = screen.getByTestId("import-session-list");
await waitFor(() => {
expect(fetchRecentProviderSessions).toHaveBeenCalledWith({
providers: ["claude"],
limit: 45,
});
});
expect(screen.getByTestId("import-session-list")).toBe(list);
expect(screen.queryByText("Loading sessions...")).toBeNull();
releaseNextPage();
await waitFor(() => {
expect(screen.queryByTestId("import-session-load-more")).toBeNull();
});
expect(screen.getByTestId("import-session-list")).toBe(list);
});
it("stops the refresh spinner and retries only the failed provider", async () => {
const fetchRecentProviderSessions = vi.fn(
async (options: { providers?: string[] } | undefined) => {
@@ -1,6 +1,6 @@
import React, { type ReactNode, useCallback, useEffect, useMemo, useRef, useState } from "react";
import { Pressable, type PressableStateCallbackType, Text, View } from "react-native";
import { keepPreviousData, useMutation, useQueries, useQueryClient } from "@tanstack/react-query";
import { useMutation, useQueries, useQueryClient, type QueryClient } from "@tanstack/react-query";
import { useTranslation } from "react-i18next";
import type {
DaemonClient,
@@ -40,6 +40,7 @@ import {
resolveDirectoryLabel,
nextPageLimit,
PER_PROVIDER_LIMIT,
previousPageLimit,
type ProviderErrorRow,
resolveImportTarget,
resolveProvidersToFetch,
@@ -100,11 +101,12 @@ interface SessionsQueryConfig {
// Query's default retry would keep the header spinner turning and pile up
// in-flight daemon requests behind a dead provider (#2512).
retry: false;
placeholderData: typeof keepPreviousData;
placeholderData: () => RecentSessionsResponse | undefined;
queryFn: () => Promise<RecentSessionsResponse>;
}
function buildSessionsQueriesConfig(args: {
queryClient: QueryClient;
providersToFetch: AgentProvider[] | null;
visible: boolean;
client: RecentProviderSessionsClient | null;
@@ -113,14 +115,24 @@ function buildSessionsQueriesConfig(args: {
limit: number;
hostDisconnectedMessage?: string;
}): SessionsQueryConfig[] {
const { providersToFetch, visible, client, cwd, query, limit, hostDisconnectedMessage } = args;
const { queryClient, providersToFetch, visible, client, cwd, query, limit } = args;
const { hostDisconnectedMessage } = args;
if (providersToFetch === null) return [];
const enabled = visible && Boolean(client);
const previousLimit = previousPageLimit(limit);
return providersToFetch.map((provider) => ({
queryKey: buildSessionsQueryKey({ cwd, query, limit, provider }),
enabled,
retry: false as const,
placeholderData: keepPreviousData,
// While Load more fetches the next page, keep showing the page it grew from. React Query's
// keepPreviousData cannot do this here: useQueries gives a changed key a new observer, which
// has no previous data, so the rows would vanish and the list would remount at the top.
placeholderData: () =>
previousLimit === null
? undefined
: queryClient.getQueryData<RecentSessionsResponse>(
buildSessionsQueryKey({ cwd, query, limit: previousLimit, provider }),
),
queryFn: async () => {
if (!client) {
throw new Error(hostDisconnectedMessage ?? i18n.t("workspace.terminal.hostDisconnected"));
@@ -522,6 +534,7 @@ export function ImportSessionSheet({
const queriesConfig = useMemo(
() =>
buildSessionsQueriesConfig({
queryClient,
providersToFetch,
visible,
client,
@@ -530,7 +543,7 @@ export function ImportSessionSheet({
limit: pageLimit,
hostDisconnectedMessage: t("workspace.terminal.hostDisconnected"),
}),
[providersToFetch, visible, client, scopeCwd, query, pageLimit, t],
[queryClient, providersToFetch, visible, client, scopeCwd, query, pageLimit, t],
);
const queries = useQueries({ queries: queriesConfig });
+1 -10
View File
@@ -1,7 +1,4 @@
import { PluginClientStateProvider } from "@getpaseo/plugin/client/host";
import type { PluginFilePanelProps } from "@getpaseo/plugin/client";
import { useMemo } from "react";
import { createPluginClientStateSource } from "@/plugins/client-state/source";
import { PluginInstallationProvider } from "@/plugins/installation-provider";
import { SurfaceErrorBoundary } from "@/plugins/surface-error-boundary";
import type { PluginFilePanel } from "./panels";
@@ -11,17 +8,11 @@ export function PluginFilePanelHost({
...props
}: PluginFilePanelProps & { panel: PluginFilePanel }) {
const { plugin, contribution } = panel;
const stateSource = useMemo(
() => createPluginClientStateSource(plugin.serverId),
[plugin.serverId],
);
const Component = contribution.Component;
return (
<SurfaceErrorBoundary installation={plugin} Surface={Component} key={panel.id}>
<PluginInstallationProvider plugin={plugin}>
<PluginClientStateProvider source={stateSource}>
<Component {...props} />
</PluginClientStateProvider>
<Component {...props} />
</PluginInstallationProvider>
</SurfaceErrorBoundary>
);
+2 -2
View File
@@ -484,8 +484,7 @@ export const ar: TranslationResources = {
archivedTitle: "مساحة العمل مؤرشفة",
restoreDescription:
"استعد {{workspaceName}} للعودة إلى وكلائها. ستستخدم شجرة العمل الفرع {{branch}}.",
restoreWithoutBranchDescription:
"استعد {{workspaceName}} للعودة إلى وكلائها. سيبدأ فرع جديد من الفرع الأساسي المحفوظ أو الفرع الافتراضي للمستودع.",
restoreWithoutBranchDescription: "استعد {{workspaceName}} للعودة إلى وكلائها.",
unarchiveDescription: "{{workspaceName}} مؤرشفة. ألغِ أرشفتها لفتحها مجددًا.",
restoreAction: "استعادة",
unarchiveAction: "إلغاء الأرشفة",
@@ -2017,6 +2016,7 @@ export const ar: TranslationResources = {
hostUnavailable: "مضيف التنزيل غير متاح.",
cancelled: "تم إلغاء التنزيل.",
failed: "فشل تنزيل الملف.",
httpFailed: "فشل تنزيل الملف (HTTP {{status}}).",
shareFile: "مشاركة الملف",
shareFileNamed: "مشاركة{{fileName}}",
},
+2 -2
View File
@@ -483,8 +483,7 @@ export const en = {
archivedTitle: "Workspace archived",
restoreDescription:
"Restore {{workspaceName}} to return to its agents. Its worktree will use branch {{branch}}.",
restoreWithoutBranchDescription:
"Restore {{workspaceName}} to return to its agents. A new branch will start from the saved base or the repository default.",
restoreWithoutBranchDescription: "Restore {{workspaceName}} to return to its agents.",
unarchiveDescription: "{{workspaceName}} is archived. Unarchive it to open it again.",
restoreAction: "Restore",
unarchiveAction: "Unarchive",
@@ -2045,6 +2044,7 @@ export const en = {
hostUnavailable: "Download host is unavailable.",
cancelled: "Download was cancelled.",
failed: "Failed to download file.",
httpFailed: "Failed to download file (HTTP {{status}}).",
shareFile: "Share file",
shareFileNamed: "Share {{fileName}}",
},
+2 -2
View File
@@ -489,8 +489,7 @@ export const es: TranslationResources = {
archivedTitle: "Espacio de trabajo archivado",
restoreDescription:
"Restaura {{workspaceName}} para volver a sus agentes. Su worktree usará la rama {{branch}}.",
restoreWithoutBranchDescription:
"Restaura {{workspaceName}} para volver a sus agentes. Se creará una rama nueva desde la base guardada o la rama predeterminada del repositorio.",
restoreWithoutBranchDescription: "Restaura {{workspaceName}} para volver a sus agentes.",
unarchiveDescription:
"{{workspaceName}} está archivado. Desarchívalo para volver a abrirlo.",
restoreAction: "Restaurar",
@@ -2066,6 +2065,7 @@ export const es: TranslationResources = {
hostUnavailable: "El host de descarga no está disponible.",
cancelled: "La descarga fue cancelada.",
failed: "No se pudo descargar el archivo.",
httpFailed: "No se pudo descargar el archivo (HTTP {{status}}).",
shareFile: "compartir archivo",
shareFileNamed: "Compartir{{fileName}}",
},
+2 -2
View File
@@ -489,8 +489,7 @@ export const fr: TranslationResources = {
archivedTitle: "Espace de travail archivé",
restoreDescription:
"Restaurez {{workspaceName}} pour retrouver ses agents. Son worktree utilisera la branche {{branch}}.",
restoreWithoutBranchDescription:
"Restaurez {{workspaceName}} pour retrouver ses agents. Une nouvelle branche partira de la base enregistrée ou de la branche par défaut du dépôt.",
restoreWithoutBranchDescription: "Restaurez {{workspaceName}} pour retrouver ses agents.",
unarchiveDescription: "{{workspaceName}} est archivé. Désarchivez-le pour le rouvrir.",
restoreAction: "Restaurer",
unarchiveAction: "Désarchiver",
@@ -2065,6 +2064,7 @@ export const fr: TranslationResources = {
hostUnavailable: "L’hôte de téléchargement est indisponible.",
cancelled: "Téléchargement annulé.",
failed: "Impossible de télécharger le fichier.",
httpFailed: "Impossible de télécharger le fichier (HTTP {{status}}).",
shareFile: "Partager le fichier",
shareFileNamed: "Partager {{fileName}}",
},
+2 -2
View File
@@ -489,8 +489,7 @@ export const ja: TranslationResources = {
archivedTitle: "ワークスペースはアーカイブ済みです",
restoreDescription:
"{{workspaceName}} を復元してエージェントに戻ります。worktree ではブランチ {{branch}} を使用します。",
restoreWithoutBranchDescription:
"{{workspaceName}} を復元してエージェントに戻ります。保存されたベース、またはリポジトリのデフォルトブランチから新しいブランチを作成します。",
restoreWithoutBranchDescription: "{{workspaceName}} を復元してエージェントに戻ります。",
unarchiveDescription:
"{{workspaceName}} はアーカイブされています。再度開くにはアーカイブを解除してください。",
restoreAction: "復元",
@@ -2038,6 +2037,7 @@ export const ja: TranslationResources = {
hostUnavailable: "ダウンロードホストが利用できません。",
cancelled: "ダウンロードがキャンセルされました。",
failed: "ファイルのダウンロードに失敗しました。",
httpFailed: "ファイルのダウンロードに失敗しました (HTTP {{status}}).",
shareFile: "ファイルを共有",
shareFileNamed: "{{fileName}}を共有",
},
+2 -2
View File
@@ -485,8 +485,7 @@ export const ko: TranslationResources = {
archivedTitle: "워크스페이스가 보관되었습니다",
restoreDescription:
"{{workspaceName}}를 복원하여 에이전트로 돌아갑니다. 워크트리는 {{branch}} 브랜치를 사용합니다.",
restoreWithoutBranchDescription:
"{{workspaceName}}를 복원하여 에이전트로 돌아갑니다. 저장된 기반 브랜치 또는 저장소 기본 브랜치에서 새 브랜치를 만듭니다.",
restoreWithoutBranchDescription: "{{workspaceName}}를 복원하여 에이전트로 돌아갑니다.",
unarchiveDescription: "{{workspaceName}}가 보관되었습니다. 다시 열려면 보관을 취소하세요.",
restoreAction: "복원",
unarchiveAction: "보관 취소",
@@ -2028,6 +2027,7 @@ export const ko: TranslationResources = {
hostUnavailable: "다운로드 호스트를 사용할 수 없습니다.",
cancelled: "다운로드가 취소되었습니다.",
failed: "파일을 다운로드하지 못했습니다.",
httpFailed: "파일을 다운로드하지 못했습니다 (HTTP {{status}}).",
shareFile: "파일 공유",
shareFileNamed: "{{fileName}} 공유",
},
+2 -2
View File
@@ -488,8 +488,7 @@ export const ptBR: TranslationResources = {
archivedTitle: "Workspace arquivado",
restoreDescription:
"Restaure {{workspaceName}} para voltar aos seus agentes. A worktree usará a branch {{branch}}.",
restoreWithoutBranchDescription:
"Restaure {{workspaceName}} para voltar aos seus agentes. Uma nova branch partirá da base salva ou da branch padrão do repositório.",
restoreWithoutBranchDescription: "Restaure {{workspaceName}} para voltar aos seus agentes.",
unarchiveDescription:
"{{workspaceName}} está arquivado. Desarquive-o para abri-lo novamente.",
restoreAction: "Restaurar",
@@ -2051,6 +2050,7 @@ export const ptBR: TranslationResources = {
hostUnavailable: "Host de download indisponível.",
cancelled: "Download cancelado.",
failed: "Falha ao baixar arquivo.",
httpFailed: "Falha ao baixar arquivo (HTTP {{status}}).",
shareFile: "Compartilhar arquivo",
shareFileNamed: "Compartilhar {{fileName}}",
},
+2 -1
View File
@@ -489,7 +489,7 @@ export const ru: TranslationResources = {
restoreDescription:
"Восстановите «{{workspaceName}}», чтобы вернуться к его агентам. Worktree будет использовать ветку {{branch}}.",
restoreWithoutBranchDescription:
"Восстановите «{{workspaceName}}», чтобы вернуться к его агентам. Новая ветка будет создана от сохранённой базовой или ветки репозитория по умолчанию.",
"Восстановите «{{workspaceName}}», чтобы вернуться к его агентам.",
unarchiveDescription:
"Рабочее пространство «{{workspaceName}}» находится в архиве. Разархивируйте его, чтобы снова открыть.",
restoreAction: "Восстановить",
@@ -2051,6 +2051,7 @@ export const ru: TranslationResources = {
hostUnavailable: "Хост загрузки недоступен.",
cancelled: "Загрузка отменена.",
failed: "Не удалось загрузить файл.",
httpFailed: "Не удалось загрузить файл (HTTP {{status}}).",
shareFile: "Поделиться файлом",
shareFileNamed: "Поделиться {{fileName}}",
},
+2 -2
View File
@@ -484,8 +484,7 @@ export const zhCN: TranslationResources = {
archivedTitle: "Workspace 已归档",
restoreDescription:
"恢复 {{workspaceName}} 以返回其中的代理。worktree 将使用分支 {{branch}}。",
restoreWithoutBranchDescription:
"恢复 {{workspaceName}} 以返回其中的代理。新分支将从保存的基准分支或仓库默认分支创建。",
restoreWithoutBranchDescription: "恢复 {{workspaceName}} 以返回其中的代理。",
unarchiveDescription: "{{workspaceName}} 已归档。取消归档以重新打开。",
restoreAction: "恢复",
unarchiveAction: "取消归档",
@@ -1994,6 +1993,7 @@ export const zhCN: TranslationResources = {
hostUnavailable: "下载 Host 不可用。",
cancelled: "下载已取消。",
failed: "下载文件失败。",
httpFailed: "下载文件失败 (HTTP {{status}}).",
shareFile: "共享文件",
shareFileNamed: "共享 {{fileName}}",
},
@@ -1,5 +1,5 @@
import { PluginTranslationRuntime } from "@getpaseo/plugin/client/host";
import { usePaseo, useRpc } from "@getpaseo/plugin/client";
import { usePaseo, useRpc, useWorkspace, useWorkspaces } from "@getpaseo/plugin/client";
import { defineRpc } from "@getpaseo/plugin";
import { createPaseoApi, type PaseoApi } from "@getpaseo/client";
import { DaemonClient } from "@getpaseo/client/internal/daemon-client";
@@ -8,7 +8,11 @@ import React from "react";
import { renderToStaticMarkup } from "react-dom/server";
import { expect, it } from "vitest";
import { z } from "zod";
import type { PluginWorkspaceSnapshot } from "@getpaseo/plugin";
import type { PluginClientStateSource } from "@getpaseo/plugin/client/host";
import type { ToastApi } from "@/components/toast-host";
import { PluginInstallationProvider } from "./installation-provider";
import { PluginEnvironmentProvider } from "./popover";
import type { InstalledPlugin } from "./types";
const status = defineRpc({
@@ -89,3 +93,53 @@ it("gives every surface the installation's client and RPCs on its first frame",
plugin.lifetime.abort();
await plugin.paseo.dispose();
});
it("lets every surface read state through the plugin state hooks", async () => {
const plugin = installation([]);
function Surface() {
return <span>{useWorkspaces().length} workspaces</span>;
}
const markup = renderToStaticMarkup(
<PluginInstallationProvider plugin={plugin}>
<Surface />
</PluginInstallationProvider>,
);
expect(markup).toBe("<span>0 workspaces</span>");
plugin.lifetime.abort();
await plugin.paseo.dispose();
});
function pluginEnvironment(plugin: InstalledPlugin, state: PluginClientStateSource) {
return { installation: plugin, state, toast: {} as ToastApi };
}
it("lets a surface read the state source its host passes", async () => {
const plugin = installation([]);
// A sidebar view spans every connected host, so its source is not the installation's host.
const workspace = { id: "ws-on-another-host" } as PluginWorkspaceSnapshot;
const state: PluginClientStateSource = {
subscribe: () => () => undefined,
getWorkspace: () => workspace,
getAgent: () => null,
getProject: () => null,
getTerminal: () => null,
getSnapshot: () => ({ workspaces: [], agents: [], projects: [], terminals: [] }),
};
function Surface() {
return <span>{useWorkspace("ws-on-another-host")?.id}</span>;
}
const environment = pluginEnvironment(plugin, state);
const markup = renderToStaticMarkup(
<PluginEnvironmentProvider environment={environment}>
<Surface />
</PluginEnvironmentProvider>,
);
expect(markup).toBe("<span>ws-on-another-host</span>");
plugin.lifetime.abort();
await plugin.paseo.dispose();
});
@@ -2,29 +2,42 @@ import { getPluginClientApi } from "./client-state/api";
import { QueryClientProvider } from "@tanstack/react-query";
import {
PaseoApiProvider,
PluginClientStateProvider,
PluginComposersProvider,
PluginRpcProvider,
PluginTranslationProvider,
type PluginClientStateSource,
} from "@getpaseo/plugin/client/host";
import React, { type ReactNode } from "react";
import React, { useMemo, type ReactNode } from "react";
import { createPluginClientStateSource } from "./client-state/source";
import { pluginComposersSource } from "./composer-items/source";
import type { InstalledPlugin } from "./types";
/** Every plugin surface renders under its installation: one query cache, one Paseo client, RPCs. */
/**
* Every plugin surface renders under its installation: one query cache, one Paseo client, RPCs,
* and the state the plugin state hooks read. That state is scoped to the installation's host
* unless the surface passes its own, as a sidebar view does to span every connected host.
*/
export function PluginInstallationProvider({
plugin,
state: surfaceState,
children,
}: {
plugin: InstalledPlugin;
state?: PluginClientStateSource;
children: ReactNode;
}) {
const state = useMemo(
() => surfaceState ?? createPluginClientStateSource(plugin.serverId),
[plugin.serverId, surfaceState],
);
return (
<QueryClientProvider client={plugin.queryClient}>
<PaseoApiProvider paseo={getPluginClientApi(plugin).paseo}>
<PluginRpcProvider invoke={plugin.invoke} subscribe={plugin.subscribe}>
<PluginTranslationProvider runtime={plugin.i18n}>
<PluginComposersProvider source={pluginComposersSource(plugin)}>
{children}
<PluginClientStateProvider source={state}>{children}</PluginClientStateProvider>
</PluginComposersProvider>
</PluginTranslationProvider>
</PluginRpcProvider>
+2 -3
View File
@@ -1,4 +1,3 @@
import { PluginClientStateProvider } from "@getpaseo/plugin/client/host";
import type { ReactNode } from "react";
import { View } from "react-native";
import { StyleSheet } from "react-native-unistyles";
@@ -30,8 +29,8 @@ export function PluginEnvironmentProvider({
}: PluginEnvironmentProviderProps) {
return (
<ToastApiProvider api={environment.toast}>
<PluginInstallationProvider plugin={environment.installation}>
<PluginClientStateProvider source={environment.state}>{children}</PluginClientStateProvider>
<PluginInstallationProvider plugin={environment.installation} state={environment.state}>
{children}
</PluginInstallationProvider>
</ToastApiProvider>
);
+1 -6
View File
@@ -1,4 +1,3 @@
import { PluginClientStateProvider } from "@getpaseo/plugin/client/host";
import type { PluginTimelineItemProps } from "@getpaseo/plugin/client";
import type { PluginTheme } from "@getpaseo/plugin";
import React, { type ComponentType, useMemo } from "react";
@@ -8,7 +7,6 @@ import { useIsCompactFormFactor } from "@/constants/layout";
import { useHostRuntimeClient, useHosts } from "@/runtime/host-runtime";
import type { Theme } from "@/styles/theme";
import type { PluginTimelineStreamItem } from "@/types/stream";
import { createPluginClientStateSource } from "../client-state/source";
import { useInstalledPlugin } from "../registry";
import { PluginInstallationProvider } from "../installation-provider";
import { SurfaceErrorBoundary } from "../surface-error-boundary";
@@ -59,7 +57,6 @@ function PluginTimelineItemBody({
const hostLabel = hosts.find((host) => host.serverId === serverId)?.label ?? serverId;
const host = useMemo(() => ({ id: serverId, label: hostLabel }), [hostLabel, serverId]);
const layout = useMemo(() => ({ compact, platform: resolvePluginPlatform() }), [compact]);
const stateSource = useMemo(() => createPluginClientStateSource(serverId), [serverId]);
if (!plugin || !renderer || !parsed || !client) {
return <TimelineItemUnavailable />;
@@ -82,9 +79,7 @@ function PluginTimelineItemBody({
return (
<SurfaceErrorBoundary installation={plugin} resetKey={item.data} Surface={Component}>
<PluginInstallationProvider plugin={plugin}>
<PluginClientStateProvider source={stateSource}>
<Component {...props} />
</PluginClientStateProvider>
<Component {...props} />
</PluginInstallationProvider>
</SurfaceErrorBoundary>
);
@@ -5,7 +5,6 @@ import type {
PluginTab,
} from "@getpaseo/plugin/client";
import type { PluginTheme } from "@getpaseo/plugin";
import { PluginClientStateProvider } from "@getpaseo/plugin/client/host";
import { CircleAlert } from "lucide-react-native";
import { useMemo, useState } from "react";
import { Text, View } from "react-native";
@@ -20,7 +19,6 @@ import { useWorkspaceExists } from "@/stores/session-store-hooks";
import type { Theme } from "@/styles/theme";
import { normalizeWorkspaceOpaqueId } from "@/utils/workspace-identity";
import { usePluginHostNavigation } from "../host-navigation";
import { createPluginClientStateSource } from "../client-state/source";
import { toPluginTheme } from "../theme";
import { pluginIconComponent } from "../icons";
import { useInstalledPlugin } from "../registry";
@@ -67,7 +65,6 @@ function PluginPanelBody({ theme }: { theme: PluginTheme }) {
const hostLabel = hosts.find((host) => host.serverId === serverId)?.label ?? serverId;
const host = useMemo(() => ({ id: serverId, label: hostLabel }), [hostLabel, serverId]);
const layout = useMemo(() => ({ compact, platform: resolvePluginPlatform() }), [compact]);
const stateSource = useMemo(() => createPluginClientStateSource(serverId), [serverId]);
const navigation = usePluginHostNavigation(serverId);
if (!plugin || !contribution || !workspaceExists) {
@@ -123,9 +120,7 @@ function PluginPanelBody({ theme }: { theme: PluginTheme }) {
Surface={Surface}
key={`${serverId}/${target.pluginId}/${target.panelId}/${target.context}`}
>
<PluginInstallationProvider plugin={plugin}>
<PluginClientStateProvider source={stateSource}>{panel}</PluginClientStateProvider>
</PluginInstallationProvider>
<PluginInstallationProvider plugin={plugin}>{panel}</PluginInstallationProvider>
</SurfaceErrorBoundary>
);
}
+48 -1
View File
@@ -2739,6 +2739,52 @@ describe("HostRuntimeStore", () => {
session.clearSession(host.serverId);
});
it("loads the directory for a consumer that sees a restored host before the registry finishes loading", async () => {
const host = makeHost({
connections: [{ id: "direct:lan:6767", type: "directTcp", endpoint: "lan:6767" }],
});
const fakeClient = new FakeDaemonClient();
fakeClient.setConnectionState({ status: "connected" });
const store = new HostRuntimeStore({
storage: createMemoryHostRuntimeStorage({
[REGISTRY_KEY]: JSON.stringify([host]),
"@paseo:e2e": "1",
}),
deps: {
createClient: () => fakeClient as unknown as DaemonClient,
connectToDaemon: async ({ host: hostProfile }) => ({
client: fakeClient as unknown as DaemonClient,
serverId: hostProfile.serverId,
hostname: hostProfile.label ?? null,
}),
getClientId: async () => "cid_test_runtime",
},
});
// A component renders on every tick while the registry loads, and acquires directory
// demand for each host it reads, as the sidebar does on its first render.
const registry = { loading: true };
const boot = store.boot().finally(() => {
registry.loading = false;
});
let releaseDemand: (() => void) | null = null;
while (registry.loading && !releaseDemand) {
if (store.getHosts().some((candidate) => candidate.serverId === host.serverId)) {
releaseDemand = store.acquireDirectoryDemand(host.serverId);
}
await Promise.resolve();
}
await boot;
expect(releaseDemand).not.toBeNull();
await waitForHostOnline(store, host.serverId);
await vi.waitFor(() => expect(fakeClient.fetchAgentsCalls).toHaveLength(1));
releaseDemand?.();
store.syncHosts([]);
useSessionStore.getState().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));
@@ -2863,7 +2909,8 @@ describe("HostRuntimeStore", () => {
await registryLoaded;
expect(store.isHostRegistryLoaded()).toBe(true);
expect(hostListNotifications).toBe(2);
// Publishing the restored hosts, the registry turning ready, and the registry loading.
expect(hostListNotifications).toBe(3);
} finally {
if (previousOverride === undefined) {
delete process.env.EXPO_PUBLIC_LOCAL_DAEMON;
+1 -3
View File
@@ -1816,11 +1816,9 @@ export class HostRuntimeStore {
shouldPersistHosts = true;
}
}
this.hosts = profiles;
this.replicaCache.setHosts(profiles.map((profile) => profile.serverId));
projectIconCache.setHosts(profiles.map((profile) => profile.serverId));
await projectIconCache.restore();
this.syncHosts(profiles);
this.setHostsAndSync(profiles);
for (const profile of profiles) {
void this.directorySyncByServer
.get(profile.serverId)
@@ -2003,9 +2003,8 @@ function WorkspaceScreenContent({
const agent =
useSessionStore.getState().sessions[normalizedServerId]?.agents?.get(agentId) ?? null;
let closePolicy = resolveCloseAgentTabPolicy(agent);
const isRunning = agent?.status === "running";
if (isRunning && closePolicy.kind === "archive-on-close") {
if (closePolicy.kind === "archive-on-close" && closePolicy.confirmArchive) {
const confirmed = await confirmDialog({
title: t("workspace.tabs.confirmations.archiveRunningAgentTitle"),
message: t("workspace.tabs.confirmations.archiveRunningAgentMessage"),
@@ -90,6 +90,7 @@ interface StartInput {
token?: ReturnType<typeof createTokenRequest>;
reader?: ReturnType<typeof createFileReader>;
saver?: ReturnType<typeof createFileSaver>;
fetchFile?: typeof fetch;
}
async function startDownload(input: StartInput): Promise<Download | undefined> {
@@ -108,6 +109,7 @@ async function startDownload(input: StartInput): Promise<Download | undefined> {
requestFileDownloadToken: token.request,
readFile: reader.read,
saveFile: saver.save,
fetchFile: input.fetchFile ?? (async () => new Response(FILE_BYTES)),
});
const { activeDownloadId, downloads } = useDownloadStore.getState();
return activeDownloadId ? downloads.get(activeDownloadId) : undefined;
@@ -203,6 +205,57 @@ describe("download store transport selection", () => {
expect(saver.savedFiles).toEqual([]);
});
it("fails with the HTTP status when a proxy in front of the host rejects the download", async () => {
const requests: Array<RequestInit | undefined> = [];
const download = await startDownload({
profile: profileWith([localTcpConnection]),
activeConnectionId: localTcpConnection.id,
fetchFile: async (_url, init) => {
requests.push(init);
return new Response("<h1>401 Authorization Required</h1>", {
status: 401,
headers: { "WWW-Authenticate": 'Basic realm="Paseo"' },
});
},
});
expect(download).toMatchObject({
status: "error",
message: i18n.t("downloads.httpFailed", { status: 401 }),
});
expect(requests).toEqual([{ credentials: "include", redirect: "error" }]);
});
it("fails with a readable message when the download request cannot reach the host", async () => {
const download = await startDownload({
profile: profileWith([localTcpConnection]),
activeConnectionId: localTcpConnection.id,
fetchFile: async () => {
throw new TypeError("Failed to fetch");
},
});
expect(download).toMatchObject({ status: "error", message: i18n.t("downloads.failed") });
});
it("fails with a readable message when the connection drops while the file is downloading", async () => {
const saver = createFileSaver();
const download = await startDownload({
profile: profileWith([localTcpConnection]),
activeConnectionId: localTcpConnection.id,
fetchFile: async () =>
new Response(
new ReadableStream({
start: (controller) => controller.error(new TypeError("network error")),
}),
),
saver,
});
expect(download).toMatchObject({ status: "error", message: i18n.t("downloads.failed") });
expect(saver.savedFiles).toEqual([]);
});
it("fails the download and saves nothing when the session read fails", async () => {
const reader = createFileReader(async () => {
throw new Error("Connection lost");
+39 -34
View File
@@ -4,7 +4,6 @@ import * as LegacyFileSystem from "expo-file-system/legacy";
import * as Sharing from "expo-sharing";
import type { HostProfile } from "@/types/host-connection";
import { buildDaemonWebSocketUrl } from "@/utils/daemon-endpoints";
import { openExternalUrl } from "@/utils/open-external-url";
import { isWeb } from "@/constants/platform";
import { i18n } from "@/i18n/i18next";
@@ -59,6 +58,7 @@ interface DownloadState {
/** Reads the whole file over the session socket; used when no direct HTTP endpoint is active. */
readFile: (path: string, maxBytes: number) => Promise<{ bytes: Uint8Array; size: number }>;
saveFile?: typeof saveDownloadedBytes;
fetchFile?: typeof fetch;
}) => Promise<void>;
updateProgress: (id: string, progress: DownloadProgress) => void;
@@ -86,6 +86,7 @@ export const useDownloadStore = create<DownloadState>()((set, get) => ({
requestFileDownloadToken,
readFile,
saveFile = saveDownloadedBytes,
fetchFile = fetch,
}) => {
const id = generateDownloadId();
const download: Download = {
@@ -144,14 +145,11 @@ export const useDownloadStore = create<DownloadState>()((set, get) => ({
throw new Error(i18n.t("downloads.hostUnavailable"));
}
const downloadUrl = buildDownloadUrl(
downloadTarget.baseUrl,
tokenResponse.token,
isWeb ? downloadTarget.authCredentials : null,
);
const downloadUrl = buildDownloadUrl(downloadTarget.baseUrl, tokenResponse.token);
if (isWeb) {
triggerBrowserDownload(downloadUrl, resolvedFileName);
const file = await fetchDownload(fetchFile, downloadUrl);
saveBrowserFile(file, resolvedFileName);
get().completeDownload(id);
return;
}
@@ -198,11 +196,6 @@ export const useDownloadStore = create<DownloadState>()((set, get) => ({
await shareSavedFile(result.uri, tokenResponse.mimeType, resolvedFileName);
} catch (error) {
const message = error instanceof Error ? error.message : i18n.t("downloads.failed");
if (isWeb) {
console.warn("[DownloadStore] Download failed:", message);
get().failDownload(id, message);
return;
}
get().failDownload(id, message);
}
},
@@ -283,7 +276,6 @@ function findMostRecentDownloadId(downloads: Map<string, Download>): string | nu
interface DownloadTarget {
baseUrl: string | null;
authHeader: string | null;
authCredentials: { username: string; password: string } | null;
}
/**
@@ -306,7 +298,7 @@ function resolveDaemonDownloadTarget(
buildDaemonWebSocketUrl(connection.endpoint, { useTls: connection.useTls ?? false }),
);
} catch {
return { baseUrl: null, authHeader: null, authCredentials: null };
return { baseUrl: null, authHeader: null };
}
if (parsed.protocol === "ws:") {
@@ -332,23 +324,41 @@ function resolveDaemonDownloadTarget(
? `Basic ${btoa(`${authCredentials.username}:${authCredentials.password}`)}`
: null;
return { baseUrl, authHeader, authCredentials };
return { baseUrl, authHeader };
}
function buildDownloadUrl(
baseUrl: string,
token: string,
authCredentials: { username: string; password: string } | null,
): string {
function buildDownloadUrl(baseUrl: string, token: string): string {
const url = new URL("/api/files/download", baseUrl);
url.searchParams.set("token", token);
if (authCredentials) {
url.username = authCredentials.username;
url.password = authCredentials.password;
}
return url.toString();
}
/**
* Fetches the file instead of navigating to it. The app runs on another origin than the host
* (paseo://app on desktop), so a link to the download URL navigates the whole window, and any
* response that is not the file (a proxy's 401 page, a 404) replaces the app.
*/
async function fetchDownload(fetchFile: typeof fetch, url: string): Promise<Blob> {
let response: Response;
try {
// Send the same cookies the host's WebSocket handshake sends, so a proxy in front of the
// host lets the download through. Refuse redirects: a proxy that redirects to a login page
// would otherwise be saved as the file.
response = await fetchFile(url, { credentials: "include", redirect: "error" });
} catch {
throw new Error(i18n.t("downloads.failed"));
}
if (!response.ok) {
throw new Error(i18n.t("downloads.httpFailed", { status: response.status }));
}
try {
// The body streams after the headers, so the connection can still drop here.
return await response.blob();
} catch {
throw new Error(i18n.t("downloads.failed"));
}
}
/**
* Saves bytes read over the session. Web and Electron hand them to the browser's download
* manager and return `null`; native writes the file and returns its URI for the share sheet.
@@ -361,12 +371,7 @@ async function saveDownloadedBytes({
if (isWeb) {
const buffer = new ArrayBuffer(bytes.byteLength);
new Uint8Array(buffer).set(bytes);
const url = URL.createObjectURL(
new Blob([buffer], { type: mimeType ?? "application/octet-stream" }),
);
triggerBrowserDownload(url, fileName);
// The browser may still be reading the blob while its save prompt is open.
setTimeout(() => URL.revokeObjectURL(url), 60_000);
saveBrowserFile(new Blob([buffer], { type: mimeType ?? "application/octet-stream" }), fileName);
return null;
}
// Resolve and write in one tick so two downloads of the same name cannot pick the same path.
@@ -390,14 +395,12 @@ async function shareSavedFile(
}
}
function triggerBrowserDownload(url: string, fileName: string) {
function saveBrowserFile(file: Blob, fileName: string) {
if (typeof document === "undefined") {
if (typeof window !== "undefined") {
void openExternalUrl(url);
}
return;
}
const url = URL.createObjectURL(file);
const link = document.createElement("a");
link.href = url;
link.download = fileName;
@@ -405,6 +408,8 @@ function triggerBrowserDownload(url: string, fileName: string) {
document.body.appendChild(link);
link.click();
link.remove();
// The browser may still be reading the blob while its save prompt is open.
setTimeout(() => URL.revokeObjectURL(url), 60_000);
}
function resolveDownloadTargetFile(fileName: string): FSFile {
+1
View File
@@ -79,6 +79,7 @@ export interface Agent {
provider: AgentProvider;
status: AgentLifecycleStatus;
backgroundWork?: { count: number };
runningProviderSubagents?: { count: number };
turn: TurnLiveness;
createdAt: Date;
updatedAt: Date;
@@ -1,21 +1,48 @@
import { describe, expect, it } from "vitest";
import { resolveCloseAgentTabPolicy } from "./close-tab-policy";
function rootAgent(overrides: Partial<Parameters<typeof resolveCloseAgentTabPolicy>[0]> = {}) {
return { parentAgentId: null, status: "idle" as const, ...overrides };
}
describe("resolveCloseAgentTabPolicy", () => {
it("archives root agents when their tab closes", () => {
expect(resolveCloseAgentTabPolicy({ parentAgentId: null })).toEqual({
it("archives an idle root agent without asking", () => {
expect(resolveCloseAgentTabPolicy(rootAgent())).toEqual({
kind: "archive-on-close",
confirmArchive: false,
});
});
it("asks before archiving a running root agent", () => {
expect(resolveCloseAgentTabPolicy(rootAgent({ status: "running" }))).toEqual({
kind: "archive-on-close",
confirmArchive: true,
});
});
it("asks before archiving a root agent whose turn ended while background work still runs", () => {
expect(resolveCloseAgentTabPolicy(rootAgent({ backgroundWork: { count: 1 } }))).toEqual({
kind: "archive-on-close",
confirmArchive: true,
});
});
it("asks before archiving a root agent whose turn ended while its background subagent still runs", () => {
expect(
resolveCloseAgentTabPolicy(rootAgent({ runningProviderSubagents: { count: 1 } })),
).toEqual({ kind: "archive-on-close", confirmArchive: true });
});
it("keeps subagent tab close layout-only", () => {
expect(resolveCloseAgentTabPolicy({ parentAgentId: "parent-agent" })).toEqual({
kind: "layout-only",
});
expect(
resolveCloseAgentTabPolicy(rootAgent({ parentAgentId: "parent-agent", status: "running" })),
).toEqual({ kind: "layout-only" });
});
it("preserves the existing archive fallback when the agent is missing", () => {
expect(resolveCloseAgentTabPolicy(null)).toEqual({ kind: "archive-on-close" });
expect(resolveCloseAgentTabPolicy(undefined)).toEqual({ kind: "archive-on-close" });
expect(resolveCloseAgentTabPolicy(null)).toEqual({
kind: "archive-on-close",
confirmArchive: false,
});
});
});
+20 -3
View File
@@ -1,13 +1,30 @@
import type { Agent } from "@/stores/session-store";
export type CloseAgentTabPolicy = { kind: "archive-on-close" } | { kind: "layout-only" };
export type CloseAgentTabPolicy =
| { kind: "archive-on-close"; confirmArchive: boolean }
| { kind: "layout-only" };
type CloseTabAgent = Pick<
Agent,
"parentAgentId" | "status" | "backgroundWork" | "runningProviderSubagents"
>;
export function resolveCloseAgentTabPolicy(
agent: Pick<Agent, "parentAgentId"> | null | undefined,
agent: CloseTabAgent | null | undefined,
): CloseAgentTabPolicy {
if (agent?.parentAgentId) {
return { kind: "layout-only" };
}
return { kind: "archive-on-close" };
return { kind: "archive-on-close", confirmArchive: agent ? hasRunningWork(agent) : false };
}
// Archiving stops the agent's process, which also stops work it left running after its turn
// ended: background subagents and background shells.
function hasRunningWork(agent: CloseTabAgent): boolean {
return (
agent.status === "running" ||
(agent.backgroundWork?.count ?? 0) > 0 ||
(agent.runningProviderSubagents?.count ?? 0) > 0
);
}
@@ -72,6 +72,7 @@ export function projectAgentSnapshot(agent: Agent): AgentSnapshotPayload {
lastUserMessageAt: agent.lastUserMessageAt?.toISOString() ?? null,
status: agent.status,
backgroundWork: agent.backgroundWork,
runningProviderSubagents: agent.runningProviderSubagents,
...projectActiveTurn(agent),
capabilities: agent.capabilities,
currentModeId: agent.currentModeId,
@@ -116,6 +117,7 @@ export function normalizeAgentSnapshot(snapshot: AgentSnapshotPayload, serverId:
provider: snapshot.provider,
status: snapshot.status,
backgroundWork: snapshot.backgroundWork,
runningProviderSubagents: snapshot.runningProviderSubagents,
turn,
createdAt,
updatedAt,
@@ -1,3 +1,4 @@
import path from "node:path";
import { describe, expect, it } from "vitest";
import { buildWorkspaceSource } from "./create.js";
@@ -8,6 +9,49 @@ describe("workspace create source", () => {
).toEqual({ kind: "directory", path: "/tmp/project", projectId: "project-1" });
});
it("resolves a relative path against the directory the command runs in", () => {
const daemonTarget = { kind: "instance" as const, home: "/tmp/paseo-home" };
expect(buildWorkspaceSource({ daemonTarget, isolation: "local", path: "." })).toEqual({
kind: "directory",
path: process.cwd(),
});
expect(
buildWorkspaceSource({ daemonTarget, isolation: "worktree", path: "../sibling" }),
).toEqual({
kind: "worktree",
cwd: path.resolve(process.cwd(), "../sibling"),
action: "branch-off",
});
});
it("sends a relative path to an explicit daemon endpoint as written", () => {
const daemonTarget = { kind: "endpoint" as const, host: "other-box:6767" };
expect(buildWorkspaceSource({ daemonTarget, isolation: "local", path: "repo" })).toEqual({
kind: "directory",
path: "repo",
});
});
it("passes an absolute path from another operating system through unchanged", () => {
expect(buildWorkspaceSource({ isolation: "local", path: "C:\\repos\\project" })).toEqual({
kind: "directory",
path: "C:\\repos\\project",
});
});
it("leaves a home-relative path for the daemon to expand", () => {
const daemonTarget = { kind: "instance" as const, home: "/tmp/paseo-home" };
expect(buildWorkspaceSource({ daemonTarget, isolation: "local", path: "~/repo" })).toEqual({
kind: "directory",
path: "~/repo",
});
expect(buildWorkspaceSource({ daemonTarget, isolation: "worktree", path: "~" })).toEqual({
kind: "worktree",
cwd: "~",
action: "branch-off",
});
});
it("keeps branch names separate from managed worktree slugs", () => {
expect(
buildWorkspaceSource({
+20 -2
View File
@@ -1,6 +1,10 @@
import { isAbsolute as isPosixAbsolute } from "node:path/posix";
import { isAbsolute as isWindowsAbsolute } from "node:path/win32";
import { resolve } from "node:path";
import type { Command } from "commander";
import { connectToDaemon, getDaemonHost } from "../../utils/client.js";
import { resolveCallerAgentId } from "../../utils/caller-agent.js";
import type { DaemonTarget } from "../../utils/daemon-target.js";
import type { CommandError, CommandOptions, SingleResult } from "../../output/index.js";
import { toWorkspaceRow, workspaceSchema, type WorkspaceRow } from "./shared.js";
@@ -121,12 +125,26 @@ function buildWorktreeWorkspaceSource(options: WorkspaceCreateOptions, path: str
}
}
// A relative --path names a directory relative to where the command runs, so
// it is made absolute here for a local daemon, which would otherwise resolve
// it against its own working directory. For an explicit endpoint the path is
// sent as written, the same rule as resolveRepositoryDirectory. An absolute
// path can target a daemon on a different operating system, and the daemon
// expands a leading ~ to its own home directory.
function resolveCallerPath(input: string, daemonTarget: DaemonTarget): string {
const isHomeRelative = input === "~" || input.startsWith("~/");
if (isHomeRelative || isPosixAbsolute(input) || isWindowsAbsolute(input)) return input;
return daemonTarget.kind === "instance" ? resolve(input) : input;
}
export function buildWorkspaceSource(options: WorkspaceCreateOptions) {
const callerPath =
options.path === undefined ? undefined : resolveCallerPath(options.path, options.daemonTarget);
if (options.isolation === "local") {
return buildLocalWorkspaceSource(options, options.path ?? process.cwd());
return buildLocalWorkspaceSource(options, callerPath ?? process.cwd());
}
if (options.isolation === "worktree") {
const sourcePath = options.path ?? (options.project ? undefined : process.cwd());
const sourcePath = callerPath ?? (options.project ? undefined : process.cwd());
return buildWorktreeWorkspaceSource(options, sourcePath);
}
throw new Error(`Unsupported workspace isolation: ${String(options.isolation)}`);
+32 -4
View File
@@ -5,18 +5,25 @@ import { fileURLToPath } from "node:url";
import { _electron as electron, expect } from "playwright/test";
const root = await mkdtemp(path.join(tmpdir(), "paseo-window-startup-"));
const modulePath = fileURLToPath(new URL("../dist/window/show-when-ready.js", import.meta.url));
const showWhenReadyPath = fileURLToPath(
new URL("../dist/window/show-when-ready.js", import.meta.url),
);
const rendererRecoveryPath = fileURLToPath(
new URL("../dist/window/renderer-recovery.js", import.meta.url),
);
async function launchWindowWithoutHiddenFrames() {
async function launchDesktopWindow() {
const main = path.join(root, "main.cjs");
await writeFile(
main,
`const { app, BrowserWindow } = require("electron");
const { showWindowWhenReady } = require(${JSON.stringify(modulePath)});
const { showWindowWhenReady } = require(${JSON.stringify(showWhenReadyPath)});
const { reloadWhenRendererExits } = require(${JSON.stringify(rendererRecoveryPath)});
app.setPath("userData", ${JSON.stringify(path.join(root, "user-data"))});
app.whenReady().then(async () => {
const win = global.mainWindow = new BrowserWindow({ show: false, paintWhenInitiallyHidden: false });
showWindowWhenReady(win, { showOnLoad: true });
reloadWhenRendererExits(win);
await win.loadURL("data:text/html,<h1>Desktop ready</h1>");
global.visibleAfterLoad = win.isVisible();
});`,
@@ -37,11 +44,32 @@ async function expectLoadedDesktopIsShown(desktop) {
await expect(page.getByRole("heading", { name: "Desktop ready" })).toBeVisible();
}
function rendererPid(desktop) {
return desktop.evaluate(() => global.mainWindow.webContents.getOSProcessId());
}
async function expectDesktopReloadsAfterRendererIsTerminated(desktop) {
const terminated = await rendererPid(desktop);
process.kill(terminated, "SIGTERM");
await expect.poll(() => rendererPid(desktop), { timeout: 15_000 }).not.toBe(terminated);
await expect
.poll(
() =>
desktop.evaluate(() =>
global.mainWindow.webContents.executeJavaScript("document.body.textContent"),
),
{ timeout: 15_000 },
)
.toBe("Desktop ready");
}
let desktop;
try {
desktop = await launchWindowWithoutHiddenFrames();
desktop = await launchDesktopWindow();
await expectLoadedDesktopIsShown(desktop);
console.log("Loaded desktop is visible without hidden compositor frames");
await expectDesktopReloadsAfterRendererIsTerminated(desktop);
console.log("Desktop reloads its window after the renderer is terminated");
} finally {
await desktop?.close();
await rm(root, { recursive: true, force: true });
+2
View File
@@ -46,6 +46,7 @@ import {
buildStandardContextMenuItems,
} from "./window/window-manager.js";
import { setupDarwinCompositorWatchdog } from "./window/compositor-watchdog/index.js";
import { reloadWhenRendererExits } from "./window/renderer-recovery.js";
import { showWindowWhenReady } from "./window/show-when-ready.js";
import { resolveDesktopWindowChromeMode, windowChromeModeArgument } from "./window/chrome.js";
import { registerDialogHandlers } from "./features/dialogs.js";
@@ -734,6 +735,7 @@ async function createWindow(
}
setupDarwinCompositorWatchdog(mainWindow);
reloadWhenRendererExits(mainWindow);
setupWindowResizeEvents(mainWindow);
if (windowStateStore) {
setupWindowStatePersistence(mainWindow, windowStateStore);
@@ -0,0 +1,86 @@
import { EventEmitter } from "node:events";
import { describe, expect, it } from "vitest";
import { reloadWhenRendererExits } from "./renderer-recovery.js";
class Contents extends EventEmitter {
reloads = 0;
url = "paseo://app/";
getURL() {
return this.url;
}
reload() {
this.reloads += 1;
}
exit(reason: string) {
this.emit("render-process-gone", {}, { reason, exitCode: reason === "clean-exit" ? 0 : 15 });
}
}
class Window {
webContents = new Contents();
destroyed = false;
isDestroyed() {
return this.destroyed;
}
}
function recoverableWindow() {
const win = new Window();
let time = 0;
reloadWhenRendererExits(win, { now: () => time });
return {
win,
advance(ms: number) {
time += ms;
},
};
}
describe("reloadWhenRendererExits", () => {
it("reloads the window when its renderer is killed", () => {
const { win } = recoverableWindow();
win.webContents.exit("killed");
expect(win.webContents.reloads).toBe(1);
});
it("reloads after a renderer crash or out-of-memory exit", () => {
const { win, advance } = recoverableWindow();
win.webContents.exit("crashed");
advance(120_000);
win.webContents.exit("oom");
expect(win.webContents.reloads).toBe(2);
});
it("leaves a renderer that exited cleanly alone", () => {
const { win } = recoverableWindow();
win.webContents.exit("clean-exit");
expect(win.webContents.reloads).toBe(0);
});
it("leaves a renderer that exits before the first page commits to Chromium", () => {
const { win } = recoverableWindow();
win.webContents.url = "";
win.webContents.exit("killed");
expect(win.webContents.reloads).toBe(0);
});
it("leaves a closed window closed", () => {
const { win } = recoverableWindow();
win.destroyed = true;
win.webContents.exit("killed");
expect(win.webContents.reloads).toBe(0);
});
it("stops reloading a renderer that keeps exiting, and recovers again later", () => {
const { win, advance } = recoverableWindow();
for (let exit = 0; exit < 5; exit += 1) {
win.webContents.exit("crashed");
advance(1_000);
}
expect(win.webContents.reloads).toBe(3);
advance(60_000);
win.webContents.exit("killed");
expect(win.webContents.reloads).toBe(4);
});
});
@@ -0,0 +1,56 @@
import log from "electron-log/main";
// A window whose renderer exits keeps its frame but shows nothing until it is
// reloaded. Reload it, but stop when the renderer keeps exiting so a page that
// crashes on load does not restart in a loop.
const MAX_RELOADS_PER_WINDOW = 3;
const RELOAD_WINDOW_MS = 60_000;
interface RendererExit {
reason: string;
exitCode: number;
}
interface RecoverableWindow {
isDestroyed(): boolean;
webContents: {
on(
event: "render-process-gone",
listener: (event: unknown, details: RendererExit) => void,
): unknown;
getURL(): string;
reload(): void;
};
}
export function reloadWhenRendererExits(
win: RecoverableWindow,
options: { now?: () => number } = {},
): void {
const now = options.now ?? Date.now;
let reloadTimes: number[] = [];
win.webContents.on("render-process-gone", (_event, details) => {
if (details.reason === "clean-exit" || win.isDestroyed()) return;
// Before the first page commits, Chromium finishes the navigation in a new
// renderer by itself. Reloading then would abort the window's initial load.
if (win.webContents.getURL() === "") return;
const time = now();
reloadTimes = reloadTimes.filter((reloadTime) => time - reloadTime < RELOAD_WINDOW_MS);
if (reloadTimes.length >= MAX_RELOADS_PER_WINDOW) {
log.error(
`[renderer-recovery] Renderer exited (${details.reason}, code ${details.exitCode}); ` +
`not reloading after ${reloadTimes.length} reloads in the last minute`,
);
return;
}
reloadTimes.push(time);
log.warn(
`[renderer-recovery] Renderer exited (${details.reason}, code ${details.exitCode}); ` +
`reloading the window (reload ${reloadTimes.length} in the last minute)`,
);
win.webContents.reload();
});
}
+2
View File
@@ -921,6 +921,8 @@ export const AgentSnapshotPayloadSchema = z.object({
lastUserMessageAt: z.string().nullable(),
status: AgentStatusSchema,
backgroundWork: z.object({ count: z.number().int().nonnegative() }).optional(),
/** Provider subagents of this agent still running. Absent when none run or on older daemons. */
runningProviderSubagents: z.object({ count: z.number().int().nonnegative() }).optional(),
activeTurn: AgentActiveTurnPayloadSchema.nullable().optional(),
capabilities: AgentCapabilityFlagsSchema,
currentModeId: z.string().nullable(),
@@ -3473,6 +3473,101 @@ test("cancelAgentRun succeeds when the provider queues completion before rejecti
}
});
test.each([
{ binding: "foreground", agentId: "00000000-0000-4000-8000-000000000307" },
{ binding: "autonomous", agentId: "00000000-0000-4000-8000-000000000308" },
] as const)(
"cancelAgentRun settles a $binding run bound to an already finalized turn",
async ({ binding, agentId }) => {
const fixture = await createControlledInterruptFixture({
name: `interrupt-finalized-${binding}`,
agentId,
turnId: "finalized-turn",
interrupt: async () => {},
});
try {
await fixture.startForegroundRun();
await expect(fixture.manager.cancelAgentRun(fixture.agentId)).resolves.toEqual({
status: "settled",
});
if (binding === "foreground") {
await fixture.startForegroundRun();
} else {
const running = waitForAgentLifecycle(fixture.manager, fixture.agentId, "running");
fixture.session.pushEvent({
type: "turn_started",
provider: "codex",
turnId: "finalized-turn",
});
await running;
}
const cancellation = await Promise.race([
fixture.manager.cancelAgentRun(fixture.agentId),
new Promise<"pending">((resolve) => setTimeout(() => resolve("pending"), 3_000)),
]);
expect(cancellation).toEqual({ status: "settled" });
expect(fixture.manager.getAgent(fixture.agentId)).toMatchObject({
lifecycle: "idle",
activeForegroundTurnId: null,
});
await expect(fixture.manager.cancelAgentRun(fixture.agentId)).resolves.toEqual({
status: "not_running",
});
await fixture.startForegroundRun();
expect(fixture.manager.getAgent(fixture.agentId)).toMatchObject({
lifecycle: "running",
activeForegroundTurnId: "finalized-turn",
});
} finally {
await fixture.cleanup();
}
},
10_000,
);
test("the provider's terminal for a run bound to an already finalized turn settles the run", async () => {
const fixture = await createControlledInterruptFixture({
name: "interrupt-finalized-provider-terminal",
agentId: "00000000-0000-4000-8000-000000000309",
turnId: "finalized-provider-terminal-turn",
interrupt: async () => {},
});
try {
await fixture.startForegroundRun();
await expect(fixture.manager.cancelAgentRun(fixture.agentId)).resolves.toEqual({
status: "settled",
});
await fixture.startForegroundRun();
const idle = waitForAgentLifecycle(fixture.manager, fixture.agentId, "idle");
fixture.session.pushEvent({
type: "turn_completed",
provider: "codex",
turnId: "finalized-provider-terminal-turn",
});
const settlement = await Promise.race([
idle.then(() => "idle" as const),
new Promise<"pending">((resolve) => setTimeout(() => resolve("pending"), 1_000)),
]);
expect(settlement).toBe("idle");
expect(fixture.manager.getAgent(fixture.agentId)).toMatchObject({
lifecycle: "idle",
activeForegroundTurnId: null,
});
await expect(fixture.manager.cancelAgentRun(fixture.agentId)).resolves.toEqual({
status: "not_running",
});
} finally {
await fixture.cleanup();
}
}, 10_000);
test("listProviderAvailability uses registered client keys, including custom providers", async () => {
const customClient: AgentClient = {
provider: "zai",
@@ -1456,6 +1456,12 @@ export class AgentManager {
return this.backgroundWork.summary(agentId);
}
/** Undefined when none of the agent's provider subagents is running. */
getRunningProviderSubagentSummary(agentId: string): { count: number } | undefined {
const count = this.providerSubagents.countRunning(agentId);
return count > 0 ? { count } : undefined;
}
private clearBackgroundWork(agentId: string): void {
const items = this.backgroundWork.clear(agentId);
if (items) this.dispatch({ type: "background_work", agentId, items });
@@ -2132,7 +2138,7 @@ export class AgentManager {
!this.foregroundMutationTails.has(agent.id) &&
!this.replacementMutationTails.has(agent.id) &&
!this.sessionEventTails.has(agent.id) &&
!this.providerSubagents.list(agent.id).some((child) => child.status === "running")
this.providerSubagents.countRunning(agent.id) === 0
);
}
@@ -5132,7 +5138,8 @@ export class AgentManager {
if (
eventTurnId &&
isTurnTerminalEvent(event) &&
this.runs.hasFinalizedTurn(agent, eventTurnId)
this.runs.hasFinalizedTurn(agent, eventTurnId) &&
this.runs.getTurnId(agent.id) !== eventTurnId
) {
return false;
}
@@ -266,6 +266,7 @@ function buildAgentManagerSpies() {
archiveAgent: vi.fn().mockResolvedValue({ archivedAt: new Date().toISOString() }),
notifyAgentState: vi.fn(),
getAgent: vi.fn(),
getAgentBackgroundWorkSummary: vi.fn().mockReturnValue(undefined),
listAgents: vi.fn().mockReturnValue([]),
getTimeline: vi.fn().mockReturnValue([]),
resumeAgentFromPersistence: vi.fn(),
@@ -6196,6 +6197,36 @@ describe("agent snapshot MCP serialization", () => {
expect(structured.agents[0]).not.toHaveProperty("pendingPermissions");
});
it("reports an idle agent's background work from get_agent_status and list_agents", async () => {
const { agentManager, agentStorage, spies } = createTestDeps();
const agent = createManagedAgent({ id: "agent-with-shell", cwd: REPO_CWD });
spies.agentManager.getAgent.mockReturnValue(agent);
spies.agentManager.listAgents.mockReturnValue([agent]);
spies.agentManager.getAgentBackgroundWorkSummary.mockReturnValue({ count: 1 });
const server = await createAgentMcpServer({
agentManager,
agentStorage,
providerSnapshotManager: createOpenCodeManager().manager,
logger,
});
const status = await registeredTool(server, "get_agent_status").handler({
agentId: "agent-with-shell",
});
const list = await registeredTool(server, "list_agents").handler({});
expect(status.structuredContent).toEqual({
status: "idle",
snapshot: expect.objectContaining({ status: "idle", backgroundWork: { count: 1 } }),
});
expect(list.structuredContent).toEqual({
agents: [expect.objectContaining({ status: "idle", backgroundWork: { count: 1 } })],
});
expect(spies.agentManager.getAgentBackgroundWorkSummary).toHaveBeenCalledWith(
"agent-with-shell",
);
});
it("returns archived agent snapshots from storage for get_agent_status", async () => {
const { agentManager, agentStorage, spies } = createTestDeps();
const record = createStoredRecord({
@@ -137,6 +137,14 @@ export class ProviderSubagentStore {
.sort((left, right) => left.createdAt.localeCompare(right.createdAt));
}
countRunning(parentAgentId: string): number {
let count = 0;
for (const subagent of this.descriptors.values()) {
if (subagent.parentAgentId === parentAgentId && subagent.status === "running") count += 1;
}
return count;
}
listAll(): ProviderSubagentDescriptor[] {
return [...this.descriptors.values()];
}
@@ -123,7 +123,8 @@ test.each(["mode", "model", "commands"] as const)(
try {
await session.startTurn("Run the foreground command");
await running.promise;
expect(await session.setThinkingOption?.("medium")).toMatchObject({
// Ultracode is launched with the query, so the change waits for a restart.
expect(await session.setThinkingOption?.("ultracode")).toMatchObject({
message: "Thinking level applies next turn",
});
if (control === "mode") await session.setMode("acceptEdits");
@@ -149,7 +150,7 @@ test.each(["mode", "model", "commands"] as const)(
await session.startTurn("Run another command with the new thinking level");
queries[1].work.resolve();
expect(await terminal.promise).toBe("turn_completed");
expect(efforts).toEqual(["low", "medium"]);
expect(efforts).toEqual(["low", "xhigh"]);
} finally {
await session.close();
}
@@ -44,6 +44,7 @@ function createQueryMock(events: unknown[], options: QueryMockOptions = {}): Que
close: vi.fn(() => undefined),
setPermissionMode: vi.fn(async () => undefined),
setModel: vi.fn(async () => undefined),
applyFlagSettings: vi.fn(async () => undefined),
supportedModels: vi.fn(async () => [{ value: "opus", displayName: "Opus" }]),
supportedCommands: vi.fn(async () => []),
rewindFiles: vi.fn(async () => ({ canRewind: true })),
@@ -382,6 +383,84 @@ describe("Claude runtime exit", () => {
}
});
test("keeps the process and its background work when the effort level changes", async () => {
let capturedOptions: Options | undefined;
const child = createChildProcessStub();
const query = createQueryMock(BACKGROUND_SHELL_TURN_EVENTS, {
tail: new Promise<never>(() => undefined),
onReturn: () => child.emit("exit", 0, null),
});
const queryFactory = vi.fn(({ options }: ClaudeQueryInput) => {
capturedOptions = options;
return query;
});
vi.spyOn(spawnUtils, "spawnProcess").mockReturnValue(child);
const client = new ClaudeAgentClient({
logger: createTestLogger(),
queryFactory,
resolveBinary: async () => "/test/claude/bin",
});
const session = await client.createSession({
provider: "claude",
cwd: process.cwd(),
thinkingOptionId: "low",
});
try {
await session.run("start a background shell");
capturedOptions?.spawnClaudeCodeProcess?.(SPAWN_OPTIONS);
const events: AgentStreamEvent[] = [];
session.subscribe((event) => events.push(event));
await expect(session.setThinkingOption?.("high")).resolves.toBeUndefined();
// A pending restart would be carried out here.
await session.listCommands();
expect(query.applyFlagSettings).toHaveBeenCalledWith({ effortLevel: "high" });
expect(queryFactory).toHaveBeenCalledTimes(1);
expect(query.return).not.toHaveBeenCalled();
expect(child.killSignals).toEqual([]);
expect(events).not.toContainEqual(
expect.objectContaining({ type: "background_work", provider: "claude", items: null }),
);
} finally {
await session.close();
}
});
test("restarts with the new effort level when the running process does not take it", async () => {
const efforts: Options["effort"][] = [];
const queryFactory = vi.fn(({ options }: ClaudeQueryInput) => {
efforts.push(options.effort);
const query = createQueryMock(BACKGROUND_SHELL_TURN_EVENTS, {
tail: new Promise<never>(() => undefined),
});
vi.mocked(query.applyFlagSettings).mockRejectedValue(new Error("unsupported"));
return query;
});
vi.spyOn(spawnUtils, "spawnProcess").mockReturnValue(createChildProcessStub());
const client = new ClaudeAgentClient({
logger: createTestLogger(),
queryFactory,
resolveBinary: async () => "/test/claude/bin",
});
const session = await client.createSession({
provider: "claude",
cwd: process.cwd(),
thinkingOptionId: "low",
});
try {
await session.run("start a background shell");
await session.setThinkingOption?.("high");
await session.listCommands();
expect(efforts).toEqual(["low", "high"]);
} finally {
await session.close();
}
});
test("ignores background work a retired query reports after its restart", async () => {
let capturedOptions: Options | undefined;
let deliverLateEvent: ((event: unknown) => void) | undefined;
@@ -1544,6 +1544,60 @@ describe("ClaudeAgentSession features", () => {
}
});
test("accepts a steer while Claude compacts, so the compaction is not interrupted", async () => {
const { queryFactory, push } = createStreamingQueryMock();
const client = new ClaudeAgentClient({
logger,
queryFactory,
resolveBinary: async () => "/test/claude/bin",
});
const session = await client.createSession({ provider: "claude", cwd: process.cwd() });
const events: AgentStreamEvent[] = [];
const unsubscribe = session.subscribe((event) => events.push(event));
try {
const { turnId } = await session.startTurn("/compact");
const input = queryFactory.mock.calls[0]?.[0].prompt as AsyncIterable<SDKUserMessage>;
const iterator = input[Symbol.asyncIterator]();
await expect(iterator.next()).resolves.toMatchObject({ value: { type: "user" } });
await vi.waitFor(() =>
expect(events).toContainEqual(
expect.objectContaining({
type: "timeline",
item: expect.objectContaining({ type: "user_message" }),
}),
),
);
push({
type: "system",
subtype: "status",
status: "compacting",
session_id: "session-1",
} as unknown as SDKMessage);
await vi.waitFor(() =>
expect(events).toContainEqual(
expect.objectContaining({
type: "timeline",
item: { type: "compaction", status: "loading" },
}),
),
);
const admission = await session.steerActiveTurn?.("message during compaction", {
expectedTurnId: turnId,
});
// Claude Code holds a `next` message until the compaction finishes. Refusing it makes the
// manager replace the turn, and the interrupt cancels the compaction.
expect(admission).toEqual({ status: "accepted", providerMessageId: expect.any(String) });
await expect(iterator.next()).resolves.toMatchObject({
value: { type: "user", priority: "next" },
});
} finally {
unsubscribe();
await session.close();
}
});
test("a human steer supersedes blocking permissions until Claude reads it", async () => {
const { queryFactory } = createQueryMock();
const client = new ClaudeAgentClient({
@@ -2637,7 +2637,10 @@ class ClaudeAgentSession implements AgentSession {
return { status: "unavailable" };
}
const activeTurnId = this.activeForegroundTurnId ?? this.autonomousTurn?.id;
if (this.compacting || activeTurnId !== options.expectedTurnId) {
// A compacting turn still takes a steer: Claude Code holds a `next` message until the
// compaction finishes. Refusing it makes the manager replace the turn, and that interrupt
// cancels the compaction.
if (activeTurnId !== options.expectedTurnId) {
return { status: "unavailable" };
}
@@ -2859,6 +2862,7 @@ class ClaudeAgentSession implements AgentSession {
? thinkingOptionId
: null;
const previousThinkingOptionId = this.config.thinkingOptionId;
if (!normalizedThinkingOptionId || normalizedThinkingOptionId === "default") {
this.config.thinkingOptionId = undefined;
} else if (isClaudeThinkingOption(normalizedThinkingOptionId)) {
@@ -2867,12 +2871,35 @@ class ClaudeAgentSession implements AgentSession {
} else {
throw new Error(`Unknown thinking option: ${normalizedThinkingOptionId}`);
}
this.queryRestartNeeded = true;
if (!(await this.applyEffortToRunningQuery(previousThinkingOptionId))) {
this.queryRestartNeeded = true;
}
if (this.activeForegroundTurnId || this.autonomousTurn) {
return THINKING_APPLIES_NEXT_TURN_NOTICE;
}
}
// A move between two effort levels changes only the effort, which a running Claude process
// takes through flag settings, so the process and its background work stay. Switching thinking
// off, to ultracode or back to the default changes how the query is launched, so it still
// restarts the query. The recorded option feeds every later launch either way.
private async applyEffortToRunningQuery(
previousThinkingOptionId: string | undefined,
): Promise<boolean> {
const effort = this.config.thinkingOptionId;
if (!this.query || this.queryRestartNeeded) return false;
if (!isClaudeThinkingEffort(previousThinkingOptionId) || !isClaudeThinkingEffort(effort)) {
return false;
}
try {
await this.query.applyFlagSettings({ effortLevel: effort });
return true;
} catch (error) {
this.logger.warn({ err: error, effort }, "Claude did not take a live effort change");
return false;
}
}
async applyOptions(options: ProviderOptions): Promise<void> {
// Every option but Fast is read when the query is built, and replacing a started query would
// end its background work, so once it exists only Fast can change.
@@ -1,59 +0,0 @@
import { beforeAll, beforeEach, describe, expect, test } from "vitest";
import pino from "pino";
import type { AgentSession, AgentStreamEvent } from "../agent-sdk-types.js";
import {
canRunRealProvider,
createRealProviderClient,
getRealProviderConfig,
} from "../../daemon-e2e/real-provider-test-config.js";
import { streamSession } from "./test-utils/session-stream-adapter.js";
function isTerminalEvent(event: AgentStreamEvent): boolean {
return (
event.type === "turn_completed" ||
event.type === "turn_failed" ||
event.type === "turn_canceled"
);
}
async function runTurn(session: AgentSession, prompt: string): Promise<AgentStreamEvent> {
for await (const event of streamSession(session, prompt)) {
if (isTerminalEvent(event)) return event;
}
throw new Error("turn ended without a terminal event");
}
describe("opencode agent whose native session is gone (real)", () => {
let canRun = false;
beforeAll(async () => {
canRun = await canRunRealProvider("opencode");
});
beforeEach((context) => {
if (!canRun) context.skip();
});
test("a resumed agent whose OpenCode session no longer exists continues in a new session", async () => {
const client = createRealProviderClient("opencode", pino({ level: "silent" }));
const config = { ...getRealProviderConfig("opencode"), cwd: process.cwd() };
// A non-persistent session deletes its native OpenCode session on close, which
// leaves the handle naming a session OpenCode no longer has.
const lost = await client.createSession(config, undefined, { persistSession: false });
const handle = lost.describePersistence();
await lost.close();
expect(handle).not.toBeNull();
const resumed = await client.resumeSession(handle!, config);
try {
const turn = await runTurn(resumed, "Reply with exactly: OK");
expect(turn).toMatchObject({ type: "turn_completed" });
expect(resumed.describePersistence()?.sessionId).not.toBe(handle!.sessionId);
} finally {
await resumed.close().catch(() => undefined);
}
}, 120_000);
});
@@ -814,79 +814,6 @@ describe("OpenCodeAgentClient adapter smoke tests", () => {
}
});
test("resuming an agent whose OpenCode session is gone continues in a new session", async () => {
const runtime = new TestOpenCodeHarness();
const execution = new TestOpenCodeClient();
execution.sessionGetResponse = {
error: { name: "NotFoundError", data: { message: "Session not found: ses_lost" } },
};
execution.sessionCreateResponse = { data: { id: "ses_fresh" } };
execution.sessionPromptAsyncImplementation = async (parameters) => {
const { sessionID } = parameters as { sessionID: string };
if (sessionID === "ses_lost") {
return {
error: { name: "NotFoundError", data: { message: "Session not found: ses_lost" } },
};
}
execution.emitEvent({ type: "session.idle", properties: { sessionID } });
return {};
};
runtime.enqueueClient(execution);
const client = new OpenCodeAgentClient(logger, undefined, {
serverManager: runtime,
createClient: runtime.createClient,
});
const cwd = tmpCwd();
try {
const session = await client.resumeSession({
provider: "opencode",
sessionId: "ses_lost",
metadata: { cwd },
});
try {
const turn = await collectTurnEvents(streamSession(session, "Are you there?"));
expect(turn.turnCompleted).toBe(true);
expect(session.describePersistence()?.sessionId).toBe("ses_fresh");
expect(session.persistenceUpdatedOnResume).toBe(true);
} finally {
await session.close();
}
} finally {
rmSync(cwd, { recursive: true, force: true });
}
});
test("loading history of an agent whose OpenCode session is gone creates no session", async () => {
const runtime = new TestOpenCodeHarness();
const execution = new TestOpenCodeClient();
execution.sessionGetResponse = {
error: { name: "NotFoundError", data: { message: "Session not found: ses_lost" } },
};
runtime.enqueueClient(execution);
const client = new OpenCodeAgentClient(logger, undefined, {
serverManager: runtime,
createClient: runtime.createClient,
});
const cwd = tmpCwd();
try {
const session = await client.resumeSession(
{ provider: "opencode", sessionId: "ses_lost", metadata: { cwd } },
undefined,
undefined,
{ purpose: "history" },
);
try {
expect(execution.calls.sessionCreate).toEqual([]);
expect(session.describePersistence()?.sessionId).toBe("ses_lost");
} finally {
await session.close();
}
} finally {
rmSync(cwd, { recursive: true, force: true });
}
});
test("fetchCatalog returns models with required fields", async () => {
const runtime = new TestOpenCodeHarness();
const openCodeClient = new TestOpenCodeClient();
@@ -546,15 +546,6 @@ function isOpenCodeNotFoundError(error: unknown): boolean {
);
}
async function isOpenCodeSessionMissing(
client: Pick<OpencodeClient, "session">,
sessionId: string,
directory: string,
): Promise<boolean> {
const response = await client.session.get({ sessionID: sessionId, directory });
return isOpenCodeNotFoundError(response.error);
}
async function abortOpenCodeSession(params: {
client: Pick<OpencodeClient, "session">;
sessionId: string;
@@ -1466,18 +1457,8 @@ export class OpenCodeAgentClient implements AgentClient {
options?: AgentCreateSessionOptions,
): Promise<AgentSession> {
const openCodeConfig = this.assertConfig(config);
const connection = await this.connectServer(openCodeConfig, launchContext);
return this.startNewSession(connection, config, openCodeConfig, launchContext, options);
}
private async startNewSession(
connection: OpenCodeServerConnection,
config: AgentSessionConfig,
openCodeConfig: OpenCodeAgentConfig,
launchContext?: AgentLaunchContext,
options?: AgentCreateSessionOptions,
): Promise<OpenCodeAgentSession> {
const connectServer = this.connectServer.bind(this, openCodeConfig, launchContext);
const connection = await connectServer();
const { client } = connection;
// OpenCode stores permission rules on the session, so they are set here and on resume
@@ -1541,7 +1522,7 @@ export class OpenCodeAgentClient implements AgentClient {
handle: AgentPersistenceHandle,
overrides?: Partial<AgentSessionConfig>,
launchContext?: AgentLaunchContext,
options?: AgentResumeSessionOptions,
_options?: AgentResumeSessionOptions,
): Promise<AgentSession> {
const metadata = (handle.metadata ?? {}) as Partial<AgentSessionConfig>;
const cwd = overrides?.cwd ?? metadata.cwd;
@@ -1566,32 +1547,6 @@ export class OpenCodeAgentClient implements AgentClient {
: await connectServer();
const { client } = connection;
// History loads stay read-only, so only an interactive resume replaces a lost session.
let sessionMissing = false;
if ((options?.purpose ?? "interactive") === "interactive") {
try {
sessionMissing = await isOpenCodeSessionMissing(
client,
handle.sessionId,
openCodeConfig.cwd,
);
} catch (error) {
await connection.release();
throw error;
}
}
if (sessionMissing) {
// Every prompt to a session OpenCode no longer has fails, so the agent
// continues in a new native session instead of staying unusable.
this.logger.warn(
{ sessionId: handle.sessionId },
"OpenCode session no longer exists; continuing in a new session",
);
const session = await this.startNewSession(connection, config, openCodeConfig, launchContext);
session.persistenceUpdatedOnResume = true;
return session;
}
try {
await this.applySessionPermissionRules(client, openCodeConfig, handle.sessionId);
await this.populateModelContextWindowCache(client, openCodeConfig.cwd);
@@ -3425,8 +3380,6 @@ interface OpenCodeServerConnection {
}
class OpenCodeAgentSession implements AgentSession {
/** Set when resume replaced a lost native session, so the new handle is saved at once. */
persistenceUpdatedOnResume = false;
readonly provider = "opencode" as const;
readonly capabilities = OPENCODE_CAPABILITIES;
readonly openOptionsPatch: Record<string, unknown>;
@@ -15,7 +15,7 @@ import { ensureValidJson } from "../../json-utils.js";
import type { Logger } from "pino";
import type { AgentMode, AgentProvider, AgentSessionConfig } from "../agent-sdk-types.js";
import type { AgentManager } from "../agent-manager.js";
import type { AgentManager, ManagedAgent } from "../agent-manager.js";
import { ActiveTurnBehaviorSchema, AgentProfileSchema } from "@getpaseo/protocol/messages";
import type { DaemonConfigStore } from "../../daemon-config-store.js";
import { featuresFromControls } from "@getpaseo/protocol/option-controls";
@@ -2099,6 +2099,13 @@ function createToolCatalog(
},
);
// Match the WebSocket snapshot: idle agents can still own background work.
async function projectLiveAgent(agent: ManagedAgent) {
const snapshot = await serializeSnapshotWithMetadata(agentStorage, agent, childLogger);
const backgroundWork = agentManager.getAgentBackgroundWorkSummary(agent.id);
return backgroundWork ? { ...snapshot, backgroundWork } : snapshot;
}
registerTool(
"get_agent_status",
{
@@ -2116,11 +2123,7 @@ function createToolCatalog(
async ({ agentId }) => {
const snapshot = agentManager.getAgent(agentId);
if (snapshot) {
const structuredSnapshot = await serializeSnapshotWithMetadata(
agentStorage,
snapshot,
childLogger,
);
const structuredSnapshot = await projectLiveAgent(snapshot);
return {
content: [],
structuredContent: ensureValidJson({
@@ -2188,8 +2191,7 @@ function createToolCatalog(
manager: agentManager,
storage: agentStorage,
workspaces: options.workspaceRegistry,
projectLive: (snapshot) =>
serializeSnapshotWithMetadata(agentStorage, snapshot, childLogger),
projectLive: projectLiveAgent,
projectStored: (record) =>
buildStoredAgentPayload(
record,
+2 -2
View File
@@ -128,7 +128,7 @@ export async function fanOutReconciledWorkspaceUpdates(input: {
);
}
import { VoiceAssistantWebSocketServer } from "./websocket-server.js";
import { VoiceAssistantWebSocketServer, isDaemonOriginAllowed } from "./websocket-server.js";
import { WorkspaceSetupRuntime } from "./workspace-setup-runtime.js";
import { createWorkspaceLabelService } from "./workspace-labels/index.js";
import { createGitHubService } from "../services/github-service.js";
@@ -813,7 +813,7 @@ export async function createPaseoDaemon(
app.use((req, res, next) => {
const origin = req.headers.origin;
if (origin && (allowedOrigins.has("*") || allowedOrigins.has(origin))) {
if (origin && isDaemonOriginAllowed(origin, req.headers.host ?? null, allowedOrigins)) {
res.setHeader("Access-Control-Allow-Origin", origin);
res.setHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS");
res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
@@ -0,0 +1,122 @@
import { beforeAll, beforeEach, describe, expect, test } from "vitest";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import pino from "pino";
import { ClaudeAgentClient } from "../agent/providers/claude/agent.js";
import { DaemonClient } from "../test-utils/daemon-client.js";
import { createTestPaseoDaemon } from "../test-utils/paseo-daemon.js";
import { canRunRealProvider, getRealProviderConfig } from "./real-provider-test-config.js";
function tmpCwd(): string {
return mkdtempSync(path.join(tmpdir(), "daemon-real-claude-steer-compaction-"));
}
type TimelineItem = Awaited<
ReturnType<DaemonClient["fetchAgentTimeline"]>
>["entries"][number]["item"];
// The steer must land while the compaction is still running, or it takes the idle path.
function isCompacting(items: TimelineItem[]): boolean {
const statuses = new Set(
items.flatMap((item) => (item.type === "compaction" ? [item.status] : [])),
);
return statuses.has("loading") && !statuses.has("completed");
}
function hasAssistantText(items: TimelineItem[], text: string): boolean {
return items.some((item) => item.type === "assistant_message" && item.text.includes(text));
}
async function timelineItems(client: DaemonClient, agentId: string): Promise<TimelineItem[]> {
const timeline = await client.fetchAgentTimeline(agentId, {
direction: "tail",
limit: 200,
});
return timeline.entries.map((entry) => entry.item);
}
async function waitForTimeline(
client: DaemonClient,
agentId: string,
check: (items: TimelineItem[]) => boolean,
timeoutMs: number,
label: string,
): Promise<TimelineItem[]> {
const deadline = Date.now() + timeoutMs;
for (;;) {
const items = await timelineItems(client, agentId);
if (check(items)) return items;
if (Date.now() > deadline) {
throw new Error(`Timed out: ${label}: ${JSON.stringify(items.slice(-6)).slice(0, 2000)}`);
}
await new Promise((resolve) => setTimeout(resolve, 100));
}
}
describe("daemon E2E (real claude) - steer during compaction", () => {
let canRun = false;
beforeAll(async () => {
canRun = await canRunRealProvider("claude");
});
beforeEach((context) => {
if (!canRun) context.skip();
});
test("a steered message waits for a running /compact instead of cancelling it", async () => {
const logger = pino({ level: "silent" });
const cwd = tmpCwd();
const daemon = await createTestPaseoDaemon({
agentClients: { claude: new ClaudeAgentClient({ logger }) },
logger,
});
const client = new DaemonClient({
url: `ws://127.0.0.1:${daemon.port}/ws`,
});
try {
await client.connect();
await client.fetchAgents({ subscribe: {} });
const agent = await client.createAgent({
cwd,
title: "claude-steer-during-compaction",
...getRealProviderConfig("claude"),
});
await client.sendAgentMessage(
agent.id,
`Remember this list for later and reply exactly: NOTED. ${Array.from(
{ length: 400 },
(_, index) => `item-${index}`,
).join(" ")}`,
);
const firstFinish = await client.waitForFinish(agent.id, 120_000);
expect(firstFinish.status, firstFinish.error).toBe("idle");
await client.sendAgentMessage(agent.id, "/compact");
await waitForTimeline(client, agent.id, isCompacting, 60_000, "Claude reports compacting");
await client.sendAgentMessage(agent.id, "Reply exactly: AFTER_COMPACT", {
activeTurnBehavior: "steer",
});
await waitForTimeline(
client,
agent.id,
(items) => hasAssistantText(items, "AFTER_COMPACT"),
180_000,
"Claude answers the steered message",
);
await client.waitForFinish(agent.id, 120_000);
const finalItems = await timelineItems(client, agent.id);
expect(
finalItems.filter((item) => item.type === "compaction").map((item) => item.status),
).toContain("completed");
expect(hasAssistantText(finalItems, "Compaction canceled")).toBe(false);
} finally {
await client.close().catch(() => undefined);
await daemon.close().catch(() => undefined);
rmSync(cwd, { recursive: true, force: true });
}
}, 420_000);
});
@@ -9,7 +9,7 @@ import {
symlinkSync,
} from "fs";
import { once } from "node:events";
import { get } from "node:http";
import { get, type IncomingMessage } from "node:http";
import { tmpdir } from "os";
import path from "path";
import { createDaemonTestContext, type DaemonTestContext } from "../test-utils/index.js";
@@ -69,6 +69,29 @@ describe("daemon E2E", () => {
}, 60000);
describe("file download tokens", () => {
test("lets a page on a loopback alias of the request's host and port fetch a download", async () => {
const cwd = tmpCwd();
writeFileSync(path.join(cwd, "download.bin"), "download bytes");
try {
// The web UI behind a remapped port (for example Docker -p 8080:6767): the page is at
// http://127.0.0.1:8080 and the app sends the request to localhost:8080. The WebSocket
// accepts this origin, so the download must as well.
const token = await ctx.client.requestDownloadToken(cwd, "download.bin");
const request = get({
host: "127.0.0.1",
port: ctx.daemon.port,
path: `/api/files/download?token=${token.token}`,
headers: { Host: "localhost:8080", Origin: "http://127.0.0.1:8080" },
});
const [response] = (await once(request, "response")) as [IncomingMessage];
response.resume();
expect(response.statusCode).toBe(200);
expect(response.headers["access-control-allow-origin"]).toBe("http://127.0.0.1:8080");
} finally {
rmSync(cwd, { recursive: true, force: true });
}
});
test.skipIf(process.platform !== "linux")(
"releases file descriptors after repeated HTTP download cancellations",
async () => {
@@ -0,0 +1,45 @@
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import { afterEach, beforeEach, expect, test } from "vitest";
import type { AgentSnapshotPayload } from "@getpaseo/protocol/messages";
import { createDaemonTestContext, type DaemonTestContext } from "../test-utils/index.js";
let ctx: DaemonTestContext;
let cwd: string;
beforeEach(async () => {
ctx = await createDaemonTestContext();
cwd = mkdtempSync(path.join(tmpdir(), "running-provider-subagents-"));
});
afterEach(async () => {
await ctx.cleanup();
rmSync(cwd, { recursive: true, force: true });
}, 30_000);
test("an idle agent's snapshot reports the provider subagent it left running until it finishes", async () => {
const updates: AgentSnapshotPayload[] = [];
ctx.client.subscribeRawMessages((message) => {
if (message.type === "agent_update" && message.payload.kind === "upsert") {
updates.push(message.payload.agent);
}
});
const agent = await ctx.client.createAgent({ provider: "codex", cwd });
await ctx.client.sendMessage(agent.id, "Emit a provider child that outlives the turn");
expect((await ctx.client.waitForFinish(agent.id, 15_000)).status).toBe("idle");
const idle = await ctx.client.fetchAgent({ agentId: agent.id });
expect(idle?.agent).toMatchObject({ status: "idle", runningProviderSubagents: { count: 1 } });
// The child finishes after the turn: subscribers get a snapshot without the count.
await expect
.poll(() => {
const latest = updates.findLast((update) => update.id === agent.id);
return latest ? { status: latest.status, running: latest.runningProviderSubagents } : null;
})
.toEqual({ status: "idle", running: undefined });
const finished = await ctx.client.fetchAgent({ agentId: agent.id });
expect(finished?.agent.runningProviderSubagents).toBeUndefined();
}, 60_000);
@@ -554,7 +554,7 @@ test("Hub resolves persisted execution ownership after daemon restart", async ()
expect(workspaceId).toEqual(expect.any(String));
expect(await hub.archivedWorkspaceAt(workspaceId!)).toEqual(expect.any(String));
expect(await hub.worktreeState(worktreeCwd)).toEqual({ exists: false, listed: false });
}, 20_000);
}, 60_000);
test("Hub treats missing and foreign executions as already controlled without exposing ownership", async () => {
const hub = await launchRelationship();
@@ -3,7 +3,7 @@ import type { WorktreeSource } from "../utils/worktree.js";
export type WorktreeCreationIntent = Exclude<
WorktreeSource,
{ kind: "restore" | "restore-from-base" }
{ kind: "restore" | "restore-from-base" | "restore-commit" }
>;
export interface ResolveWorktreeCreationIntentInput {
@@ -412,6 +412,7 @@ function createSessionForTest(options: SessionForTestOptions = {}): Session {
listAgents: vi.fn(() => []),
listProviderSubagentActivity: vi.fn(() => []),
getAgentBackgroundWorkSummary: () => undefined,
getRunningProviderSubagentSummary: () => undefined,
subscribe: vi.fn(() => () => {}),
...options.agentManager,
}),
+8 -20
View File
@@ -2258,8 +2258,11 @@ export class Session {
private forwardProviderSubagent(event: ProviderSubagentManagerEvent): void {
const parentAgentId =
event.type === "upsert" ? event.subagent.parentAgentId : event.parentAgentId;
if (this.agentManager.getAgent(parentAgentId)?.internal) return;
this.emitProviderSubagentWorkspaceUpdate(event);
const parent = this.agentManager.getAgent(parentAgentId);
if (parent?.internal) return;
// The parent's snapshot carries its running subagent count, and forwarding it also
// refreshes the parent's workspace.
if (event.type !== "timeline" && parent) void this.agentUpdates.forwardLiveAgent(parent);
this.forwardProviderSubagentUpdate(event);
}
@@ -2275,24 +2278,6 @@ export class Session {
if (agent) void this.agentUpdates.forwardLiveAgent(agent);
}
private emitProviderSubagentWorkspaceUpdate(event: ProviderSubagentManagerEvent): void {
if (event.type === "timeline") {
return;
}
const parentAgentId =
event.type === "upsert" ? event.subagent.parentAgentId : event.parentAgentId;
const parent = this.agentManager.getAgent(parentAgentId);
if (!parent?.workspaceId) {
return;
}
void this.emitWorkspaceUpdateForWorkspaceId(parent.workspaceId).catch((error) => {
this.sessionLogger.error(
{ err: error, parentAgentId, workspaceId: parent.workspaceId },
"Failed to emit provider subagent workspace update",
);
});
}
private buildAgentStreamPayload(
event: Extract<AgentManagerEvent, { type: "agent_stream" }>,
serializedEvent: Extract<SessionOutboundMessage, { type: "agent_stream" }>["payload"]["event"],
@@ -2308,6 +2293,9 @@ export class Session {
private async enrichAgentPayload(payload: AgentSnapshotPayload): Promise<AgentSnapshotPayload> {
payload.backgroundWork = this.agentManager.getAgentBackgroundWorkSummary(payload.id);
payload.runningProviderSubagents = this.agentManager.getRunningProviderSubagentSummary(
payload.id,
);
const storedRecord = await this.agentStorage.get(payload.id);
payload.title = storedRecord?.title ?? null;
payload.archivedAt = storedRecord?.archivedAt ?? null;
@@ -335,11 +335,15 @@ async function createBaseRecoveryFixture(baseBranch: string | null) {
await registry.update(record.workspaceId, (value) => ({ ...value, archivedAt: null }));
},
});
async function archiveAndRemove() {
await archivePersistedWorkspaceRecord({
workspaceId: workspace.workspaceId,
workspaceRegistry: registry,
});
async function archiveAndRemove(legacy = false) {
if (legacy) {
await registry.archive(workspace.workspaceId, new Date().toISOString());
} else {
await archivePersistedWorkspaceRecord({
workspaceId: workspace.workspaceId,
workspaceRegistry: registry,
});
}
await deletePaseoWorktree({ cwd: repoDir, worktreePath: workspace.cwd, paseoHome });
expect(existsSync(workspace.cwd)).toBe(false);
}
@@ -357,6 +361,134 @@ test("preserves ordinary checkout behavior when no separate base was recorded",
).toMatchObject({ currentBranch: "feature", baseRef: "feature" });
});
test("records the full HEAD ref of an archived checkout", async () => {
const fixture = await createBaseRecoveryFixture(null);
await fixture.archiveAndRemove();
expect(await fixture.registry.get(fixture.workspace.workspaceId)).toMatchObject({
branch: "feature",
head: "refs/heads/feature",
});
});
test("archives a workspace whose worktree Git administration is missing", async () => {
const fixture = await createBaseRecoveryFixture(null);
const gitDir = execFileSync("git", ["rev-parse", "--absolute-git-dir"], {
cwd: fixture.workspace.cwd,
encoding: "utf8",
}).trim();
rmSync(gitDir, { recursive: true, force: true });
await archivePersistedWorkspaceRecord({
workspaceId: fixture.workspace.workspaceId,
workspaceRegistry: fixture.registry,
});
expect((await fixture.registry.get(fixture.workspace.workspaceId))?.archivedAt).toBeTruthy();
});
test("restores a branch that shares its name with a tag", async () => {
const fixture = await createBaseRecoveryFixture("main");
execFileSync("git", ["tag", "feature"], { cwd: fixture.repoDir });
await fixture.archiveAndRemove();
expect((await fixture.registry.get(fixture.workspace.workspaceId))?.head).toBe(
"refs/heads/feature",
);
expect(await fixture.service.inspect(fixture.workspace.workspaceId)).toMatchObject({
branch: "feature",
});
await fixture.service.restore(fixture.workspace.workspaceId);
expect(
execFileSync("git", ["symbolic-ref", "HEAD"], {
cwd: fixture.workspace.cwd,
encoding: "utf8",
}).trim(),
).toBe("refs/heads/feature");
});
test("restores detached HEAD even when the stored branch is stale", async () => {
const fixture = await createBaseRecoveryFixture("main");
execFileSync("git", ["switch", "--detach"], { cwd: fixture.workspace.cwd });
const commit = execFileSync("git", ["rev-parse", "HEAD"], {
cwd: fixture.workspace.cwd,
encoding: "utf8",
}).trim();
await fixture.archiveAndRemove();
expect(await fixture.registry.get(fixture.workspace.workspaceId)).toMatchObject({
branch: "feature",
head: commit,
});
expect(await fixture.service.inspect(fixture.workspace.workspaceId)).toMatchObject({
branch: null,
});
await fixture.service.restore(fixture.workspace.workspaceId);
expect(
execFileSync("git", ["rev-parse", "--abbrev-ref", "HEAD"], {
cwd: fixture.workspace.cwd,
encoding: "utf8",
}).trim(),
).toBe("HEAD");
expect(
execFileSync("git", ["rev-parse", "HEAD"], {
cwd: fixture.workspace.cwd,
encoding: "utf8",
}).trim(),
).toBe(commit);
});
test.each(["manual", "reconciliation"] as const)(
"a later %s archive without a readable HEAD restores the latest recorded branch",
async (route) => {
const fixture = await createBaseRecoveryFixture("main");
await fixture.archiveAndRemove();
await fixture.service.restore(fixture.workspace.workspaceId);
execFileSync("git", ["switch", "-c", "feature-b"], { cwd: fixture.workspace.cwd });
writeFileSync(join(fixture.workspace.cwd, "newer.txt"), "newer\n");
execFileSync("git", ["add", "newer.txt"], { cwd: fixture.workspace.cwd });
execFileSync("git", ["-c", "commit.gpgsign=false", "commit", "-m", "newer"], {
cwd: fixture.workspace.cwd,
});
const commit = execFileSync("git", ["rev-parse", "HEAD"], {
cwd: fixture.workspace.cwd,
encoding: "utf8",
}).trim();
// Placement reconciliation records the branch observed while the workspace is active.
await fixture.registry.update(fixture.workspace.workspaceId, (workspace) => ({
...workspace,
branch: "feature-b",
}));
execFileSync("git", ["worktree", "remove", "--force", fixture.workspace.cwd], {
cwd: fixture.repoDir,
});
if (route === "manual") {
await archivePersistedWorkspaceRecord({
workspaceId: fixture.workspace.workspaceId,
workspaceRegistry: fixture.registry,
});
} else {
await fixture.registry.archive(fixture.workspace.workspaceId, new Date().toISOString());
}
expect(await fixture.registry.get(fixture.workspace.workspaceId)).toMatchObject({
branch: "feature-b",
head: undefined,
});
expect(await fixture.service.inspect(fixture.workspace.workspaceId)).toMatchObject({
branch: "feature-b",
});
await fixture.service.restore(fixture.workspace.workspaceId);
expect(
execFileSync("git", ["symbolic-ref", "HEAD"], {
cwd: fixture.workspace.cwd,
encoding: "utf8",
}).trim(),
).toBe("refs/heads/feature-b");
expect(
execFileSync("git", ["rev-parse", "HEAD"], {
cwd: fixture.workspace.cwd,
encoding: "utf8",
}).trim(),
).toBe(commit);
},
);
test("restores a branchless workspace from its recorded base so work can continue", async () => {
const fixture = await createBaseRecoveryFixture("refs/heads/release");
execFileSync("git", ["switch", "-c", "release"], { cwd: fixture.repoDir, stdio: "pipe" });
@@ -368,7 +500,7 @@ test("restores a branchless workspace from its recorded base so work can continu
...workspace,
branch: null,
}));
await fixture.archiveAndRemove();
await fixture.archiveAndRemove(true);
await expect(fixture.service.inspect(fixture.workspace.workspaceId)).resolves.toMatchObject({
kind: "recoverable",
@@ -402,7 +534,7 @@ test("restores a branchless workspace from the repository default when its base
...workspace,
branch: null,
}));
await fixture.archiveAndRemove();
await fixture.archiveAndRemove(true);
await expect(fixture.service.restore(fixture.workspace.workspaceId)).resolves.toEqual({
workspaceId: fixture.workspace.workspaceId,
@@ -418,6 +550,44 @@ test("restores a branchless workspace from the repository default when its base
);
});
test("restores the archived detached checkout at its recorded commit", async () => {
const fixture = await createBaseRecoveryFixture("refs/heads/main");
execFileSync("git", ["switch", "--detach"], { cwd: fixture.workspace.cwd });
writeFileSync(join(fixture.workspace.cwd, "detached.txt"), "detached\n");
execFileSync("git", ["add", "detached.txt"], { cwd: fixture.workspace.cwd });
execFileSync("git", ["-c", "commit.gpgsign=false", "commit", "-m", "detached"], {
cwd: fixture.workspace.cwd,
});
const commit = execFileSync("git", ["rev-parse", "HEAD"], {
cwd: fixture.workspace.cwd,
encoding: "utf8",
}).trim();
await fixture.archiveAndRemove();
expect(await fixture.registry.get(fixture.workspace.workspaceId)).toMatchObject({
branch: "feature",
head: commit,
});
execFileSync("git", ["reflog", "expire", "--expire=now", "--all"], { cwd: fixture.repoDir });
execFileSync("git", ["gc", "--prune=now"], { cwd: fixture.repoDir });
await fixture.service.restore(fixture.workspace.workspaceId);
expect(await readPaseoWorktreeMetadata(fixture.workspace.cwd)).toMatchObject({
baseRefName: "main",
baseRef: "refs/heads/main",
});
expect(
execFileSync("git", ["rev-parse", "HEAD"], {
cwd: fixture.workspace.cwd,
encoding: "utf8",
}).trim(),
).toBe(commit);
expect(
execFileSync("git", ["rev-parse", "--abbrev-ref", "HEAD"], {
cwd: fixture.workspace.cwd,
encoding: "utf8",
}).trim(),
).toBe("HEAD");
});
test("restores the branch HEAD with a base name when the exact base is missing", async () => {
const fixture = await createBaseRecoveryFixture("refs/remotes/upstream/main");
const headBeforeArchive = execFileSync("git", ["rev-parse", "HEAD"], {
@@ -151,13 +151,27 @@ export function createWorkspaceRecoveryService(deps: {
workspace: PersistedWorkspaceRecord,
sourceRepoRoot: string,
): Promise<void> {
const source: WorktreeSource = workspace.branch
? { kind: "restore", branchName: workspace.branch, baseRef: workspace.baseBranch }
: {
kind: "restore-from-base",
branchName: `restored/${randomUUID().slice(0, 8)}`,
baseRef: await resolveRecoveryBase(sourceRepoRoot, workspace.baseBranch),
};
let source: WorktreeSource;
const checkout = parseWorkspaceHead(workspace);
if (checkout.kind === "branch") {
source = {
kind: "restore",
branchName: checkout.branch,
baseRef: workspace.baseBranch,
};
} else if (checkout.kind === "commit") {
source = {
kind: "restore-commit",
commit: checkout.commit,
baseRef: await resolveRecoveryBase(sourceRepoRoot, workspace.baseBranch),
};
} else {
source = {
kind: "restore-from-base",
branchName: `restored/${randomUUID().slice(0, 8)}`,
baseRef: await resolveRecoveryBase(sourceRepoRoot, workspace.baseBranch),
};
}
try {
await runGitCommand(["worktree", "prune"], { cwd: sourceRepoRoot, timeout: 30_000 });
@@ -251,16 +265,29 @@ async function resolveRecoveryBase(repoRoot: string, recordedBase: string | null
return defaultBranch;
}
function parseWorkspaceHead(
workspace: PersistedWorkspaceRecord,
): { kind: "branch"; branch: string } | { kind: "commit"; commit: string } | { kind: "missing" } {
if (workspace.head) {
const prefix = "refs/heads/";
return workspace.head.startsWith(prefix)
? { kind: "branch", branch: workspace.head.slice(prefix.length) }
: { kind: "commit", commit: workspace.head };
}
return workspace.branch ? { kind: "branch", branch: workspace.branch } : { kind: "missing" };
}
function createRecoveryPlan(
input:
| { action: "unarchive"; workspace: PersistedWorkspaceRecord }
| { action: "restore"; workspace: PersistedWorkspaceRecord; sourceRepoRoot: string },
): RecoveryPlan {
const checkout = parseWorkspaceHead(input.workspace);
const state = {
kind: "recoverable" as const,
workspaceId: input.workspace.workspaceId,
workspaceName: resolveWorkspaceDisplayName(input.workspace),
branch: input.workspace.branch,
branch: checkout.kind === "branch" ? checkout.branch : null,
};
if (input.action === "restore") {
return {
@@ -589,6 +589,27 @@ class FakeAgentSession implements AgentSession {
});
}
/**
* A provider child that keeps running after the turn completes, then finishes on its own a
* moment later, the way a Claude background subagent does.
*/
private async emitProviderChildOutlivingTurn(): Promise<void> {
const child = (status: "running" | "completed"): AgentStreamEvent => ({
type: "provider_subagent",
provider: this.providerName,
event: { type: "upsert", id: "outliving-child", title: "Outliving child", status },
});
await this.emitEvent(child("running"));
await this.emitEvent({
type: "turn_completed",
provider: this.providerName,
usage: { inputTokens: 1, outputTokens: 1 },
});
setTimeout(() => {
this.emitEvent(child("completed")).catch(() => undefined);
}, 500);
}
private async emitStressTurn(stress: { count: number; coalesced: boolean }): Promise<void> {
for (let index = 0; index < stress.count; index += 1) {
const stressUpdate: AgentStreamEvent = {
@@ -832,6 +853,11 @@ class FakeAgentSession implements AgentSession {
this.notifySubscribers(child);
}
if (textPrompt === "Emit a provider child that outlives the turn") {
await this.emitProviderChildOutlivingTurn();
return;
}
if (textPrompt === "Start background work") {
await this.emitBackgroundWorkTurn();
return;
@@ -39,6 +39,7 @@ export function asAgentManager(stub: {
getRetiredInternalAgent: () => null,
effectiveOptionsFor: (_provider: string, own?: Record<string, unknown>) => own ?? {},
getAgentBackgroundWorkSummary: () => undefined,
getRunningProviderSubagentSummary: () => undefined,
...stub,
});
}
+17 -3
View File
@@ -998,9 +998,7 @@ export class VoiceAssistantWebSocketServer {
callback(false, 403, "Host not allowed");
return;
}
const sameOrigin = isWebSocketSameOrigin(origin, requestHost);
if (!origin || allowedOrigins.has("*") || allowedOrigins.has(origin) || sameOrigin) {
if (!origin || isDaemonOriginAllowed(origin, requestHost, allowedOrigins)) {
callback(true);
} else {
this.incrementRuntimeCounter("originRejected");
@@ -3267,6 +3265,22 @@ function isLoopbackAlias(hostname: string): boolean {
return /^127(?:\.\d{1,3}){3}$/.test(normalized);
}
/**
* Whether a page at `origin` may talk to the daemon reached at `requestHost`. The WebSocket
* upgrade and the HTTP CORS check both use it, so a page that can connect can also fetch.
*/
export function isDaemonOriginAllowed(
origin: string,
requestHost: string | null,
allowedOrigins: Set<string>,
): boolean {
return (
allowedOrigins.has("*") ||
allowedOrigins.has(origin) ||
isWebSocketSameOrigin(origin, requestHost)
);
}
export function isWebSocketSameOrigin(
origin: string | undefined,
requestHost: string | null,
@@ -118,6 +118,10 @@ class InMemoryAgentManager {
return undefined;
}
getRunningProviderSubagentSummary() {
return undefined;
}
fetchTimeline(_agentId: string, options?: AgentTimelineFetchOptions) {
return this.timeline.fetch("agent-1", options);
}
@@ -8,6 +8,7 @@ import type { WorkspaceGitService } from "./workspace-git-service.js";
import type { ForgeService } from "../services/forge-service.js";
import {
deletePaseoWorktree,
readWorktreeHeadReference,
isPaseoOwnedWorktreeCwd,
runWorktreeTeardownCommands,
WorktreeTeardownError,
@@ -707,7 +708,15 @@ export async function archivePersistedWorkspaceRecord(input: {
}
const archivedAt = input.archivedAt ?? new Date().toISOString();
await input.workspaceRegistry.archive(input.workspaceId, archivedAt, input.context);
let head: string | null = null;
if (existingWorkspace.kind === "worktree") {
const cwd = existingWorkspace.worktreeRoot ?? existingWorkspace.cwd;
head = await readWorktreeHeadReference(cwd);
}
await input.workspaceRegistry.archive(input.workspaceId, archivedAt, {
...input.context,
...(head ? { head } : {}),
});
return existingWorkspace;
}
@@ -151,6 +151,40 @@ test.skipIf(process.platform === "win32")(
60000,
);
test.skipIf(process.platform === "win32").each([
["branch", "restore"],
["branch", "undo"],
["detached", "restore"],
["detached", "undo"],
] as const)(
"%s checkout survives archive and %s",
async (checkout, action) => {
const repo = createRepoWithGatedTeardown();
repo.releaseTeardown();
const { workspaceId, directory } = await createWorktreeWorkspaceWithAgent(
repo.repoDir,
`keep-${checkout}-${action}`,
);
if (checkout === "detached") git(directory, ["switch", "--detach"]);
writeFileSync(path.join(directory, "change.txt"), `${checkout}\n`);
git(directory, ["add", "change.txt"]);
git(directory, ["-c", "commit.gpgsign=false", "commit", "-m", "workspace commit"]);
const readHead = (args: string[]) =>
execFileSync("git", args, { cwd: directory, encoding: "utf8" }).trim();
const commit = readHead(["rev-parse", "HEAD"]);
const branch = readHead(["rev-parse", "--abbrev-ref", "HEAD"]);
expect((await ctx.client.archiveWorkspace(workspaceId)).error).toBeNull();
expect(existsSync(directory)).toBe(false);
git(repo.repoDir, ["reflog", "expire", "--expire=now", "--all"]);
git(repo.repoDir, ["gc", "--prune=now"]);
if (action === "undo") await ctx.client.undoWorkspaceArchive(workspaceId);
else await ctx.client.restoreWorkspace(workspaceId);
expect(readHead(["rev-parse", "HEAD"])).toBe(commit);
expect(readHead(["rev-parse", "--abbrev-ref", "HEAD"])).toBe(branch);
},
60000,
);
test.skipIf(process.platform === "win32")(
"archive, undo, archive leaves the workspace archived",
async () => {
@@ -604,6 +604,7 @@ interface WorkspaceGitAuxiliaryReadCacheEntry<T> {
interface WorkspaceForgePrStatusPollTarget {
headRef: string;
currentBranch?: string;
headSha?: string;
headRepositoryOwner?: string;
}
@@ -3150,11 +3151,7 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
if (resolution.service.retainCurrentPullRequestStatusPoll) {
target.forgePrStatusPollSubscription = resolution.service.retainCurrentPullRequestStatusPoll({
cwd: target.cwd,
headRef: pollTarget.headRef,
...(pollTarget.headSha ? { headSha: pollTarget.headSha } : {}),
...(pollTarget.headRepositoryOwner
? { headRepositoryOwner: pollTarget.headRepositoryOwner }
: {}),
...pollTarget,
onStatus: (status) => {
if (!this.isActiveObservedWorkspaceTarget(target)) {
return;
@@ -3226,11 +3223,7 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
try {
const status = await service.getCurrentPullRequestStatus({
cwd: target.cwd,
headRef: pollTarget.headRef,
...(pollTarget.headSha ? { headSha: pollTarget.headSha } : {}),
...(pollTarget.headRepositoryOwner
? { headRepositoryOwner: pollTarget.headRepositoryOwner }
: {}),
...pollTarget,
reason: "self-heal-forge-pr-status",
});
if (!closed && this.isActiveObservedWorkspaceTarget(target)) {
@@ -3285,13 +3278,14 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
target.latestFacts?.isGit && target.latestFacts.currentBranch === git.currentBranch
? target.latestFacts.pullRequestLookupTarget
: null;
if (target.latestFacts?.isGit && target.latestFacts.paseoWorktree.isPaseoOwnedWorktree) {
return lookupTarget;
}
if (lookupTarget) {
return lookupTarget;
return git.currentBranch === lookupTarget.headRef
? lookupTarget
: { ...lookupTarget, currentBranch: git.currentBranch };
}
if (target.latestFacts?.isGit && target.latestFacts.paseoWorktree.isPaseoOwnedWorktree) {
return null;
}
return { headRef: git.currentBranch };
}
@@ -4424,6 +4418,7 @@ function buildWorkspaceForgePrStatusPollKey({
forge,
remoteUrl,
target.headRef,
target.currentBranch ?? null,
target.headSha ?? null,
target.headRepositoryOwner ?? null,
]);
@@ -72,6 +72,7 @@ const PersistedWorkspaceRecordSchema = z.object({
.nullable()
.optional()
.transform((value) => value ?? null),
head: z.string().optional(),
// Exact checkout/worktree root backing cwd. This differs from cwd when the
// selected project is a subdirectory inside a repository. Persist it so
// archive and recovery do not need the directory to still exist in order to
@@ -126,6 +127,7 @@ export interface WorkspaceMutationContext {
export interface WorkspaceArchiveContext {
autoArchivedChangeRequestUrl?: string;
head?: string;
}
export interface ProjectMutation {
@@ -586,6 +588,7 @@ export class FileBackedWorkspaceRegistry
...existing,
updatedAt: archivedAt,
archivedAt,
head: context?.head,
...(context?.autoArchivedChangeRequestUrl
? { autoArchivedChangeRequestUrl: context.autoArchivedChangeRequestUrl }
: {}),
+23 -14
View File
@@ -436,6 +436,22 @@ export interface CreatePullRequestOptions {
body?: string;
}
export interface CurrentPullRequestLookup {
cwd: string;
headRef: string;
headSha?: string;
headRepositoryOwner?: string;
/** Local branch name when it differs from the PR source ref. */
currentBranch?: string;
}
export function isOnDefaultBranch(
lookup: Pick<CurrentPullRequestLookup, "currentBranch" | "headRef">,
defaultBranch: string | null | undefined,
): boolean {
return (lookup.currentBranch ?? lookup.headRef) === defaultBranch;
}
export interface ForgeService {
listPullRequests(options: ListPullRequestsOptions): Promise<PullRequestSummary[]>;
listIssues(options: ListIssuesOptions): Promise<IssueSummary[]>;
@@ -475,12 +491,7 @@ export interface ForgeService {
*/
getReferenceRepository?(options: { cwd: string } & ForgeReadOptions): Promise<string | null>;
getCurrentPullRequestStatus(
options: {
cwd: string;
headRef: string;
headSha?: string;
headRepositoryOwner?: string;
} & ForgeReadOptions,
options: CurrentPullRequestLookup & ForgeReadOptions,
): Promise<CurrentPullRequestStatus | null>;
getPullRequestTimeline(options: GetPullRequestTimelineOptions): Promise<PullRequestTimeline>;
getCheckDetails(options: GetCheckDetailsOptions): Promise<CheckDetails>;
@@ -516,14 +527,12 @@ export interface ForgeService {
* cannot change the outcome and is pure overhead.
*/
authProbeCanThrow?: boolean;
retainCurrentPullRequestStatusPoll?(options: {
cwd: string;
headRef: string;
headSha?: string;
headRepositoryOwner?: string;
onStatus?: (status: CurrentPullRequestStatus | null) => void;
onError?: (error: unknown) => void;
}): { unsubscribe: () => void };
retainCurrentPullRequestStatusPoll?(
options: CurrentPullRequestLookup & {
onStatus?: (status: CurrentPullRequestStatus | null) => void;
onError?: (error: unknown) => void;
},
): { unsubscribe: () => void };
invalidate(options: { cwd: string }): void;
dispose?(): void;
}
@@ -2036,6 +2036,33 @@ describe("createGiteaService", () => {
]);
});
it("hides a historical PR on the repository's default branch", async () => {
const historical = currentPullRequestApi({
number: 8,
state: "closed",
headRef: "trunk",
headSha: "8888888888888888888888888888888888888888",
});
const { service } = makeService((args) => {
if (args[0] === "pr" && args[1] === "list") return ok("[]");
if (args[0] === "api" && args[1].includes("/pulls?state=all")) {
return ok(JSON.stringify([historical]));
}
if (args[0] === "api" && args[1] === "repos/example-user/sample-repo") {
return ok(
JSON.stringify({
full_name: "example-user/sample-repo",
default_branch: "trunk",
}),
);
}
throw new Error(`unexpected call: ${args.join(" ")}`);
});
await expect(
service.getCurrentPullRequestStatus({ cwd: "/repo", headRef: "trunk" }),
).resolves.toBeNull();
});
it("falls back to the recent all-state PR window for a recently closed current branch PR", async () => {
const headSha = "8888888888888888888888888888888888888888";
const closedPr = currentPullRequestApi({
+28 -23
View File
@@ -26,11 +26,13 @@ import {
compareTimelineItems,
createUnavailableSearchResult,
normalizeForgeSearchKinds,
isOnDefaultBranch,
parseOptionalTime,
} from "./forge-service.js";
import type {
CheckDetails,
CreatePullRequestOptions,
CurrentPullRequestLookup,
CurrentPullRequestStatus,
DisablePullRequestAutoMergeOptions,
EnablePullRequestAutoMergeOptions,
@@ -251,6 +253,7 @@ const GiteaPullRequestApiSchema = z
const GiteaRepositoryApiSchema = z
.object({
full_name: z.string(),
default_branch: z.string().nullish(),
parent: z.object({ full_name: z.string().optional() }).nullable().optional(),
})
.passthrough();
@@ -1585,11 +1588,9 @@ export function createGiteaService(options: CreateGiteaServiceOptions = {}): For
return { items, truncated: true };
}
async function loadCurrentPullRequestStatus(input: {
cwd: string;
headRef: string;
headSha?: string;
}): Promise<CurrentPullRequestStatus | null> {
async function loadCurrentPullRequestStatus(
input: CurrentPullRequestLookup,
): Promise<CurrentPullRequestStatus | null> {
const match = await findCurrentPullRequestForHeadRef(input);
if (!match) {
return null;
@@ -1613,11 +1614,19 @@ export function createGiteaService(options: CreateGiteaServiceOptions = {}): For
return identity ? { owner: identity.owner, name: identity.name } : null;
}
async function findCurrentPullRequestForHeadRef(input: {
cwd: string;
headRef: string;
headSha?: string;
}): Promise<GiteaPrListItem | null> {
function readRepository(cwd: string, repoPath: string) {
return runJson(["api", repoPath], { cwd }, GiteaRepositoryApiSchema);
}
function repositoryApiPath(repo: { owner: string; name: string } | null): string {
return repo
? `repos/${encodeURIComponent(repo.owner)}/${encodeURIComponent(repo.name)}`
: "repos/{owner}/{repo}";
}
async function findCurrentPullRequestForHeadRef(
input: CurrentPullRequestLookup,
): Promise<GiteaPrListItem | null> {
const repoIdentity = await resolveCurrentRepoIdentity(input.cwd);
const expectedHeadOwner = repoIdentity?.owner ?? null;
const openMatch = await findOpenPullRequestForHeadRef(input, expectedHeadOwner);
@@ -1628,9 +1637,7 @@ export function createGiteaService(options: CreateGiteaServiceOptions = {}): For
// tea discovers repository context from any configured git remote, while
// the default remote resolver reads origin only. Preserve that broader
// discovery for repositories whose primary remote has another name.
const repoPath = repoIdentity
? `repos/${encodeURIComponent(repoIdentity.owner)}/${encodeURIComponent(repoIdentity.name)}`
: "repos/{owner}/{repo}";
const repoPath = repositoryApiPath(repoIdentity);
const recentItems = await runJsonArray(
[
"api",
@@ -1666,6 +1673,12 @@ export function createGiteaService(options: CreateGiteaServiceOptions = {}): For
) ??
candidates[0] ??
null;
if (match && mapGiteaState(match.state) !== "open") {
const repository = await readRepository(input.cwd, repoPath).catch(() => null);
if (isOnDefaultBranch(input, repository?.default_branch)) {
return null;
}
}
return match ? currentPullRequestApiToListItem(match) : null;
}
@@ -2020,20 +2033,12 @@ export function createGiteaService(options: CreateGiteaServiceOptions = {}): For
if (!repo) {
return null;
}
const repository = await runJson(
["api", `repos/${encodeURIComponent(repo.owner)}/${encodeURIComponent(repo.name)}`],
{ cwd: input.cwd },
GiteaRepositoryApiSchema,
);
const repository = await readRepository(input.cwd, repositoryApiPath(repo));
return repository.parent?.full_name ?? null;
},
getCurrentPullRequestStatus(input): Promise<CurrentPullRequestStatus | null> {
return loadCurrentPullRequestStatus({
cwd: input.cwd,
headRef: input.headRef,
headSha: input.headSha,
});
return loadCurrentPullRequestStatus(input);
},
async getPullRequest(input: GetPullRequestOptions): Promise<PullRequestSummary> {
@@ -552,7 +552,7 @@ describe("ForgeService", () => {
"view",
"fork-owner/repo",
"--json",
"owner,name,parent",
"owner,name,parent,defaultBranchRef",
]);
});
@@ -862,7 +862,7 @@ describe("ForgeService", () => {
expect(runner.calls).toHaveLength(2);
expect(runner.calls[0]).toEqual({
cwd: "/repo",
args: ["repo", "view", "--json", "owner,name,parent"],
args: ["repo", "view", "--json", "owner,name,parent,defaultBranchRef"],
});
expect(runner.calls[1]?.cwd).toBe("/repo");
expect(runner.calls[1]?.args.slice(0, 3)).toEqual(["api", "graphql", "-f"]);
@@ -1111,6 +1111,56 @@ describe("ForgeService", () => {
expect(currentPullRequestStatusCalls(runner.calls)).toHaveLength(1);
});
it.each([
{ currentBranch: undefined, state: "MERGED", expected: null, calls: 1 },
{ currentBranch: undefined, state: "OPEN", expected: "open", calls: 2 },
{ currentBranch: "fork/trunk", state: "MERGED", expected: "merged", calls: 2 },
])(
"polls a $state PR with source trunk from checkout $currentBranch",
async ({ currentBranch, state, expected, calls }) => {
const runner = createScriptedRunner([
batchPollStatusJson({
t0: batchPollRepositoryJson(
[
batchPollPrNodeJson({
headRefName: "trunk",
state,
...(state === "OPEN" ? { mergedAt: null } : {}),
}),
],
{
defaultBranchRef: { name: "trunk" },
},
),
}),
batchPollStatusJson({ t0: batchPollChecksAliasJson([]) }),
]);
const service = createGitHubService({
runner: runner.runner,
resolveGhPath: async () => "/usr/bin/gh",
resolveRepoHost: async () => null,
resolveRepoSlug: async () => "acme/widgets",
now: () => 0,
});
const statuses: Array<CurrentPullRequestStatus | null> = [];
try {
service.retainCurrentPullRequestStatusPoll?.({
cwd: "/repo",
headRef: "trunk",
currentBranch,
onStatus: (status) => statuses.push(status),
});
await vi.advanceTimersByTimeAsync(0);
await flushMicrotasks();
expect(statuses.map((status) => status?.state ?? null)).toEqual([expected]);
expect(runner.calls).toHaveLength(calls);
} finally {
service.dispose?.();
}
},
);
it("batches PR status polls across workspaces into one GraphQL request", async () => {
let now = 0;
const runner = createScriptedRunner([
@@ -1490,13 +1540,19 @@ describe("ForgeService", () => {
batchPollStatusJson({
t0: batchPollRepositoryJson([], { isFork: true, parent }),
}),
batchPollStatusJson({ t0: batchPollRepositoryJson([forkPr]) }),
batchPollStatusJson({
t0: batchPollRepositoryJson([forkPr], { defaultBranchRef: { name: "feat-a" } }),
origin0: { defaultBranchRef: { name: "main" } },
}),
batchPollStatusJson({
t0: batchPollChecksAliasJson([
{ __typename: "StatusContext", context: "ci", state: "SUCCESS" },
]),
}),
batchPollStatusJson({ t0: batchPollRepositoryJson([forkPr]) }),
batchPollStatusJson({
t0: batchPollRepositoryJson([forkPr], { defaultBranchRef: { name: "feat-a" } }),
origin0: { defaultBranchRef: { name: "main" } },
}),
]);
const service = createGitHubService({
ttlMs: 0,
@@ -1524,6 +1580,9 @@ describe("ForgeService", () => {
expect(runner.calls[1]?.args[3]).toContain(
't0: repository(owner: "upstream", name: "widgets")',
);
expect(runner.calls[1]?.args[3]).toContain(
'origin0: repository(owner: "forkowner", name: "widgets")',
);
expect(statuses).toEqual([
expect.objectContaining({ number: 42, repoOwner: "upstream", checksStatus: "success" }),
]);
@@ -3278,6 +3337,30 @@ describe("ForgeService", () => {
});
});
it.each([
["main", "CLOSED"],
["master", "MERGED"],
])("hides a %s PR on the default branch in a direct read (state %s)", async (headRef, state) => {
const historical = currentPullRequestJson({
headRefName: headRef,
headRepositoryOwner: { login: "acme" },
state,
});
const runner = createScriptedRunner([
historical,
JSON.stringify({ owner: { login: "acme" }, defaultBranchRef: { name: headRef } }),
JSON.stringify([JSON.parse(historical)]),
]);
const service = createGitHubService({
runner: runner.runner,
resolveGhPath: async () => "/usr/bin/gh",
});
await expect(
service.getCurrentPullRequestStatus({ cwd: "/repo", headRef }),
).resolves.toBeNull();
});
it("keeps a merged PR when headRefOid matches the checkout HEAD", async () => {
const headSha = "2222222222222222222222222222222222222222";
const runner = createRunner([
@@ -3605,7 +3688,7 @@ describe("ForgeService", () => {
});
expect(runner.calls.slice(0, 5).map((call) => call.args)).toEqual([
["pr", "view", "--json", CURRENT_PR_STATUS_FIELDS],
["repo", "view", "--json", "owner,name,parent"],
["repo", "view", "--json", "owner,name,parent,defaultBranchRef"],
["api", `repos/parentOwner/parentRepo/pulls?${FORK_PR_QUERY}`],
["pr", "view", "41", "--repo", "parentOwner/parentRepo", "--json", CURRENT_PR_STATUS_FIELDS],
["pr", "view", "42", "--repo", "parentOwner/parentRepo", "--json", CURRENT_PR_STATUS_FIELDS],
@@ -3837,7 +3920,7 @@ describe("ForgeService", () => {
});
expect(runner.calls.slice(0, 5).map((call) => call.args)).toEqual([
["pr", "view", "--json", CURRENT_PR_STATUS_FIELDS],
["repo", "view", "--json", "owner,name,parent"],
["repo", "view", "--json", "owner,name,parent,defaultBranchRef"],
["api", `repos/parentOwner/parentRepo/pulls?${FORK_PR_QUERY}`],
["pr", "view", "42", "--repo", "parentOwner/parentRepo", "--json", CURRENT_PR_STATUS_FIELDS],
[
@@ -3902,7 +3985,7 @@ describe("ForgeService", () => {
).resolves.toBeNull();
expect(calls.map((call) => call.args)).toEqual([
["pr", "view", "--json", CURRENT_PR_STATUS_FIELDS],
["repo", "view", "--json", "owner,name,parent"],
["repo", "view", "--json", "owner,name,parent,defaultBranchRef"],
[
"pr",
"list",
@@ -4750,7 +4833,12 @@ describe("ForgeService", () => {
}),
).resolves.toEqual({ url: "https://github.com/acme/repo/pull/7", number: 7 });
expect(runner.calls[0]?.args).toEqual(["repo", "view", "--json", "owner,name,parent"]);
expect(runner.calls[0]?.args).toEqual([
"repo",
"view",
"--json",
"owner,name,parent,defaultBranchRef",
]);
expect(runner.calls[1]?.args).toEqual([
"api",
"-X",
@@ -4824,7 +4912,7 @@ describe("ForgeService", () => {
expect(readFakeGitHubCliLog(fixture.logPath)).toEqual(
expect.arrayContaining([
"auth status --hostname github.acme.internal|",
"repo view --json owner,name,parent|github.acme.internal",
"repo view --json owner,name,parent,defaultBranchRef|github.acme.internal",
"api -X POST repos/acme/repo/pulls -f title=Add thing -f head=feature -f base=main|github.acme.internal",
]),
);
@@ -4869,7 +4957,7 @@ describe("ForgeService", () => {
).toHaveLength(2);
expect(log).toEqual(
expect.arrayContaining([
"repo view --json owner,name,parent|github.acme.internal",
"repo view --json owner,name,parent,defaultBranchRef|github.acme.internal",
"api -X POST repos/acme/repo/pulls -f title=Add thing -f head=feature -f base=main|github.acme.internal",
]),
);
+106 -60
View File
@@ -27,6 +27,7 @@ import {
computeChecksStatus,
compareTimelineItems,
createUnavailableSearchResult,
isOnDefaultBranch,
normalizeForgeSearchKinds,
parseOptionalTime,
} from "./forge-service.js";
@@ -34,6 +35,7 @@ import type {
CheckAnnotation,
CheckDetails,
CheckFailedJob,
CurrentPullRequestLookup,
CurrentPullRequestStatus,
DisablePullRequestAutoMergeOptions,
EnablePullRequestAutoMergeOptions,
@@ -446,7 +448,11 @@ const PullRequestTimelineGraphqlSchema = z.object({
.optional(),
});
const GitHubRepoViewSchema = z.object({
const GitHubDefaultBranchSchema = z.object({
defaultBranchRef: z.object({ name: z.string() }).nullish(),
});
const GitHubRepoViewSchema = GitHubDefaultBranchSchema.extend({
owner: z
.object({
login: z.string().optional(),
@@ -657,7 +663,7 @@ const BatchPollPrNodeSchema = z.object({
isInMergeQueue: z.boolean().optional().catch(false),
});
const BatchPollRepositorySchema = z.object({
const BatchPollRepositorySchema = GitHubDefaultBranchSchema.extend({
owner: z.object({ login: z.string().optional() }).nullable().optional().catch(null),
isFork: z.boolean().optional().catch(false),
parent: z
@@ -779,9 +785,7 @@ function graphqlString(value: string): string {
return JSON.stringify(value);
}
function buildBatchPullRequestStatusQuery(
entries: Array<{ owner: string; name: string; headRef: string }>,
): string {
function buildBatchPullRequestStatusQuery(entries: GitHubBatchPollEntry[]): string {
const aliases = entries.map(
(entry, index) => ` ${batchAlias(index)}: repository(owner: ${graphqlString(
entry.owner,
@@ -789,6 +793,9 @@ function buildBatchPullRequestStatusQuery(
owner {
login
}
defaultBranchRef {
name
}
isFork
parent {
owner {
@@ -802,7 +809,7 @@ function buildBatchPullRequestStatusQuery(
rebaseMergeAllowed
viewerDefaultMergeMethod
pullRequests(headRefName: ${graphqlString(
entry.headRef,
entry.target.headRef,
)}, first: ${BATCH_PR_CANDIDATE_LIMIT}, orderBy: {field: CREATED_AT, direction: DESC}) {
nodes {
...PaseoPollPullRequest
@@ -810,13 +817,26 @@ function buildBatchPullRequestStatusQuery(
}
}`,
);
const originAliases = entries.flatMap((entry, index) =>
entry.owner === entry.originOwner && entry.name === entry.originName
? []
: [
` origin${index}: repository(owner: ${graphqlString(
entry.originOwner,
)}, name: ${graphqlString(entry.originName)}) {
defaultBranchRef {
name
}
}`,
],
);
return `query PaseoBatchPullRequestStatus {
rateLimit {
limit
remaining
resetAt
}
${aliases.join("\n")}
${[...aliases, ...originAliases].join("\n")}
}\n${BATCH_PR_STATUS_FRAGMENT}`;
}
@@ -1076,11 +1096,7 @@ interface InFlightCacheEntry {
force: boolean;
}
interface GitHubPollTarget {
cwd: string;
headRef: string;
headSha?: string;
headRepositoryOwner?: string;
interface GitHubPollTarget extends CurrentPullRequestLookup {
retainCount: number;
/** Absolute due time on the shared poll grid; null while a poll is in flight. */
nextDueAt: number | null;
@@ -1364,12 +1380,7 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G
});
}
function getPollTargetKey(target: {
cwd: string;
headRef: string;
headSha?: string;
headRepositoryOwner?: string;
}): string {
function getPollTargetKey(target: CurrentPullRequestLookup): string {
return buildCacheKey({
cwd: target.cwd,
method: "getCurrentPullRequestStatus",
@@ -1377,18 +1388,17 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G
headRef: target.headRef,
headSha: target.headSha,
headRepositoryOwner: target.headRepositoryOwner,
currentBranch: target.currentBranch,
},
});
}
function updatePollTargetAfterSuccess(update: {
cwd: string;
headRef: string;
headSha?: string;
headRepositoryOwner?: string;
status: CurrentPullRequestStatus | null;
notify: boolean;
}): void {
function updatePollTargetAfterSuccess(
update: CurrentPullRequestLookup & {
status: CurrentPullRequestStatus | null;
notify: boolean;
},
): void {
const target = pollTargets.get(getPollTargetKey(update));
if (!target) {
return;
@@ -1638,13 +1648,7 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G
if (!firstEntry) {
return;
}
const query = buildBatchPullRequestStatusQuery(
addressedEntries.map((entry) => ({
owner: entry.owner,
name: entry.name,
headRef: entry.target.headRef,
})),
);
const query = buildBatchPullRequestStatusQuery(addressedEntries);
const args = ["api", "graphql", "-f", `query=${query}`];
const response = await loadGitHubPollBatchResponse({
entries: addressedEntries,
@@ -1760,6 +1764,18 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G
}
continue;
}
if (
isTerminalOnDefaultBranch(entry, node, repository.data, input.aliases[`origin${index}`])
) {
finalizeBatchPollTarget({
entry,
node: null,
repository: repository.data,
rollup: null,
startedAt: input.startedAt,
});
continue;
}
const frozenKey =
node.state !== "OPEN" && node.headRefOid.length > 0
? `${entry.owner}/${entry.name}#${node.number}@${node.headRefOid}`
@@ -1786,6 +1802,22 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G
return distribution;
}
function isTerminalOnDefaultBranch(
entry: GitHubBatchPollEntry,
node: BatchPollPrNode,
repository: BatchPollRepository,
originAlias: unknown,
): boolean {
if (node.state === "OPEN") {
return false;
}
const origin =
entry.owner === entry.originOwner && entry.name === entry.originName
? repository
: GitHubDefaultBranchSchema.safeParse(originAlias).data;
return isOnDefaultBranch(entry.target, origin?.defaultBranchRef?.name);
}
function addressGitHubBatchEntry(entry: GitHubBatchPollEntry): GitHubBatchPollEntry {
const redirect = pollRepositoryRedirects.get(batchRepositoryRedirectKey(entry));
return redirect
@@ -1963,25 +1995,14 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G
);
status = built ? { ...built, forgeSpecific: { forge: "github", ...facts } } : null;
}
const cacheKey = buildCacheKey({
cwd: entry.target.cwd,
method: "getCurrentPullRequestStatus",
args: {
headRef: entry.target.headRef,
headSha: entry.target.headSha,
headRepositoryOwner: entry.target.headRepositoryOwner,
},
});
const cacheKey = getPollTargetKey(entry.target);
// A direct or forced read can finish between this batch becoming due and
// its checks query returning. Its cache write is newer than this cycle, so
// converge on it instead of overwriting fresher data with the batch's.
const existing = cache.get(cacheKey);
if (existing && existing.expiresAt - ttlMs > input.startedAt) {
updatePollTargetAfterSuccess({
cwd: entry.target.cwd,
headRef: entry.target.headRef,
headSha: entry.target.headSha,
headRepositoryOwner: entry.target.headRepositoryOwner,
...entry.target,
status: existing.value as CurrentPullRequestStatus | null,
notify: true,
});
@@ -1991,10 +2012,7 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G
// between polls reuse the batch result instead of spawning gh again.
cache.set(cacheKey, { value: status, cwd: entry.target.cwd, expiresAt: deps.now() + ttlMs });
updatePollTargetAfterSuccess({
cwd: entry.target.cwd,
headRef: entry.target.headRef,
headSha: entry.target.headSha,
headRepositoryOwner: entry.target.headRepositoryOwner,
...entry.target,
status,
notify: true,
});
@@ -2007,6 +2025,7 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G
headRef: target.headRef,
headSha: target.headSha,
headRepositoryOwner: target.headRepositoryOwner,
currentBranch: target.currentBranch,
reason: "self-heal-github",
});
} catch (error) {
@@ -2173,14 +2192,17 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G
headRef: input.headRef,
headSha: input.headSha,
headRepositoryOwner: input.headRepositoryOwner,
currentBranch: input.currentBranch,
},
readOptions: input,
load: async () => {
const status = await resolveCurrentPullRequestView({
const status = await loadCurrentPullRequestView({
cwd: input.cwd,
headRef: input.headRef,
headSha: input.headSha,
headRepositoryOwner: input.headRepositoryOwner,
currentBranch: input.currentBranch,
resolveOriginRepo: () => resolveRepoSlugCached(input.cwd),
run,
});
return addCurrentPullRequestGithubFacts({ cwd: input.cwd, status, run });
@@ -2191,6 +2213,7 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G
headRef: input.headRef,
headSha: input.headSha,
headRepositoryOwner: input.headRepositoryOwner,
currentBranch: input.currentBranch,
status,
notify: input.reason === "self-heal-github",
});
@@ -2603,6 +2626,7 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G
headRef: input.headRef,
headSha: input.headSha,
headRepositoryOwner: input.headRepositoryOwner,
currentBranch: input.currentBranch,
retainCount: 0,
nextDueAt: null,
pollCycleStartedAt: null,
@@ -2984,13 +3008,35 @@ function isGitHubRateLimitError(error: unknown): boolean {
);
}
async function resolveCurrentPullRequestView(options: {
cwd: string;
headRef: string;
headSha?: string;
headRepositoryOwner?: string;
run: (args: string[], options: GitHubCommandRunnerOptions) => Promise<string>;
}): Promise<CurrentPullRequestStatus | null> {
async function loadCurrentPullRequestView(
options: CurrentPullRequestLookup & {
resolveOriginRepo(): Promise<string | null>;
run: (args: string[], options: GitHubCommandRunnerOptions) => Promise<string>;
},
): Promise<CurrentPullRequestStatus | null> {
let repoRead: ReturnType<typeof getGitHubRepoView> | undefined;
const readRepo = () => (repoRead ??= getGitHubRepoView(options));
const status = await resolveCurrentPullRequestView({ ...options, readRepo });
if (!status || status.state === "open") {
return status;
}
const originRepo = await options.resolveOriginRepo();
const repo = await repoRead;
const repoName = repo?.owner?.login && repo.name ? `${repo.owner.login}/${repo.name}` : null;
const origin =
originRepo && originRepo.toLowerCase() !== repoName?.toLowerCase()
? await getGitHubRepoView({ ...options, repo: originRepo })
: await readRepo();
return isOnDefaultBranch(options, origin?.defaultBranchRef?.name) ? null : status;
}
async function resolveCurrentPullRequestView(
options: CurrentPullRequestLookup & {
readRepo(): Promise<z.infer<typeof GitHubRepoViewSchema> | null>;
run: (args: string[], options: GitHubCommandRunnerOptions) => Promise<string>;
},
): Promise<CurrentPullRequestStatus | null> {
const viewCandidate = await tryCurrentPullRequestView(options);
const viewMatch = viewCandidate
? pickPullRequestCandidate({
@@ -3007,7 +3053,7 @@ async function resolveCurrentPullRequestView(options: {
let headRepositoryOwner = options.headRepositoryOwner;
if (!headRepositoryOwner) {
const repo = await getGitHubRepoView(options);
const repo = await options.readRepo();
const forkOwner = repo?.owner?.login;
const parentOwner = repo?.parent?.owner?.login;
const parentName = repo?.parent?.name;
@@ -3282,7 +3328,7 @@ async function readGitHubRepoView(
"view",
...(options.repo ? [options.repo] : []),
"--json",
"owner,name,parent",
"owner,name,parent,defaultBranchRef",
];
const stdout = await options.run(args, {
cwd: options.cwd,
@@ -389,6 +389,26 @@ describe("createGitLabService", () => {
expect(calls[1]).toEqual(["mr", "view", "270", "-F", "json"]);
});
it("hides a historical MR on the project's default branch", async () => {
const historical = { ...OPEN_MR, state: "merged", source_branch: "trunk" };
const { service } = makeService((args) => {
if (args[1] === "list") return ok(JSON.stringify([historical]));
if (args[1] === "view") return ok(JSON.stringify(historical));
if (args[0] === "api" && args[1] === "projects/example-group%2Fexample-project") {
return ok(
JSON.stringify({
path_with_namespace: "example-group/example-project",
default_branch: "trunk",
}),
);
}
return ok("{}");
});
await expect(
service.getCurrentPullRequestStatus({ cwd: "/repo", headRef: "trunk" }),
).resolves.toBeNull();
});
it("keeps a merged MR when its remote head advances beyond the checkout", async () => {
const stale = {
...OPEN_MR,
+23 -11
View File
@@ -16,6 +16,7 @@ import {
compareTimelineItems,
createUnavailableSearchResult,
normalizeForgeSearchKinds,
isOnDefaultBranch,
parseOptionalTime,
} from "./forge-service.js";
import type {
@@ -252,6 +253,7 @@ const GitLabApprovalsSchema = z
const GitLabProjectSchema = z
.object({
path_with_namespace: z.string(),
default_branch: z.string().nullish(),
forked_from_project: z
.object({ path_with_namespace: z.string().optional() })
.nullable()
@@ -1142,6 +1144,19 @@ export function createGitLabService(options: CreateGitLabServiceOptions = {}): F
return issues.map(toIssueSummary);
}
async function readOriginProject(cwd: string) {
const remoteUrl = await resolveRemoteUrl(cwd);
const projectPath = remoteUrl ? parseGitRemoteLocation(remoteUrl)?.path : null;
if (!projectPath) {
return null;
}
return runJson(
["api", `projects/${encodeURIComponent(projectPath)}`],
{ cwd: cwd },
GitLabProjectSchema,
);
}
return {
async isAuthenticated(input: { cwd: string } & ForgeReadOptions): Promise<boolean> {
const glabPath = await resolveGlab();
@@ -1162,17 +1177,8 @@ export function createGitLabService(options: CreateGitLabServiceOptions = {}): F
},
async getReferenceRepository(input): Promise<string | null> {
const remoteUrl = await resolveRemoteUrl(input.cwd);
const projectPath = remoteUrl ? parseGitRemoteLocation(remoteUrl)?.path : null;
if (!projectPath) {
return null;
}
const project = await runJson(
["api", `projects/${encodeURIComponent(projectPath)}`],
{ cwd: input.cwd },
GitLabProjectSchema,
);
return project.forked_from_project?.path_with_namespace ?? null;
const project = await readOriginProject(input.cwd);
return project?.forked_from_project?.path_with_namespace ?? null;
},
async getCurrentPullRequestStatus(input): Promise<CurrentPullRequestStatus | null> {
@@ -1181,6 +1187,12 @@ export function createGitLabService(options: CreateGitLabServiceOptions = {}): F
if (!mr) {
return null;
}
if (mapMergeRequestState(mr.state) !== "open") {
const project = await readOriginProject(input.cwd).catch(() => null);
if (isOnDefaultBranch(input, project?.default_branch)) {
return null;
}
}
const [approvals, pipelineChecks] = await Promise.all([
fetchApprovals(input.cwd, mr),
fetchPipelineChecks(input.cwd, mr),
@@ -13,6 +13,7 @@ import {
import { createRequire } from "node:module";
import { access, readdir, rm } from "node:fs/promises";
import path from "node:path";
import { setTimeout as delay } from "node:timers/promises";
import { fileURLToPath } from "node:url";
import { ensurePrivateDirectory } from "../server/private-files.js";
import { listTerminalWorkerRecords, terminalWorkerDirectory } from "./terminal-worker-record.js";
@@ -193,6 +194,28 @@ export function prepareTerminalWorkerRuntime(input: {
return entry;
}
// Windows keeps a just-exited worker's files open for a moment, so a delete that fails with one
// of these codes is retried for a short window. Each attempt is a single rm: rm's own maxRetries
// repeats at every directory level, so a file that stays locked deep in node-pty would hold
// daemon start and stop far past any window.
const TRANSIENT_REMOVE_ERRORS = new Set(["EPERM", "EBUSY", "EACCES", "ENOTEMPTY"]);
const TRANSIENT_REMOVE_WINDOW_MS = 3_000;
const TRANSIENT_REMOVE_PAUSE_MS = 100;
async function removeCopy(directory: string): Promise<void> {
const deadline = Date.now() + TRANSIENT_REMOVE_WINDOW_MS;
for (;;) {
try {
await rm(directory, { recursive: true, force: true });
return;
} catch (error) {
const code = (error as NodeJS.ErrnoException).code;
if (!code || !TRANSIENT_REMOVE_ERRORS.has(code) || Date.now() >= deadline) throw error;
await delay(TRANSIENT_REMOVE_PAUSE_MS);
}
}
}
export interface PruneTerminalWorkerRuntimesResult {
removed: string[];
/** Copies that could not be deleted (a worker that just exited can still hold files on Windows). */
@@ -236,7 +259,7 @@ export async function pruneTerminalWorkerRuntimes(
)
continue;
try {
await rm(directory, { recursive: true, force: true });
await removeCopy(directory);
result.removed.push(directory);
} catch (error) {
result.failed.push({
+22 -2
View File
@@ -178,6 +178,7 @@ function createPullRequestStatus(overrides?: Partial<CurrentPullRequestStatus>)
interface RequestedPullRequestTarget {
headRef: string;
currentBranch?: string;
headSha?: string;
headRepositoryOwner?: string;
}
@@ -194,6 +195,7 @@ function createGitHubServiceRecordingPullRequestTargets(
github.getCurrentPullRequestStatus = async (request) => {
options.requestedTargets.push({
headRef: request.headRef,
...(request.currentBranch ? { currentBranch: request.currentBranch } : {}),
...(request.headSha ? { headSha: request.headSha } : {}),
...(request.headRepositoryOwner ? { headRepositoryOwner: request.headRepositoryOwner } : {}),
});
@@ -3460,7 +3462,7 @@ const x = 1;
{ paseoHome },
);
expect(requestedTargets).toEqual([factsTarget]);
expect(requestedTargets).toEqual([{ ...factsTarget, currentBranch: "tender-parrot" }]);
});
it("uses the tracked fork branch for PR worktree status lookup", async () => {
@@ -3490,7 +3492,11 @@ const x = 1;
const status = await getPullRequestStatus(repoDir, github);
expect(requestedTargets).toEqual([
expect.objectContaining({ headRef: "main", headRepositoryOwner: "chethanuk" }),
expect.objectContaining({
headRef: "main",
currentBranch: "chethanuk/main",
headRepositoryOwner: "chethanuk",
}),
]);
expect(status.status?.number).toBe(345);
expect(status.status?.headRefName).toBe("main");
@@ -3521,6 +3527,20 @@ const x = 1;
expect(status.status?.state).toBe("closed");
});
it("looks up PR status again when switching branches at the same commit", async () => {
execFileSync("git", ["checkout", "-b", "feature"], { cwd: repoDir });
const requestedTargets: RequestedPullRequestTarget[] = [];
const forge = createGitHubServiceRecordingPullRequestTargets({ requestedTargets });
const feature = await getPullRequestStatus(repoDir, forge);
execFileSync("git", ["checkout", "main"], { cwd: repoDir });
const main = await getPullRequestStatus(repoDir, forge);
expect(feature.status?.headRefName).toBe("feature");
expect(main.status?.headRefName).toBe("main");
expect(requestedTargets.map(({ headRef }) => headRef)).toEqual(["feature", "main"]);
});
it("caches PR status results for duplicate lookups", async () => {
execFileSync("git", ["checkout", "-b", "feature"], { cwd: repoDir });
execFileSync("git", ["remote", "add", "origin", "https://github.com/getpaseo/paseo.git"], {
+18 -12
View File
@@ -153,8 +153,12 @@ function createShortstatCache(ttlMs: number) {
});
}
function getPullRequestStatusCacheKey(cwd: string, headSha: string | null): string {
return `${resolve(cwd)}\u0000${headSha ?? ""}`;
function getPullRequestStatusCacheKey(
cwd: string,
currentBranch: string | null,
headSha: string | null,
): string {
return `${resolve(cwd)}\u0000${currentBranch ?? ""}\u0000${headSha ?? ""}`;
}
function rememberPullRequestStatus(cacheKey: string, status: PullRequestStatusResult): void {
@@ -4437,8 +4441,11 @@ export async function getPullRequestStatus(
options?: CheckoutReadCacheOptions,
context?: CheckoutContext,
): Promise<PullRequestStatusResult> {
const headSha = await getCurrentHeadSha(cwd, context);
const cacheKey = getPullRequestStatusCacheKey(cwd, headSha);
const [headSha, head] = await Promise.all([
getCurrentHeadSha(cwd, context),
context?.facts?.isGit ? context.facts.currentBranch : getCurrentBranch(cwd, context),
]);
const cacheKey = getPullRequestStatusCacheKey(cwd, head, headSha);
if (!options?.force) {
const cached = pullRequestStatusCache.get(cacheKey);
if (cached) {
@@ -4451,7 +4458,7 @@ export async function getPullRequestStatus(
}
}
const lookup = getPullRequestStatusUncached(cwd, forgeService, options, context, headSha)
const lookup = getPullRequestStatusUncached(cwd, forgeService, head, options, context, headSha)
.then((status) => {
pullRequestStatusCache.set(cacheKey, status);
rememberPullRequestStatus(cacheKey, status);
@@ -4477,6 +4484,7 @@ export async function getPullRequestStatus(
async function getPullRequestStatusUncached(
cwd: string,
forgeService: ForgeService,
head: string | null,
options?: CheckoutReadCacheOptions,
context?: CheckoutContext,
headSha?: string | null,
@@ -4486,18 +4494,16 @@ async function getPullRequestStatusUncached(
if (!context?.facts?.isGit) {
await requireGitRepo(cwd, context);
}
const head = context?.facts?.isGit
? context.facts.currentBranch
: await getCurrentBranch(cwd, context);
if (!head) {
return buildPullRequestStatusResult(null, "no_remote");
}
try {
const resolvedLookupTarget = await resolvePullRequestStatusLookupTarget(cwd, head, context);
const lookupTarget =
headSha && !resolvedLookupTarget.headSha
? { ...resolvedLookupTarget, headSha }
: resolvedLookupTarget;
const lookupTarget = {
...resolvedLookupTarget,
...(headSha && !resolvedLookupTarget.headSha ? { headSha } : {}),
...(head !== resolvedLookupTarget.headRef ? { currentBranch: head } : {}),
};
let status: CurrentPullRequestStatus | null;
if (options?.force) {
const reason = options.reason;
@@ -1406,6 +1406,32 @@ describe.skipIf(isPlatform("win32"))("worktree POSIX-only", () => {
rmSync(tempDir, { recursive: true, force: true });
});
it("keeps an otherwise unreachable detached commit after deleting the worktree", async () => {
const result = await createWorktreePrimitive({
cwd: repoDir,
worktreeSlug: "keep-commit",
source: { kind: "branch-off", baseBranch: "main", branchName: "feature/keep-commit" },
paseoHome,
});
execFileSync("git", ["checkout", "--detach"], { cwd: result.worktreePath });
writeFileSync(join(result.worktreePath, "file.txt"), "detached change\n");
execFileSync("git", ["add", "file.txt"], { cwd: result.worktreePath });
execFileSync("git", ["-c", "commit.gpgsign=false", "commit", "-m", "detached"], {
cwd: result.worktreePath,
});
const commit = execFileSync("git", ["rev-parse", "HEAD"], {
cwd: result.worktreePath,
encoding: "utf8",
}).trim();
await deletePaseoWorktree({ cwd: repoDir, worktreePath: result.worktreePath, paseoHome });
execFileSync("git", ["reflog", "expire", "--expire=now", "--all"], { cwd: repoDir });
execFileSync("git", ["gc", "--prune=now"], { cwd: repoDir });
expect(
execFileSync("git", ["cat-file", "-t", commit], { cwd: repoDir, encoding: "utf8" }).trim(),
).toBe("commit");
});
it("places, owns, lists, and deletes a worktree outside the legacy root", async () => {
// Sibling layout: <repo-parent>/wt-<slug>
@@ -3,6 +3,7 @@ import {
createWorktree as createWorktreePrimitive,
deriveWorktreeProjectHash,
deletePaseoWorktree,
readWorktreeHead,
isPaseoOwnedWorktreeCwd,
mapWorkspaceCwdToWorktree,
runWorktreeTeardownCommands,
@@ -302,6 +303,29 @@ describe("paseo worktree manager", () => {
expect(existsSync(created.worktreePath)).toBe(false);
});
it("does not read a parent repository's HEAD when the worktree has no .git", async () => {
const directory = join(repoDir, "missing-worktree");
mkdirSync(directory);
await expect(readWorktreeHead(directory)).resolves.toBeNull();
});
it("keeps a worktree when writing its retention ref fails", async () => {
const created = await createLegacyWorktreeForTest({
branchName: "ref-write-failure",
cwd: repoDir,
baseBranch: "main",
worktreeSlug: "ref-write-failure",
paseoHome,
});
mkdirSync(join(repoDir, ".git", "refs", "paseo"), { recursive: true });
writeFileSync(join(repoDir, ".git", "refs", "paseo", "kept-commits"), "blocked\n");
await expect(
deletePaseoWorktree({ cwd: repoDir, worktreePath: created.worktreePath, paseoHome }),
).rejects.toThrow();
expect(existsSync(created.worktreePath)).toBe(true);
});
it("deletes a worktree when Git reports its source through native and long path spellings", async () => {
const created = await createLegacyWorktreeForTest({
branchName: "identity-delete",
+69 -6
View File
@@ -188,6 +188,7 @@ export type WorktreeSource =
| { kind: "branch-off"; baseBranch: string; branchName: string }
| { kind: "checkout-branch"; branchName: string }
| { kind: "restore"; branchName: string; baseRef: string | null }
| { kind: "restore-commit"; commit: string; baseRef: string }
| { kind: "restore-from-base"; baseRef: string; branchName: string }
| {
kind: "checkout-change-request";
@@ -1153,6 +1154,32 @@ async function assertWorktreeBelongsToRepo(cwd: string, worktreePath: string): P
}
}
export async function readWorktreeHead(worktreePath: string): Promise<string | null> {
if (!(await pathExists(join(worktreePath, ".git")))) return null;
try {
const { stdout } = await runGitCommand(["rev-parse", "--verify", "HEAD^{commit}"], {
cwd: worktreePath,
});
return stdout.trim();
} catch {
return null;
}
}
export async function readWorktreeHeadReference(worktreePath: string): Promise<string | null> {
if (!(await pathExists(join(worktreePath, ".git")))) return null;
try {
const result = await runGitCommand(["symbolic-ref", "--quiet", "HEAD"], {
cwd: worktreePath,
acceptExitCodes: [0, 1],
});
if (result.exitCode === 0) return result.stdout.trim();
return readWorktreeHead(worktreePath);
} catch {
return null;
}
}
export async function deletePaseoWorktree({
cwd,
worktreePath,
@@ -1208,6 +1235,12 @@ export async function deletePaseoWorktree({
teardownCwd,
});
}
const commit = await readWorktreeHead(resolvedWorktree);
if (commit) {
await runGitCommand(["update-ref", `refs/paseo/kept-commits/${commit}`, commit], {
cwd: resolvedWorktree,
});
}
}
if (cwd) {
@@ -1361,14 +1394,22 @@ export async function resolveDefaultWorktreePath(
/**
* Create a git worktree with proper naming conventions
*/
export const createWorktree = async ({
export function createWorktree(
options: CreateWorktreeOptions & { source: Exclude<WorktreeSource, { kind: "restore-commit" }> },
): Promise<CreatedWorktree>;
export function createWorktree(
options: CreateWorktreeOptions,
): Promise<Omit<CreatedWorktree, "branchName"> & { branchName: string | null }>;
export async function createWorktree({
cwd,
source,
worktreeSlug,
paseoHome,
worktreesRoot,
worktreePath: explicitWorktreePath,
}: CreateWorktreeOptions): Promise<CreatedWorktree> => {
}: CreateWorktreeOptions): Promise<
Omit<CreatedWorktree, "branchName"> & { branchName: string | null }
> {
const branchesBefore =
source.kind === "checkout-branch" ||
source.kind === "checkout-change-request" ||
@@ -1394,14 +1435,14 @@ export const createWorktree = async ({
});
worktreePath = await normalizePathForOwnership(worktreePath);
if (sourcePlan.pushRemote) {
if (sourcePlan.pushRemote && sourcePlan.branchName) {
await configureWorktreePushRemote({
cwd,
branchName: sourcePlan.branchName,
remote: sourcePlan.pushRemote,
});
}
if (sourcePlan.trackingRemote) {
if (sourcePlan.trackingRemote && sourcePlan.branchName) {
await configureWorktreeTrackingRemote({
cwd,
branchName: sourcePlan.branchName,
@@ -1434,7 +1475,7 @@ export const createWorktree = async ({
}
throw error;
}
};
}
interface ResolveWorktreeSourcePlanOptions {
cwd: string;
@@ -1443,7 +1484,7 @@ interface ResolveWorktreeSourcePlanOptions {
}
interface WorktreeSourcePlan {
branchName: string;
branchName: string | null;
// Display name and exact ref are two different facts. The name cannot round-trip to a
// commit — "main" resolves local-first even when the worktree was cut from a fork's
// upstream — so comparisons and actions read the ref and the UI reads the name.
@@ -1492,6 +1533,26 @@ async function resolveRestoredWorktreeSourcePlan(
};
}
async function resolveRestoredCommitSourcePlan(
cwd: string,
source: Extract<WorktreeSource, { kind: "restore-commit" }>,
): Promise<WorktreeSourcePlan> {
let exactBase: string | undefined;
if (isQualifiedRef(source.baseRef)) {
try {
exactBase = await resolveBaseBranchForWorktree(cwd, source.baseRef);
} catch {
// Restore the saved commit even when its comparison ref no longer exists.
}
}
return {
branchName: null,
metadataBaseRefName: normalizeRequiredBaseBranch(source.baseRef),
...(exactBase ? { metadataBaseRef: exactBase } : {}),
addArguments: ["--detach", source.commit],
};
}
async function resolveRestoredWorktreeFromBasePlan(
cwd: string,
source: Extract<WorktreeSource, { kind: "restore-from-base" }>,
@@ -1544,6 +1605,8 @@ async function resolveWorktreeSourcePlan({
return resolveBranchOffWorktreeSourcePlan(cwd, source, desiredSlug);
case "restore":
return resolveRestoredWorktreeSourcePlan(cwd, source);
case "restore-commit":
return resolveRestoredCommitSourcePlan(cwd, source);
case "restore-from-base":
return resolveRestoredWorktreeFromBasePlan(cwd, source);
case "checkout-branch": {