Compare commits

..
Author SHA1 Message Date
paseo-bot[bot] b0e8724383 fix(opencode): keep history loads read-only and save the new session id at once
Only an interactive resume replaces a lost OpenCode session, so opening an
archived agent's history no longer creates a native session. A replaced
session reports persistenceUpdatedOnResume, so the agent manager stores
the new id when it registers the session, not after the next prompt.
2026-11-17 07:32:24 +00:00
paseo-bot[bot] b4ae32d77e fix(opencode): continue in a new session when the saved one is gone
Resuming an OpenCode agent reused the saved session id without checking
that OpenCode still had it. When the session was gone, every prompt failed
with NotFoundError "Session not found" and the agent never recovered.

Resume now asks OpenCode for the session first. When OpenCode reports it
missing, the agent starts a new native session on the same server, so the
next prompt runs and the new session id is persisted.
2026-11-17 07:20:32 +00:00
94 changed files with 538 additions and 2290 deletions
-8
View File
@@ -121,14 +121,6 @@ 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
+2 -4
View File
@@ -99,10 +99,8 @@ 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. 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
HEAD, then the most recently updated terminal request. A reused branch can show
its previous request until a new one opens. Auto-archive separately requires an
observed open-to-merged transition and a fresh exact match between checkout HEAD
and the PR head, along with the existing workspace safety checks.
-2
View File
@@ -7,7 +7,6 @@ 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";
@@ -147,7 +146,6 @@ 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 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:");
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();
expect(downloaded.suggestedFilename()).toBe(fileName);
const savedFile = testInfo.outputPath(fileName);
await downloaded.saveAs(savedFile);
@@ -479,45 +479,6 @@ 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,16 +362,6 @@ 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,10 +361,6 @@ 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",
@@ -393,7 +389,10 @@ 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.", { exact: true }),
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 },
),
).toBeVisible();
await captureBranchlessRestoreStep(page, "01-restore-workspace.png");
@@ -410,13 +409,17 @@ test.describe("Worktree restore", () => {
cwd: backingWorktree.workspaceDirectory,
encoding: "utf8",
}).trim();
expect(restoredHead).toBe(originalHead);
const defaultHead = execFileSync("git", ["rev-parse", "main"], {
cwd: tempRepo.path,
encoding: "utf8",
}).trim();
expect(restoredHead).toBe(defaultHead);
expect(
execFileSync("git", ["branch", "--show-current"], {
cwd: backingWorktree.workspaceDirectory,
encoding: "utf8",
}).trim(),
).toBe("");
).toMatch(/^restored\//);
});
test("restore failure stays visible and permits a successful retry", async ({ page }) => {
@@ -97,15 +97,18 @@ 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.getByTestId("import-session-list").evaluate((list, advance) => {
list.scrollTop = advance ? list.scrollTop + list.clientHeight * 0.8 : 0;
list.dispatchEvent(new Event("scroll"));
}, forward);
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);
}
async search(query: string) {
await this.page.getByTestId("import-session-search").fill(query);
@@ -117,18 +120,11 @@ 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() {
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.page.getByTestId("import-session-load-more").click();
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,14 +198,6 @@ 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 });
}
@@ -362,12 +354,14 @@ 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 first = await readContentObservation(page);
const observation = page.getByLabel("Content observation", { exact: true });
await expect(observation).not.toHaveText("");
const first = (await observation.textContent())!;
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 readContentObservation(page);
const second = (await observation.textContent())!;
expect(second).not.toBe(first);
await workspace.client.renameProject(workspace.projectId, "Observer control");
await expect(page.getByText("Observed updates: 1", { exact: true })).toBeVisible();
@@ -379,7 +373,7 @@ export async function withButtonShowcase(
await page.keyboard.press("Escape");
await press(page, "Header status");
await expectDetails(page);
const recovered = await readContentObservation(page);
const recovered = (await observation.textContent())!;
expect([first, second]).not.toContain(recovered);
await showcase.setTitle("Healthy app after button failure");
await expect(page.getByTestId("workspace-header-title")).toHaveText(
@@ -693,7 +687,9 @@ export async function withButtonShowcase(
page,
page.getByRole("button", { name: "Close deployment details", exact: true }),
);
const owner = await readContentObservation(page);
const observation = page.getByLabel("Content observation", { exact: true });
await expect(observation).not.toHaveText("");
const owner = (await observation.textContent())!;
await showcase.disable();
await expect.poll(() => released.has(owner)).toBe(true);
await expect(
@@ -15,18 +15,8 @@ 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>;
}
@@ -73,13 +63,11 @@ 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 () => {};
}
`;
@@ -1,2 +0,0 @@
/android/.cxx/
/android/build/
@@ -1,23 +0,0 @@
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'
}
@@ -1,86 +0,0 @@
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
}
@@ -1,43 +0,0 @@
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
},
)
}
}
@@ -1,35 +0,0 @@
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;
@@ -1,29 +0,0 @@
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",
);
});
});
@@ -1,6 +0,0 @@
{
"platforms": ["android"],
"android": {
"modules": []
}
}
@@ -1,5 +0,0 @@
{
"name": "paseo-display-metrics",
"version": "0.1.0",
"private": true
}
@@ -17,11 +17,6 @@ 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,44 +1172,6 @@ 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 { useMutation, useQueries, useQueryClient, type QueryClient } from "@tanstack/react-query";
import { keepPreviousData, useMutation, useQueries, useQueryClient } from "@tanstack/react-query";
import { useTranslation } from "react-i18next";
import type {
DaemonClient,
@@ -40,7 +40,6 @@ import {
resolveDirectoryLabel,
nextPageLimit,
PER_PROVIDER_LIMIT,
previousPageLimit,
type ProviderErrorRow,
resolveImportTarget,
resolveProvidersToFetch,
@@ -101,12 +100,11 @@ 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: () => RecentSessionsResponse | undefined;
placeholderData: typeof keepPreviousData;
queryFn: () => Promise<RecentSessionsResponse>;
}
function buildSessionsQueriesConfig(args: {
queryClient: QueryClient;
providersToFetch: AgentProvider[] | null;
visible: boolean;
client: RecentProviderSessionsClient | null;
@@ -115,24 +113,14 @@ function buildSessionsQueriesConfig(args: {
limit: number;
hostDisconnectedMessage?: string;
}): SessionsQueryConfig[] {
const { queryClient, providersToFetch, visible, client, cwd, query, limit } = args;
const { hostDisconnectedMessage } = args;
const { providersToFetch, visible, client, cwd, query, limit, 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,
// 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 }),
),
placeholderData: keepPreviousData,
queryFn: async () => {
if (!client) {
throw new Error(hostDisconnectedMessage ?? i18n.t("workspace.terminal.hostDisconnected"));
@@ -534,7 +522,6 @@ export function ImportSessionSheet({
const queriesConfig = useMemo(
() =>
buildSessionsQueriesConfig({
queryClient,
providersToFetch,
visible,
client,
@@ -543,7 +530,7 @@ export function ImportSessionSheet({
limit: pageLimit,
hostDisconnectedMessage: t("workspace.terminal.hostDisconnected"),
}),
[queryClient, providersToFetch, visible, client, scopeCwd, query, pageLimit, t],
[providersToFetch, visible, client, scopeCwd, query, pageLimit, t],
);
const queries = useQueries({ queries: queriesConfig });
+10 -1
View File
@@ -1,4 +1,7 @@
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";
@@ -8,11 +11,17 @@ 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}>
<Component {...props} />
<PluginClientStateProvider source={stateSource}>
<Component {...props} />
</PluginClientStateProvider>
</PluginInstallationProvider>
</SurfaceErrorBoundary>
);
+2 -2
View File
@@ -484,7 +484,8 @@ export const ar: TranslationResources = {
archivedTitle: "مساحة العمل مؤرشفة",
restoreDescription:
"استعد {{workspaceName}} للعودة إلى وكلائها. ستستخدم شجرة العمل الفرع {{branch}}.",
restoreWithoutBranchDescription: "استعد {{workspaceName}} للعودة إلى وكلائها.",
restoreWithoutBranchDescription:
"استعد {{workspaceName}} للعودة إلى وكلائها. سيبدأ فرع جديد من الفرع الأساسي المحفوظ أو الفرع الافتراضي للمستودع.",
unarchiveDescription: "{{workspaceName}} مؤرشفة. ألغِ أرشفتها لفتحها مجددًا.",
restoreAction: "استعادة",
unarchiveAction: "إلغاء الأرشفة",
@@ -2016,7 +2017,6 @@ export const ar: TranslationResources = {
hostUnavailable: "مضيف التنزيل غير متاح.",
cancelled: "تم إلغاء التنزيل.",
failed: "فشل تنزيل الملف.",
httpFailed: "فشل تنزيل الملف (HTTP {{status}}).",
shareFile: "مشاركة الملف",
shareFileNamed: "مشاركة{{fileName}}",
},
+2 -2
View File
@@ -483,7 +483,8 @@ 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.",
restoreWithoutBranchDescription:
"Restore {{workspaceName}} to return to its agents. A new branch will start from the saved base or the repository default.",
unarchiveDescription: "{{workspaceName}} is archived. Unarchive it to open it again.",
restoreAction: "Restore",
unarchiveAction: "Unarchive",
@@ -2044,7 +2045,6 @@ 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,7 +489,8 @@ 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.",
restoreWithoutBranchDescription:
"Restaura {{workspaceName}} para volver a sus agentes. Se creará una rama nueva desde la base guardada o la rama predeterminada del repositorio.",
unarchiveDescription:
"{{workspaceName}} está archivado. Desarchívalo para volver a abrirlo.",
restoreAction: "Restaurar",
@@ -2065,7 +2066,6 @@ 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,7 +489,8 @@ 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.",
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.",
unarchiveDescription: "{{workspaceName}} est archivé. Désarchivez-le pour le rouvrir.",
restoreAction: "Restaurer",
unarchiveAction: "Désarchiver",
@@ -2064,7 +2065,6 @@ 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,7 +489,8 @@ export const ja: TranslationResources = {
archivedTitle: "ワークスペースはアーカイブ済みです",
restoreDescription:
"{{workspaceName}} を復元してエージェントに戻ります。worktree ではブランチ {{branch}} を使用します。",
restoreWithoutBranchDescription: "{{workspaceName}} を復元してエージェントに戻ります。",
restoreWithoutBranchDescription:
"{{workspaceName}} を復元してエージェントに戻ります。保存されたベース、またはリポジトリのデフォルトブランチから新しいブランチを作成します。",
unarchiveDescription:
"{{workspaceName}} はアーカイブされています。再度開くにはアーカイブを解除してください。",
restoreAction: "復元",
@@ -2037,7 +2038,6 @@ export const ja: TranslationResources = {
hostUnavailable: "ダウンロードホストが利用できません。",
cancelled: "ダウンロードがキャンセルされました。",
failed: "ファイルのダウンロードに失敗しました。",
httpFailed: "ファイルのダウンロードに失敗しました (HTTP {{status}}).",
shareFile: "ファイルを共有",
shareFileNamed: "{{fileName}}を共有",
},
+2 -2
View File
@@ -485,7 +485,8 @@ export const ko: TranslationResources = {
archivedTitle: "워크스페이스가 보관되었습니다",
restoreDescription:
"{{workspaceName}}를 복원하여 에이전트로 돌아갑니다. 워크트리는 {{branch}} 브랜치를 사용합니다.",
restoreWithoutBranchDescription: "{{workspaceName}}를 복원하여 에이전트로 돌아갑니다.",
restoreWithoutBranchDescription:
"{{workspaceName}}를 복원하여 에이전트로 돌아갑니다. 저장된 기반 브랜치 또는 저장소 기본 브랜치에서 새 브랜치를 만듭니다.",
unarchiveDescription: "{{workspaceName}}가 보관되었습니다. 다시 열려면 보관을 취소하세요.",
restoreAction: "복원",
unarchiveAction: "보관 취소",
@@ -2027,7 +2028,6 @@ export const ko: TranslationResources = {
hostUnavailable: "다운로드 호스트를 사용할 수 없습니다.",
cancelled: "다운로드가 취소되었습니다.",
failed: "파일을 다운로드하지 못했습니다.",
httpFailed: "파일을 다운로드하지 못했습니다 (HTTP {{status}}).",
shareFile: "파일 공유",
shareFileNamed: "{{fileName}} 공유",
},
+2 -2
View File
@@ -488,7 +488,8 @@ 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.",
restoreWithoutBranchDescription:
"Restaure {{workspaceName}} para voltar aos seus agentes. Uma nova branch partirá da base salva ou da branch padrão do repositório.",
unarchiveDescription:
"{{workspaceName}} está arquivado. Desarquive-o para abri-lo novamente.",
restoreAction: "Restaurar",
@@ -2050,7 +2051,6 @@ 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}}",
},
+1 -2
View File
@@ -489,7 +489,7 @@ export const ru: TranslationResources = {
restoreDescription:
"Восстановите «{{workspaceName}}», чтобы вернуться к его агентам. Worktree будет использовать ветку {{branch}}.",
restoreWithoutBranchDescription:
"Восстановите «{{workspaceName}}», чтобы вернуться к его агентам.",
"Восстановите «{{workspaceName}}», чтобы вернуться к его агентам. Новая ветка будет создана от сохранённой базовой или ветки репозитория по умолчанию.",
unarchiveDescription:
"Рабочее пространство «{{workspaceName}}» находится в архиве. Разархивируйте его, чтобы снова открыть.",
restoreAction: "Восстановить",
@@ -2051,7 +2051,6 @@ export const ru: TranslationResources = {
hostUnavailable: "Хост загрузки недоступен.",
cancelled: "Загрузка отменена.",
failed: "Не удалось загрузить файл.",
httpFailed: "Не удалось загрузить файл (HTTP {{status}}).",
shareFile: "Поделиться файлом",
shareFileNamed: "Поделиться {{fileName}}",
},
+2 -2
View File
@@ -484,7 +484,8 @@ export const zhCN: TranslationResources = {
archivedTitle: "Workspace 已归档",
restoreDescription:
"恢复 {{workspaceName}} 以返回其中的代理。worktree 将使用分支 {{branch}}。",
restoreWithoutBranchDescription: "恢复 {{workspaceName}} 以返回其中的代理。",
restoreWithoutBranchDescription:
"恢复 {{workspaceName}} 以返回其中的代理。新分支将从保存的基准分支或仓库默认分支创建。",
unarchiveDescription: "{{workspaceName}} 已归档。取消归档以重新打开。",
restoreAction: "恢复",
unarchiveAction: "取消归档",
@@ -1993,7 +1994,6 @@ 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, useWorkspace, useWorkspaces } from "@getpaseo/plugin/client";
import { usePaseo, useRpc } 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,11 +8,7 @@ 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({
@@ -93,53 +89,3 @@ 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,42 +2,29 @@ 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, { useMemo, type ReactNode } from "react";
import { createPluginClientStateSource } from "./client-state/source";
import React, { type ReactNode } from "react";
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,
* 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.
*/
/** Every plugin surface renders under its installation: one query cache, one Paseo client, RPCs. */
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)}>
<PluginClientStateProvider source={state}>{children}</PluginClientStateProvider>
{children}
</PluginComposersProvider>
</PluginTranslationProvider>
</PluginRpcProvider>
+3 -2
View File
@@ -1,3 +1,4 @@
import { PluginClientStateProvider } from "@getpaseo/plugin/client/host";
import type { ReactNode } from "react";
import { View } from "react-native";
import { StyleSheet } from "react-native-unistyles";
@@ -29,8 +30,8 @@ export function PluginEnvironmentProvider({
}: PluginEnvironmentProviderProps) {
return (
<ToastApiProvider api={environment.toast}>
<PluginInstallationProvider plugin={environment.installation} state={environment.state}>
{children}
<PluginInstallationProvider plugin={environment.installation}>
<PluginClientStateProvider source={environment.state}>{children}</PluginClientStateProvider>
</PluginInstallationProvider>
</ToastApiProvider>
);
+6 -1
View File
@@ -1,3 +1,4 @@
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";
@@ -7,6 +8,7 @@ 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";
@@ -57,6 +59,7 @@ 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 />;
@@ -79,7 +82,9 @@ function PluginTimelineItemBody({
return (
<SurfaceErrorBoundary installation={plugin} resetKey={item.data} Surface={Component}>
<PluginInstallationProvider plugin={plugin}>
<Component {...props} />
<PluginClientStateProvider source={stateSource}>
<Component {...props} />
</PluginClientStateProvider>
</PluginInstallationProvider>
</SurfaceErrorBoundary>
);
@@ -5,6 +5,7 @@ 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";
@@ -19,6 +20,7 @@ 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";
@@ -65,6 +67,7 @@ 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) {
@@ -120,7 +123,9 @@ function PluginPanelBody({ theme }: { theme: PluginTheme }) {
Surface={Surface}
key={`${serverId}/${target.pluginId}/${target.panelId}/${target.context}`}
>
<PluginInstallationProvider plugin={plugin}>{panel}</PluginInstallationProvider>
<PluginInstallationProvider plugin={plugin}>
<PluginClientStateProvider source={stateSource}>{panel}</PluginClientStateProvider>
</PluginInstallationProvider>
</SurfaceErrorBoundary>
);
}
+1 -48
View File
@@ -2739,52 +2739,6 @@ 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));
@@ -2909,8 +2863,7 @@ describe("HostRuntimeStore", () => {
await registryLoaded;
expect(store.isHostRegistryLoaded()).toBe(true);
// Publishing the restored hosts, the registry turning ready, and the registry loading.
expect(hostListNotifications).toBe(3);
expect(hostListNotifications).toBe(2);
} finally {
if (previousOverride === undefined) {
delete process.env.EXPO_PUBLIC_LOCAL_DAEMON;
+3 -1
View File
@@ -1816,9 +1816,11 @@ 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.setHostsAndSync(profiles);
this.syncHosts(profiles);
for (const profile of profiles) {
void this.directorySyncByServer
.get(profile.serverId)
@@ -2003,8 +2003,9 @@ function WorkspaceScreenContent({
const agent =
useSessionStore.getState().sessions[normalizedServerId]?.agents?.get(agentId) ?? null;
let closePolicy = resolveCloseAgentTabPolicy(agent);
const isRunning = agent?.status === "running";
if (closePolicy.kind === "archive-on-close" && closePolicy.confirmArchive) {
if (isRunning && closePolicy.kind === "archive-on-close") {
const confirmed = await confirmDialog({
title: t("workspace.tabs.confirmations.archiveRunningAgentTitle"),
message: t("workspace.tabs.confirmations.archiveRunningAgentMessage"),
@@ -90,7 +90,6 @@ 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> {
@@ -109,7 +108,6 @@ 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;
@@ -205,57 +203,6 @@ 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");
+34 -39
View File
@@ -4,6 +4,7 @@ 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";
@@ -58,7 +59,6 @@ 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,7 +86,6 @@ export const useDownloadStore = create<DownloadState>()((set, get) => ({
requestFileDownloadToken,
readFile,
saveFile = saveDownloadedBytes,
fetchFile = fetch,
}) => {
const id = generateDownloadId();
const download: Download = {
@@ -145,11 +144,14 @@ export const useDownloadStore = create<DownloadState>()((set, get) => ({
throw new Error(i18n.t("downloads.hostUnavailable"));
}
const downloadUrl = buildDownloadUrl(downloadTarget.baseUrl, tokenResponse.token);
const downloadUrl = buildDownloadUrl(
downloadTarget.baseUrl,
tokenResponse.token,
isWeb ? downloadTarget.authCredentials : null,
);
if (isWeb) {
const file = await fetchDownload(fetchFile, downloadUrl);
saveBrowserFile(file, resolvedFileName);
triggerBrowserDownload(downloadUrl, resolvedFileName);
get().completeDownload(id);
return;
}
@@ -196,6 +198,11 @@ 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);
}
},
@@ -276,6 +283,7 @@ function findMostRecentDownloadId(downloads: Map<string, Download>): string | nu
interface DownloadTarget {
baseUrl: string | null;
authHeader: string | null;
authCredentials: { username: string; password: string } | null;
}
/**
@@ -298,7 +306,7 @@ function resolveDaemonDownloadTarget(
buildDaemonWebSocketUrl(connection.endpoint, { useTls: connection.useTls ?? false }),
);
} catch {
return { baseUrl: null, authHeader: null };
return { baseUrl: null, authHeader: null, authCredentials: null };
}
if (parsed.protocol === "ws:") {
@@ -324,41 +332,23 @@ function resolveDaemonDownloadTarget(
? `Basic ${btoa(`${authCredentials.username}:${authCredentials.password}`)}`
: null;
return { baseUrl, authHeader };
return { baseUrl, authHeader, authCredentials };
}
function buildDownloadUrl(baseUrl: string, token: string): string {
function buildDownloadUrl(
baseUrl: string,
token: string,
authCredentials: { username: string; password: string } | null,
): 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.
@@ -371,7 +361,12 @@ async function saveDownloadedBytes({
if (isWeb) {
const buffer = new ArrayBuffer(bytes.byteLength);
new Uint8Array(buffer).set(bytes);
saveBrowserFile(new Blob([buffer], { type: mimeType ?? "application/octet-stream" }), fileName);
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);
return null;
}
// Resolve and write in one tick so two downloads of the same name cannot pick the same path.
@@ -395,12 +390,14 @@ async function shareSavedFile(
}
}
function saveBrowserFile(file: Blob, fileName: string) {
function triggerBrowserDownload(url: string, 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;
@@ -408,8 +405,6 @@ function saveBrowserFile(file: Blob, 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,7 +79,6 @@ export interface Agent {
provider: AgentProvider;
status: AgentLifecycleStatus;
backgroundWork?: { count: number };
runningProviderSubagents?: { count: number };
turn: TurnLiveness;
createdAt: Date;
updatedAt: Date;
@@ -1,48 +1,21 @@
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 an idle root agent without asking", () => {
expect(resolveCloseAgentTabPolicy(rootAgent())).toEqual({
it("archives root agents when their tab closes", () => {
expect(resolveCloseAgentTabPolicy({ parentAgentId: null })).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(rootAgent({ parentAgentId: "parent-agent", status: "running" })),
).toEqual({ kind: "layout-only" });
expect(resolveCloseAgentTabPolicy({ parentAgentId: "parent-agent" })).toEqual({
kind: "layout-only",
});
});
it("preserves the existing archive fallback when the agent is missing", () => {
expect(resolveCloseAgentTabPolicy(null)).toEqual({
kind: "archive-on-close",
confirmArchive: false,
});
expect(resolveCloseAgentTabPolicy(null)).toEqual({ kind: "archive-on-close" });
expect(resolveCloseAgentTabPolicy(undefined)).toEqual({ kind: "archive-on-close" });
});
});
+3 -20
View File
@@ -1,30 +1,13 @@
import type { Agent } from "@/stores/session-store";
export type CloseAgentTabPolicy =
| { kind: "archive-on-close"; confirmArchive: boolean }
| { kind: "layout-only" };
type CloseTabAgent = Pick<
Agent,
"parentAgentId" | "status" | "backgroundWork" | "runningProviderSubagents"
>;
export type CloseAgentTabPolicy = { kind: "archive-on-close" } | { kind: "layout-only" };
export function resolveCloseAgentTabPolicy(
agent: CloseTabAgent | null | undefined,
agent: Pick<Agent, "parentAgentId"> | null | undefined,
): CloseAgentTabPolicy {
if (agent?.parentAgentId) {
return { kind: "layout-only" };
}
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
);
return { kind: "archive-on-close" };
}
@@ -72,7 +72,6 @@ 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,
@@ -117,7 +116,6 @@ export function normalizeAgentSnapshot(snapshot: AgentSnapshotPayload, serverId:
provider: snapshot.provider,
status: snapshot.status,
backgroundWork: snapshot.backgroundWork,
runningProviderSubagents: snapshot.runningProviderSubagents,
turn,
createdAt,
updatedAt,
@@ -1,4 +1,3 @@
import path from "node:path";
import { describe, expect, it } from "vitest";
import { buildWorkspaceSource } from "./create.js";
@@ -9,49 +8,6 @@ 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({
+2 -20
View File
@@ -1,10 +1,6 @@
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";
@@ -125,26 +121,12 @@ 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, callerPath ?? process.cwd());
return buildLocalWorkspaceSource(options, options.path ?? process.cwd());
}
if (options.isolation === "worktree") {
const sourcePath = callerPath ?? (options.project ? undefined : process.cwd());
const sourcePath = options.path ?? (options.project ? undefined : process.cwd());
return buildWorktreeWorkspaceSource(options, sourcePath);
}
throw new Error(`Unsupported workspace isolation: ${String(options.isolation)}`);
+4 -32
View File
@@ -5,25 +5,18 @@ import { fileURLToPath } from "node:url";
import { _electron as electron, expect } from "playwright/test";
const root = await mkdtemp(path.join(tmpdir(), "paseo-window-startup-"));
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),
);
const modulePath = fileURLToPath(new URL("../dist/window/show-when-ready.js", import.meta.url));
async function launchDesktopWindow() {
async function launchWindowWithoutHiddenFrames() {
const main = path.join(root, "main.cjs");
await writeFile(
main,
`const { app, BrowserWindow } = require("electron");
const { showWindowWhenReady } = require(${JSON.stringify(showWhenReadyPath)});
const { reloadWhenRendererExits } = require(${JSON.stringify(rendererRecoveryPath)});
const { showWindowWhenReady } = require(${JSON.stringify(modulePath)});
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();
});`,
@@ -44,32 +37,11 @@ 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 launchDesktopWindow();
desktop = await launchWindowWithoutHiddenFrames();
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,7 +46,6 @@ 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";
@@ -735,7 +734,6 @@ async function createWindow(
}
setupDarwinCompositorWatchdog(mainWindow);
reloadWhenRendererExits(mainWindow);
setupWindowResizeEvents(mainWindow);
if (windowStateStore) {
setupWindowStatePersistence(mainWindow, windowStateStore);
@@ -1,86 +0,0 @@
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);
});
});
@@ -1,56 +0,0 @@
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,8 +921,6 @@ 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,101 +3473,6 @@ 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,12 +1456,6 @@ 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 });
@@ -2138,7 +2132,7 @@ export class AgentManager {
!this.foregroundMutationTails.has(agent.id) &&
!this.replacementMutationTails.has(agent.id) &&
!this.sessionEventTails.has(agent.id) &&
this.providerSubagents.countRunning(agent.id) === 0
!this.providerSubagents.list(agent.id).some((child) => child.status === "running")
);
}
@@ -5138,8 +5132,7 @@ export class AgentManager {
if (
eventTurnId &&
isTurnTerminalEvent(event) &&
this.runs.hasFinalizedTurn(agent, eventTurnId) &&
this.runs.getTurnId(agent.id) !== eventTurnId
this.runs.hasFinalizedTurn(agent, eventTurnId)
) {
return false;
}
@@ -266,7 +266,6 @@ 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(),
@@ -6197,36 +6196,6 @@ 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,14 +137,6 @@ 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,8 +123,7 @@ test.each(["mode", "model", "commands"] as const)(
try {
await session.startTurn("Run the foreground command");
await running.promise;
// Ultracode is launched with the query, so the change waits for a restart.
expect(await session.setThinkingOption?.("ultracode")).toMatchObject({
expect(await session.setThinkingOption?.("medium")).toMatchObject({
message: "Thinking level applies next turn",
});
if (control === "mode") await session.setMode("acceptEdits");
@@ -150,7 +149,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", "xhigh"]);
expect(efforts).toEqual(["low", "medium"]);
} finally {
await session.close();
}
@@ -44,7 +44,6 @@ 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 })),
@@ -383,84 +382,6 @@ 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,60 +1544,6 @@ 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,10 +2637,7 @@ class ClaudeAgentSession implements AgentSession {
return { status: "unavailable" };
}
const activeTurnId = this.activeForegroundTurnId ?? this.autonomousTurn?.id;
// 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) {
if (this.compacting || activeTurnId !== options.expectedTurnId) {
return { status: "unavailable" };
}
@@ -2862,7 +2859,6 @@ class ClaudeAgentSession implements AgentSession {
? thinkingOptionId
: null;
const previousThinkingOptionId = this.config.thinkingOptionId;
if (!normalizedThinkingOptionId || normalizedThinkingOptionId === "default") {
this.config.thinkingOptionId = undefined;
} else if (isClaudeThinkingOption(normalizedThinkingOptionId)) {
@@ -2871,35 +2867,12 @@ class ClaudeAgentSession implements AgentSession {
} else {
throw new Error(`Unknown thinking option: ${normalizedThinkingOptionId}`);
}
if (!(await this.applyEffortToRunningQuery(previousThinkingOptionId))) {
this.queryRestartNeeded = true;
}
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.
@@ -0,0 +1,59 @@
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,6 +814,79 @@ 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,6 +546,15 @@ 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;
@@ -1457,8 +1466,18 @@ 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
@@ -1522,7 +1541,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;
@@ -1547,6 +1566,32 @@ 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);
@@ -3380,6 +3425,8 @@ 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, ManagedAgent } from "../agent-manager.js";
import type { AgentManager } 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,13 +2099,6 @@ 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",
{
@@ -2123,7 +2116,11 @@ function createToolCatalog(
async ({ agentId }) => {
const snapshot = agentManager.getAgent(agentId);
if (snapshot) {
const structuredSnapshot = await projectLiveAgent(snapshot);
const structuredSnapshot = await serializeSnapshotWithMetadata(
agentStorage,
snapshot,
childLogger,
);
return {
content: [],
structuredContent: ensureValidJson({
@@ -2191,7 +2188,8 @@ function createToolCatalog(
manager: agentManager,
storage: agentStorage,
workspaces: options.workspaceRegistry,
projectLive: projectLiveAgent,
projectLive: (snapshot) =>
serializeSnapshotWithMetadata(agentStorage, snapshot, childLogger),
projectStored: (record) =>
buildStoredAgentPayload(
record,
+2 -2
View File
@@ -128,7 +128,7 @@ export async function fanOutReconciledWorkspaceUpdates(input: {
);
}
import { VoiceAssistantWebSocketServer, isDaemonOriginAllowed } from "./websocket-server.js";
import { VoiceAssistantWebSocketServer } 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 && isDaemonOriginAllowed(origin, req.headers.host ?? null, allowedOrigins)) {
if (origin && (allowedOrigins.has("*") || allowedOrigins.has(origin))) {
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");
@@ -1,122 +0,0 @@
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, type IncomingMessage } from "node:http";
import { get } from "node:http";
import { tmpdir } from "os";
import path from "path";
import { createDaemonTestContext, type DaemonTestContext } from "../test-utils/index.js";
@@ -69,29 +69,6 @@ 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 () => {
@@ -1,45 +0,0 @@
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 });
}, 60_000);
}, 20_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" | "restore-commit" }
{ kind: "restore" | "restore-from-base" }
>;
export interface ResolveWorktreeCreationIntentInput {
@@ -412,7 +412,6 @@ function createSessionForTest(options: SessionForTestOptions = {}): Session {
listAgents: vi.fn(() => []),
listProviderSubagentActivity: vi.fn(() => []),
getAgentBackgroundWorkSummary: () => undefined,
getRunningProviderSubagentSummary: () => undefined,
subscribe: vi.fn(() => () => {}),
...options.agentManager,
}),
+20 -8
View File
@@ -2258,11 +2258,8 @@ export class Session {
private forwardProviderSubagent(event: ProviderSubagentManagerEvent): void {
const parentAgentId =
event.type === "upsert" ? event.subagent.parentAgentId : event.parentAgentId;
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);
if (this.agentManager.getAgent(parentAgentId)?.internal) return;
this.emitProviderSubagentWorkspaceUpdate(event);
this.forwardProviderSubagentUpdate(event);
}
@@ -2278,6 +2275,24 @@ 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"],
@@ -2293,9 +2308,6 @@ 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,15 +335,11 @@ async function createBaseRecoveryFixture(baseBranch: string | null) {
await registry.update(record.workspaceId, (value) => ({ ...value, archivedAt: null }));
},
});
async function archiveAndRemove(legacy = false) {
if (legacy) {
await registry.archive(workspace.workspaceId, new Date().toISOString());
} else {
await archivePersistedWorkspaceRecord({
workspaceId: workspace.workspaceId,
workspaceRegistry: registry,
});
}
async function archiveAndRemove() {
await archivePersistedWorkspaceRecord({
workspaceId: workspace.workspaceId,
workspaceRegistry: registry,
});
await deletePaseoWorktree({ cwd: repoDir, worktreePath: workspace.cwd, paseoHome });
expect(existsSync(workspace.cwd)).toBe(false);
}
@@ -361,134 +357,6 @@ 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" });
@@ -500,7 +368,7 @@ test("restores a branchless workspace from its recorded base so work can continu
...workspace,
branch: null,
}));
await fixture.archiveAndRemove(true);
await fixture.archiveAndRemove();
await expect(fixture.service.inspect(fixture.workspace.workspaceId)).resolves.toMatchObject({
kind: "recoverable",
@@ -534,7 +402,7 @@ test("restores a branchless workspace from the repository default when its base
...workspace,
branch: null,
}));
await fixture.archiveAndRemove(true);
await fixture.archiveAndRemove();
await expect(fixture.service.restore(fixture.workspace.workspaceId)).resolves.toEqual({
workspaceId: fixture.workspace.workspaceId,
@@ -550,44 +418,6 @@ 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,27 +151,13 @@ export function createWorkspaceRecoveryService(deps: {
workspace: PersistedWorkspaceRecord,
sourceRepoRoot: string,
): Promise<void> {
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),
};
}
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),
};
try {
await runGitCommand(["worktree", "prune"], { cwd: sourceRepoRoot, timeout: 30_000 });
@@ -265,29 +251,16 @@ 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: checkout.kind === "branch" ? checkout.branch : null,
branch: input.workspace.branch,
};
if (input.action === "restore") {
return {
@@ -589,27 +589,6 @@ 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 = {
@@ -853,11 +832,6 @@ 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,7 +39,6 @@ export function asAgentManager(stub: {
getRetiredInternalAgent: () => null,
effectiveOptionsFor: (_provider: string, own?: Record<string, unknown>) => own ?? {},
getAgentBackgroundWorkSummary: () => undefined,
getRunningProviderSubagentSummary: () => undefined,
...stub,
});
}
+3 -17
View File
@@ -998,7 +998,9 @@ export class VoiceAssistantWebSocketServer {
callback(false, 403, "Host not allowed");
return;
}
if (!origin || isDaemonOriginAllowed(origin, requestHost, allowedOrigins)) {
const sameOrigin = isWebSocketSameOrigin(origin, requestHost);
if (!origin || allowedOrigins.has("*") || allowedOrigins.has(origin) || sameOrigin) {
callback(true);
} else {
this.incrementRuntimeCounter("originRejected");
@@ -3265,22 +3267,6 @@ 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,10 +118,6 @@ class InMemoryAgentManager {
return undefined;
}
getRunningProviderSubagentSummary() {
return undefined;
}
fetchTimeline(_agentId: string, options?: AgentTimelineFetchOptions) {
return this.timeline.fetch("agent-1", options);
}
@@ -8,7 +8,6 @@ import type { WorkspaceGitService } from "./workspace-git-service.js";
import type { ForgeService } from "../services/forge-service.js";
import {
deletePaseoWorktree,
readWorktreeHeadReference,
isPaseoOwnedWorktreeCwd,
runWorktreeTeardownCommands,
WorktreeTeardownError,
@@ -708,15 +707,7 @@ export async function archivePersistedWorkspaceRecord(input: {
}
const archivedAt = input.archivedAt ?? new Date().toISOString();
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 } : {}),
});
await input.workspaceRegistry.archive(input.workspaceId, archivedAt, input.context);
return existingWorkspace;
}
@@ -151,40 +151,6 @@ 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,7 +604,6 @@ interface WorkspaceGitAuxiliaryReadCacheEntry<T> {
interface WorkspaceForgePrStatusPollTarget {
headRef: string;
currentBranch?: string;
headSha?: string;
headRepositoryOwner?: string;
}
@@ -3151,7 +3150,11 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
if (resolution.service.retainCurrentPullRequestStatusPoll) {
target.forgePrStatusPollSubscription = resolution.service.retainCurrentPullRequestStatusPoll({
cwd: target.cwd,
...pollTarget,
headRef: pollTarget.headRef,
...(pollTarget.headSha ? { headSha: pollTarget.headSha } : {}),
...(pollTarget.headRepositoryOwner
? { headRepositoryOwner: pollTarget.headRepositoryOwner }
: {}),
onStatus: (status) => {
if (!this.isActiveObservedWorkspaceTarget(target)) {
return;
@@ -3223,7 +3226,11 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
try {
const status = await service.getCurrentPullRequestStatus({
cwd: target.cwd,
...pollTarget,
headRef: pollTarget.headRef,
...(pollTarget.headSha ? { headSha: pollTarget.headSha } : {}),
...(pollTarget.headRepositoryOwner
? { headRepositoryOwner: pollTarget.headRepositoryOwner }
: {}),
reason: "self-heal-forge-pr-status",
});
if (!closed && this.isActiveObservedWorkspaceTarget(target)) {
@@ -3278,14 +3285,13 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
target.latestFacts?.isGit && target.latestFacts.currentBranch === git.currentBranch
? target.latestFacts.pullRequestLookupTarget
: null;
if (lookupTarget) {
return git.currentBranch === lookupTarget.headRef
? lookupTarget
: { ...lookupTarget, currentBranch: git.currentBranch };
}
if (target.latestFacts?.isGit && target.latestFacts.paseoWorktree.isPaseoOwnedWorktree) {
return null;
return lookupTarget;
}
if (lookupTarget) {
return lookupTarget;
}
return { headRef: git.currentBranch };
}
@@ -4418,7 +4424,6 @@ function buildWorkspaceForgePrStatusPollKey({
forge,
remoteUrl,
target.headRef,
target.currentBranch ?? null,
target.headSha ?? null,
target.headRepositoryOwner ?? null,
]);
@@ -72,7 +72,6 @@ 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
@@ -127,7 +126,6 @@ export interface WorkspaceMutationContext {
export interface WorkspaceArchiveContext {
autoArchivedChangeRequestUrl?: string;
head?: string;
}
export interface ProjectMutation {
@@ -588,7 +586,6 @@ export class FileBackedWorkspaceRegistry
...existing,
updatedAt: archivedAt,
archivedAt,
head: context?.head,
...(context?.autoArchivedChangeRequestUrl
? { autoArchivedChangeRequestUrl: context.autoArchivedChangeRequestUrl }
: {}),
+14 -23
View File
@@ -436,22 +436,6 @@ 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[]>;
@@ -491,7 +475,12 @@ export interface ForgeService {
*/
getReferenceRepository?(options: { cwd: string } & ForgeReadOptions): Promise<string | null>;
getCurrentPullRequestStatus(
options: CurrentPullRequestLookup & ForgeReadOptions,
options: {
cwd: string;
headRef: string;
headSha?: string;
headRepositoryOwner?: string;
} & ForgeReadOptions,
): Promise<CurrentPullRequestStatus | null>;
getPullRequestTimeline(options: GetPullRequestTimelineOptions): Promise<PullRequestTimeline>;
getCheckDetails(options: GetCheckDetailsOptions): Promise<CheckDetails>;
@@ -527,12 +516,14 @@ export interface ForgeService {
* cannot change the outcome and is pure overhead.
*/
authProbeCanThrow?: boolean;
retainCurrentPullRequestStatusPoll?(
options: CurrentPullRequestLookup & {
onStatus?: (status: CurrentPullRequestStatus | null) => void;
onError?: (error: unknown) => void;
},
): { unsubscribe: () => void };
retainCurrentPullRequestStatusPoll?(options: {
cwd: string;
headRef: string;
headSha?: string;
headRepositoryOwner?: string;
onStatus?: (status: CurrentPullRequestStatus | null) => void;
onError?: (error: unknown) => void;
}): { unsubscribe: () => void };
invalidate(options: { cwd: string }): void;
dispose?(): void;
}
@@ -2036,33 +2036,6 @@ 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({
+23 -28
View File
@@ -26,13 +26,11 @@ import {
compareTimelineItems,
createUnavailableSearchResult,
normalizeForgeSearchKinds,
isOnDefaultBranch,
parseOptionalTime,
} from "./forge-service.js";
import type {
CheckDetails,
CreatePullRequestOptions,
CurrentPullRequestLookup,
CurrentPullRequestStatus,
DisablePullRequestAutoMergeOptions,
EnablePullRequestAutoMergeOptions,
@@ -253,7 +251,6 @@ 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();
@@ -1588,9 +1585,11 @@ export function createGiteaService(options: CreateGiteaServiceOptions = {}): For
return { items, truncated: true };
}
async function loadCurrentPullRequestStatus(
input: CurrentPullRequestLookup,
): Promise<CurrentPullRequestStatus | null> {
async function loadCurrentPullRequestStatus(input: {
cwd: string;
headRef: string;
headSha?: string;
}): Promise<CurrentPullRequestStatus | null> {
const match = await findCurrentPullRequestForHeadRef(input);
if (!match) {
return null;
@@ -1614,19 +1613,11 @@ export function createGiteaService(options: CreateGiteaServiceOptions = {}): For
return identity ? { owner: identity.owner, name: identity.name } : 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> {
async function findCurrentPullRequestForHeadRef(input: {
cwd: string;
headRef: string;
headSha?: string;
}): Promise<GiteaPrListItem | null> {
const repoIdentity = await resolveCurrentRepoIdentity(input.cwd);
const expectedHeadOwner = repoIdentity?.owner ?? null;
const openMatch = await findOpenPullRequestForHeadRef(input, expectedHeadOwner);
@@ -1637,7 +1628,9 @@ 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 = repositoryApiPath(repoIdentity);
const repoPath = repoIdentity
? `repos/${encodeURIComponent(repoIdentity.owner)}/${encodeURIComponent(repoIdentity.name)}`
: "repos/{owner}/{repo}";
const recentItems = await runJsonArray(
[
"api",
@@ -1673,12 +1666,6 @@ 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;
}
@@ -2033,12 +2020,20 @@ export function createGiteaService(options: CreateGiteaServiceOptions = {}): For
if (!repo) {
return null;
}
const repository = await readRepository(input.cwd, repositoryApiPath(repo));
const repository = await runJson(
["api", `repos/${encodeURIComponent(repo.owner)}/${encodeURIComponent(repo.name)}`],
{ cwd: input.cwd },
GiteaRepositoryApiSchema,
);
return repository.parent?.full_name ?? null;
},
getCurrentPullRequestStatus(input): Promise<CurrentPullRequestStatus | null> {
return loadCurrentPullRequestStatus(input);
return loadCurrentPullRequestStatus({
cwd: input.cwd,
headRef: input.headRef,
headSha: input.headSha,
});
},
async getPullRequest(input: GetPullRequestOptions): Promise<PullRequestSummary> {
@@ -552,7 +552,7 @@ describe("ForgeService", () => {
"view",
"fork-owner/repo",
"--json",
"owner,name,parent,defaultBranchRef",
"owner,name,parent",
]);
});
@@ -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,defaultBranchRef"],
args: ["repo", "view", "--json", "owner,name,parent"],
});
expect(runner.calls[1]?.cwd).toBe("/repo");
expect(runner.calls[1]?.args.slice(0, 3)).toEqual(["api", "graphql", "-f"]);
@@ -1111,56 +1111,6 @@ 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([
@@ -1540,19 +1490,13 @@ describe("ForgeService", () => {
batchPollStatusJson({
t0: batchPollRepositoryJson([], { isFork: true, parent }),
}),
batchPollStatusJson({
t0: batchPollRepositoryJson([forkPr], { defaultBranchRef: { name: "feat-a" } }),
origin0: { defaultBranchRef: { name: "main" } },
}),
batchPollStatusJson({ t0: batchPollRepositoryJson([forkPr]) }),
batchPollStatusJson({
t0: batchPollChecksAliasJson([
{ __typename: "StatusContext", context: "ci", state: "SUCCESS" },
]),
}),
batchPollStatusJson({
t0: batchPollRepositoryJson([forkPr], { defaultBranchRef: { name: "feat-a" } }),
origin0: { defaultBranchRef: { name: "main" } },
}),
batchPollStatusJson({ t0: batchPollRepositoryJson([forkPr]) }),
]);
const service = createGitHubService({
ttlMs: 0,
@@ -1580,9 +1524,6 @@ 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" }),
]);
@@ -3337,30 +3278,6 @@ 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([
@@ -3688,7 +3605,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,defaultBranchRef"],
["repo", "view", "--json", "owner,name,parent"],
["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],
@@ -3920,7 +3837,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,defaultBranchRef"],
["repo", "view", "--json", "owner,name,parent"],
["api", `repos/parentOwner/parentRepo/pulls?${FORK_PR_QUERY}`],
["pr", "view", "42", "--repo", "parentOwner/parentRepo", "--json", CURRENT_PR_STATUS_FIELDS],
[
@@ -3985,7 +3902,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,defaultBranchRef"],
["repo", "view", "--json", "owner,name,parent"],
[
"pr",
"list",
@@ -4833,12 +4750,7 @@ 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,defaultBranchRef",
]);
expect(runner.calls[0]?.args).toEqual(["repo", "view", "--json", "owner,name,parent"]);
expect(runner.calls[1]?.args).toEqual([
"api",
"-X",
@@ -4912,7 +4824,7 @@ describe("ForgeService", () => {
expect(readFakeGitHubCliLog(fixture.logPath)).toEqual(
expect.arrayContaining([
"auth status --hostname github.acme.internal|",
"repo view --json owner,name,parent,defaultBranchRef|github.acme.internal",
"repo view --json owner,name,parent|github.acme.internal",
"api -X POST repos/acme/repo/pulls -f title=Add thing -f head=feature -f base=main|github.acme.internal",
]),
);
@@ -4957,7 +4869,7 @@ describe("ForgeService", () => {
).toHaveLength(2);
expect(log).toEqual(
expect.arrayContaining([
"repo view --json owner,name,parent,defaultBranchRef|github.acme.internal",
"repo view --json owner,name,parent|github.acme.internal",
"api -X POST repos/acme/repo/pulls -f title=Add thing -f head=feature -f base=main|github.acme.internal",
]),
);
+60 -106
View File
@@ -27,7 +27,6 @@ import {
computeChecksStatus,
compareTimelineItems,
createUnavailableSearchResult,
isOnDefaultBranch,
normalizeForgeSearchKinds,
parseOptionalTime,
} from "./forge-service.js";
@@ -35,7 +34,6 @@ import type {
CheckAnnotation,
CheckDetails,
CheckFailedJob,
CurrentPullRequestLookup,
CurrentPullRequestStatus,
DisablePullRequestAutoMergeOptions,
EnablePullRequestAutoMergeOptions,
@@ -448,11 +446,7 @@ const PullRequestTimelineGraphqlSchema = z.object({
.optional(),
});
const GitHubDefaultBranchSchema = z.object({
defaultBranchRef: z.object({ name: z.string() }).nullish(),
});
const GitHubRepoViewSchema = GitHubDefaultBranchSchema.extend({
const GitHubRepoViewSchema = z.object({
owner: z
.object({
login: z.string().optional(),
@@ -663,7 +657,7 @@ const BatchPollPrNodeSchema = z.object({
isInMergeQueue: z.boolean().optional().catch(false),
});
const BatchPollRepositorySchema = GitHubDefaultBranchSchema.extend({
const BatchPollRepositorySchema = z.object({
owner: z.object({ login: z.string().optional() }).nullable().optional().catch(null),
isFork: z.boolean().optional().catch(false),
parent: z
@@ -785,7 +779,9 @@ function graphqlString(value: string): string {
return JSON.stringify(value);
}
function buildBatchPullRequestStatusQuery(entries: GitHubBatchPollEntry[]): string {
function buildBatchPullRequestStatusQuery(
entries: Array<{ owner: string; name: string; headRef: string }>,
): string {
const aliases = entries.map(
(entry, index) => ` ${batchAlias(index)}: repository(owner: ${graphqlString(
entry.owner,
@@ -793,9 +789,6 @@ function buildBatchPullRequestStatusQuery(entries: GitHubBatchPollEntry[]): stri
owner {
login
}
defaultBranchRef {
name
}
isFork
parent {
owner {
@@ -809,7 +802,7 @@ function buildBatchPullRequestStatusQuery(entries: GitHubBatchPollEntry[]): stri
rebaseMergeAllowed
viewerDefaultMergeMethod
pullRequests(headRefName: ${graphqlString(
entry.target.headRef,
entry.headRef,
)}, first: ${BATCH_PR_CANDIDATE_LIMIT}, orderBy: {field: CREATED_AT, direction: DESC}) {
nodes {
...PaseoPollPullRequest
@@ -817,26 +810,13 @@ function buildBatchPullRequestStatusQuery(entries: GitHubBatchPollEntry[]): stri
}
}`,
);
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, ...originAliases].join("\n")}
${aliases.join("\n")}
}\n${BATCH_PR_STATUS_FRAGMENT}`;
}
@@ -1096,7 +1076,11 @@ interface InFlightCacheEntry {
force: boolean;
}
interface GitHubPollTarget extends CurrentPullRequestLookup {
interface GitHubPollTarget {
cwd: string;
headRef: string;
headSha?: string;
headRepositoryOwner?: string;
retainCount: number;
/** Absolute due time on the shared poll grid; null while a poll is in flight. */
nextDueAt: number | null;
@@ -1380,7 +1364,12 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G
});
}
function getPollTargetKey(target: CurrentPullRequestLookup): string {
function getPollTargetKey(target: {
cwd: string;
headRef: string;
headSha?: string;
headRepositoryOwner?: string;
}): string {
return buildCacheKey({
cwd: target.cwd,
method: "getCurrentPullRequestStatus",
@@ -1388,17 +1377,18 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G
headRef: target.headRef,
headSha: target.headSha,
headRepositoryOwner: target.headRepositoryOwner,
currentBranch: target.currentBranch,
},
});
}
function updatePollTargetAfterSuccess(
update: CurrentPullRequestLookup & {
status: CurrentPullRequestStatus | null;
notify: boolean;
},
): void {
function updatePollTargetAfterSuccess(update: {
cwd: string;
headRef: string;
headSha?: string;
headRepositoryOwner?: string;
status: CurrentPullRequestStatus | null;
notify: boolean;
}): void {
const target = pollTargets.get(getPollTargetKey(update));
if (!target) {
return;
@@ -1648,7 +1638,13 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G
if (!firstEntry) {
return;
}
const query = buildBatchPullRequestStatusQuery(addressedEntries);
const query = buildBatchPullRequestStatusQuery(
addressedEntries.map((entry) => ({
owner: entry.owner,
name: entry.name,
headRef: entry.target.headRef,
})),
);
const args = ["api", "graphql", "-f", `query=${query}`];
const response = await loadGitHubPollBatchResponse({
entries: addressedEntries,
@@ -1764,18 +1760,6 @@ 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}`
@@ -1802,22 +1786,6 @@ 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
@@ -1995,14 +1963,25 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G
);
status = built ? { ...built, forgeSpecific: { forge: "github", ...facts } } : null;
}
const cacheKey = getPollTargetKey(entry.target);
const cacheKey = buildCacheKey({
cwd: entry.target.cwd,
method: "getCurrentPullRequestStatus",
args: {
headRef: entry.target.headRef,
headSha: entry.target.headSha,
headRepositoryOwner: entry.target.headRepositoryOwner,
},
});
// 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({
...entry.target,
cwd: entry.target.cwd,
headRef: entry.target.headRef,
headSha: entry.target.headSha,
headRepositoryOwner: entry.target.headRepositoryOwner,
status: existing.value as CurrentPullRequestStatus | null,
notify: true,
});
@@ -2012,7 +1991,10 @@ 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({
...entry.target,
cwd: entry.target.cwd,
headRef: entry.target.headRef,
headSha: entry.target.headSha,
headRepositoryOwner: entry.target.headRepositoryOwner,
status,
notify: true,
});
@@ -2025,7 +2007,6 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G
headRef: target.headRef,
headSha: target.headSha,
headRepositoryOwner: target.headRepositoryOwner,
currentBranch: target.currentBranch,
reason: "self-heal-github",
});
} catch (error) {
@@ -2192,17 +2173,14 @@ 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 loadCurrentPullRequestView({
const status = await resolveCurrentPullRequestView({
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 });
@@ -2213,7 +2191,6 @@ 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",
});
@@ -2626,7 +2603,6 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G
headRef: input.headRef,
headSha: input.headSha,
headRepositoryOwner: input.headRepositoryOwner,
currentBranch: input.currentBranch,
retainCount: 0,
nextDueAt: null,
pollCycleStartedAt: null,
@@ -3008,35 +2984,13 @@ function isGitHubRateLimitError(error: unknown): boolean {
);
}
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> {
async function resolveCurrentPullRequestView(options: {
cwd: string;
headRef: string;
headSha?: string;
headRepositoryOwner?: string;
run: (args: string[], options: GitHubCommandRunnerOptions) => Promise<string>;
}): Promise<CurrentPullRequestStatus | null> {
const viewCandidate = await tryCurrentPullRequestView(options);
const viewMatch = viewCandidate
? pickPullRequestCandidate({
@@ -3053,7 +3007,7 @@ async function resolveCurrentPullRequestView(
let headRepositoryOwner = options.headRepositoryOwner;
if (!headRepositoryOwner) {
const repo = await options.readRepo();
const repo = await getGitHubRepoView(options);
const forkOwner = repo?.owner?.login;
const parentOwner = repo?.parent?.owner?.login;
const parentName = repo?.parent?.name;
@@ -3328,7 +3282,7 @@ async function readGitHubRepoView(
"view",
...(options.repo ? [options.repo] : []),
"--json",
"owner,name,parent,defaultBranchRef",
"owner,name,parent",
];
const stdout = await options.run(args, {
cwd: options.cwd,
@@ -389,26 +389,6 @@ 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,
+11 -23
View File
@@ -16,7 +16,6 @@ import {
compareTimelineItems,
createUnavailableSearchResult,
normalizeForgeSearchKinds,
isOnDefaultBranch,
parseOptionalTime,
} from "./forge-service.js";
import type {
@@ -253,7 +252,6 @@ 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()
@@ -1144,19 +1142,6 @@ 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();
@@ -1177,8 +1162,17 @@ export function createGitLabService(options: CreateGitLabServiceOptions = {}): F
},
async getReferenceRepository(input): Promise<string | null> {
const project = await readOriginProject(input.cwd);
return project?.forked_from_project?.path_with_namespace ?? 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;
},
async getCurrentPullRequestStatus(input): Promise<CurrentPullRequestStatus | null> {
@@ -1187,12 +1181,6 @@ 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,7 +13,6 @@ 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";
@@ -194,28 +193,6 @@ 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). */
@@ -259,7 +236,7 @@ export async function pruneTerminalWorkerRuntimes(
)
continue;
try {
await removeCopy(directory);
await rm(directory, { recursive: true, force: true });
result.removed.push(directory);
} catch (error) {
result.failed.push({
+2 -22
View File
@@ -178,7 +178,6 @@ function createPullRequestStatus(overrides?: Partial<CurrentPullRequestStatus>)
interface RequestedPullRequestTarget {
headRef: string;
currentBranch?: string;
headSha?: string;
headRepositoryOwner?: string;
}
@@ -195,7 +194,6 @@ 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 } : {}),
});
@@ -3462,7 +3460,7 @@ const x = 1;
{ paseoHome },
);
expect(requestedTargets).toEqual([{ ...factsTarget, currentBranch: "tender-parrot" }]);
expect(requestedTargets).toEqual([factsTarget]);
});
it("uses the tracked fork branch for PR worktree status lookup", async () => {
@@ -3492,11 +3490,7 @@ const x = 1;
const status = await getPullRequestStatus(repoDir, github);
expect(requestedTargets).toEqual([
expect.objectContaining({
headRef: "main",
currentBranch: "chethanuk/main",
headRepositoryOwner: "chethanuk",
}),
expect.objectContaining({ headRef: "main", headRepositoryOwner: "chethanuk" }),
]);
expect(status.status?.number).toBe(345);
expect(status.status?.headRefName).toBe("main");
@@ -3527,20 +3521,6 @@ 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"], {
+12 -18
View File
@@ -153,12 +153,8 @@ function createShortstatCache(ttlMs: number) {
});
}
function getPullRequestStatusCacheKey(
cwd: string,
currentBranch: string | null,
headSha: string | null,
): string {
return `${resolve(cwd)}\u0000${currentBranch ?? ""}\u0000${headSha ?? ""}`;
function getPullRequestStatusCacheKey(cwd: string, headSha: string | null): string {
return `${resolve(cwd)}\u0000${headSha ?? ""}`;
}
function rememberPullRequestStatus(cacheKey: string, status: PullRequestStatusResult): void {
@@ -4441,11 +4437,8 @@ export async function getPullRequestStatus(
options?: CheckoutReadCacheOptions,
context?: CheckoutContext,
): Promise<PullRequestStatusResult> {
const [headSha, head] = await Promise.all([
getCurrentHeadSha(cwd, context),
context?.facts?.isGit ? context.facts.currentBranch : getCurrentBranch(cwd, context),
]);
const cacheKey = getPullRequestStatusCacheKey(cwd, head, headSha);
const headSha = await getCurrentHeadSha(cwd, context);
const cacheKey = getPullRequestStatusCacheKey(cwd, headSha);
if (!options?.force) {
const cached = pullRequestStatusCache.get(cacheKey);
if (cached) {
@@ -4458,7 +4451,7 @@ export async function getPullRequestStatus(
}
}
const lookup = getPullRequestStatusUncached(cwd, forgeService, head, options, context, headSha)
const lookup = getPullRequestStatusUncached(cwd, forgeService, options, context, headSha)
.then((status) => {
pullRequestStatusCache.set(cacheKey, status);
rememberPullRequestStatus(cacheKey, status);
@@ -4484,7 +4477,6 @@ export async function getPullRequestStatus(
async function getPullRequestStatusUncached(
cwd: string,
forgeService: ForgeService,
head: string | null,
options?: CheckoutReadCacheOptions,
context?: CheckoutContext,
headSha?: string | null,
@@ -4494,16 +4486,18 @@ 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 = {
...resolvedLookupTarget,
...(headSha && !resolvedLookupTarget.headSha ? { headSha } : {}),
...(head !== resolvedLookupTarget.headRef ? { currentBranch: head } : {}),
};
const lookupTarget =
headSha && !resolvedLookupTarget.headSha
? { ...resolvedLookupTarget, headSha }
: resolvedLookupTarget;
let status: CurrentPullRequestStatus | null;
if (options?.force) {
const reason = options.reason;
@@ -1406,32 +1406,6 @@ 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,7 +3,6 @@ import {
createWorktree as createWorktreePrimitive,
deriveWorktreeProjectHash,
deletePaseoWorktree,
readWorktreeHead,
isPaseoOwnedWorktreeCwd,
mapWorkspaceCwdToWorktree,
runWorktreeTeardownCommands,
@@ -303,29 +302,6 @@ 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",
+6 -69
View File
@@ -188,7 +188,6 @@ 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";
@@ -1154,32 +1153,6 @@ 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,
@@ -1235,12 +1208,6 @@ 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) {
@@ -1394,22 +1361,14 @@ export async function resolveDefaultWorktreePath(
/**
* Create a git worktree with proper naming conventions
*/
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({
export const createWorktree = async ({
cwd,
source,
worktreeSlug,
paseoHome,
worktreesRoot,
worktreePath: explicitWorktreePath,
}: CreateWorktreeOptions): Promise<
Omit<CreatedWorktree, "branchName"> & { branchName: string | null }
> {
}: CreateWorktreeOptions): Promise<CreatedWorktree> => {
const branchesBefore =
source.kind === "checkout-branch" ||
source.kind === "checkout-change-request" ||
@@ -1435,14 +1394,14 @@ export async function createWorktree({
});
worktreePath = await normalizePathForOwnership(worktreePath);
if (sourcePlan.pushRemote && sourcePlan.branchName) {
if (sourcePlan.pushRemote) {
await configureWorktreePushRemote({
cwd,
branchName: sourcePlan.branchName,
remote: sourcePlan.pushRemote,
});
}
if (sourcePlan.trackingRemote && sourcePlan.branchName) {
if (sourcePlan.trackingRemote) {
await configureWorktreeTrackingRemote({
cwd,
branchName: sourcePlan.branchName,
@@ -1475,7 +1434,7 @@ export async function createWorktree({
}
throw error;
}
}
};
interface ResolveWorktreeSourcePlanOptions {
cwd: string;
@@ -1484,7 +1443,7 @@ interface ResolveWorktreeSourcePlanOptions {
}
interface WorktreeSourcePlan {
branchName: string | null;
branchName: string;
// 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.
@@ -1533,26 +1492,6 @@ 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" }>,
@@ -1605,8 +1544,6 @@ 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": {