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