mirror of
https://github.com/getpaseo/paseo.git
synced 2026-11-18 14:25:25 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e8f891d948 | ||
|
|
57a9142106 |
@@ -590,16 +590,6 @@ bookkeeping may scan opaque row sizes during a deferred write, never during host
|
||||
before a requested cache row can paint. The row store is not encrypted. A cached timeline can contain
|
||||
source code, prompts, and tool output; encrypted-at-rest storage is a separate security decision.
|
||||
|
||||
### Saved hosts
|
||||
|
||||
**AsyncStorage key:** `@paseo:daemon-registry`, an array of host profiles.
|
||||
|
||||
Every app build on a device shares this key, including an older build after a downgrade and a newer
|
||||
one that saves a connection kind this build doesn't know. The key holds every saved host and its
|
||||
password, so never remove it. Read each host and connection on its own, skip the ones this build
|
||||
can't read, and write them back on every save. A value that isn't a JSON array is copied to
|
||||
`@paseo:daemon-registry:unreadable` before the next save overwrites it.
|
||||
|
||||
### Draft Store
|
||||
|
||||
**AsyncStorage key:** `paseo-drafts` (version 2)
|
||||
|
||||
+6
-19
@@ -97,25 +97,12 @@ Register the adapter in `defaultForgeRegistry` with:
|
||||
- `matchesHost` from manifest `cloudHosts`
|
||||
- `probeHost` when self-hosted/Enterprise detection is supported
|
||||
|
||||
Current change-request lookup prefers an open request for the branch and repository.
|
||||
A closed or merged request belongs to a workspace only when its checkout commit
|
||||
is in the forge's PR/MR commit list. Commits inherited from the base do not count.
|
||||
Display and auto-archive share this rule, preserving squash-merged requests and
|
||||
requests updated remotely while rejecting a fresh workspace on their base commit.
|
||||
A rewritten or newly advanced checkout no longer matches the terminal request.
|
||||
|
||||
Commit membership stays in the server snapshot; clients receive the selected
|
||||
request without its commit list. Archive uses that same evidence after refreshing
|
||||
the workspace. It still requires an observed open-to-merged transition and the
|
||||
workspace safety checks; being behind alone does not block it.
|
||||
|
||||
Containment spawns no Git commands and fetches no Git objects. GitHub loads only terminal
|
||||
commit IDs in a separate batch under the same rate budget, newest page first,
|
||||
and remembers pages by PR head. Open requests need no membership read. GitLab,
|
||||
Gitea, and legacy GitHub cache successful terminal commit lists by request head;
|
||||
failed reads stay retryable and reject the lookup, preserving its previous snapshot. A failed
|
||||
GitHub commit batch does not block workspaces whose status is already complete.
|
||||
Missing membership evidence leaves the workspace active.
|
||||
Current change-request lookup matches the branch and repository for both open and
|
||||
terminal requests. Prefer an open request, then a terminal request at the local
|
||||
HEAD, then the most recently updated terminal request. A reused branch can show
|
||||
its previous request until a new one opens. Auto-archive separately requires an
|
||||
observed open-to-merged transition and a fresh exact match between checkout HEAD
|
||||
and the PR head, along with the existing workspace safety checks.
|
||||
|
||||
Keep checkout HEAD in adapter cache and poll identities so checkout changes
|
||||
refresh the facts used by archive eligibility.
|
||||
|
||||
@@ -2,16 +2,10 @@ import { copyPluginExample } from "../support/helpers/plugin-fixture";
|
||||
import { expect, test as base, type Page } from "../support/fixtures";
|
||||
import { gotoAppShell } from "../support/helpers/app";
|
||||
import { connectNewWorkspaceDaemonClient } from "../support/helpers/new-workspace";
|
||||
import { waitForSettledPosition } from "../support/helpers/sheet-layout";
|
||||
|
||||
async function openExample(page: Page, example: string) {
|
||||
await page.getByRole("button", { name: `Open ${example}`, exact: true }).click();
|
||||
const title = page.getByText(`Modal example: ${example}`, { exact: true });
|
||||
// A compact sheet holds below the viewport and then slides up, so a pointer placed before it
|
||||
// stops lands on whatever slides under it. The settle check starts once the slide has begun;
|
||||
// two equal reads during the hold would otherwise count as settled.
|
||||
await expect(title).toBeInViewport();
|
||||
await waitForSettledPosition(title);
|
||||
await expect(page.getByText(`Modal example: ${example}`, { exact: true })).toBeVisible();
|
||||
}
|
||||
|
||||
async function closeExample(page: Page) {
|
||||
|
||||
@@ -208,35 +208,6 @@ test.describe("Plugin sidebar items", () => {
|
||||
});
|
||||
});
|
||||
|
||||
test("a short desktop sidebar keeps workspaces usable while navigation scrolls", async ({
|
||||
page,
|
||||
}) => {
|
||||
await page.setViewportSize({ width: 1280, height: 480 });
|
||||
await gotoAppShell(page);
|
||||
await expect(botRow(page, "status")).toBeAttached();
|
||||
const workspace = visibleTestId(page, `sidebar-workspace-row-${getServerId()}:${workspaceId}`);
|
||||
await expect(workspace).toBeInViewport({ ratio: 1 });
|
||||
await expect(botRow(page, "status")).not.toBeInViewport();
|
||||
|
||||
await test.step("navigation stays within half the sidebar", async () => {
|
||||
const nav = await boxOf(visibleTestId(page, "sidebar-nav-scroll"));
|
||||
expect(nav.height).toBeLessThanOrEqual(480 / 2 + 1);
|
||||
});
|
||||
|
||||
await test.step("scrolling navigation reaches its last row without moving workspaces", async () => {
|
||||
const before = await boxOf(workspace);
|
||||
await visibleTestId(page, "sidebar-global-new-workspace").hover();
|
||||
await page.mouse.wheel(0, 800);
|
||||
await expect(botRow(page, "status")).toBeInViewport({ ratio: 1 });
|
||||
await expect(workspace).toBeInViewport({ ratio: 1 });
|
||||
expect((await boxOf(workspace)).y).toBe(before.y);
|
||||
await qaScreenshot(page, "desktop-short-sidebar-nav-scrolled");
|
||||
await botRow(page, "status").click();
|
||||
await expect(page.getByText("Bot status details", { exact: true })).toBeVisible();
|
||||
await page.getByRole("button", { name: "Close bot status", exact: true }).click();
|
||||
});
|
||||
});
|
||||
|
||||
test("a restored plugin screen waits for its catalog before rendering", async ({ page }) => {
|
||||
await page.setViewportSize(WIDE);
|
||||
await gotoWorkspace(page, workspaceId);
|
||||
|
||||
@@ -1,106 +0,0 @@
|
||||
import { expect, type Page } from "@playwright/test";
|
||||
import { test } from "../support/fixtures";
|
||||
import { gotoAppShell, openSettings } from "../support/helpers/app";
|
||||
import { renameHostFromSettings } from "../support/helpers/hosts";
|
||||
import { getServerId } from "../support/helpers/server-id";
|
||||
import { openHostSection, selectSettingsHost } from "../support/helpers/settings";
|
||||
|
||||
const REGISTRY_KEY = "@paseo:daemon-registry";
|
||||
const SEED_NONCE_KEY = "@paseo:e2e-seed-nonce";
|
||||
const DISABLE_DEFAULT_SEED_ONCE_KEY = "@paseo:e2e-disable-default-seed-once";
|
||||
|
||||
// What a build with a connection kind this one doesn't know leaves in the registry: an extra
|
||||
// connection on a host this build can reach, and a host reached only through it.
|
||||
const UNKNOWN_CONNECTION = { id: "future:garage", type: "futureKind", address: "garage" };
|
||||
const UNKNOWN_HOST = {
|
||||
serverId: "srv_e2e_unknown_connection_host",
|
||||
label: "Unknown connection host",
|
||||
connections: [{ id: "future:roof", type: "futureKind", address: "roof" }],
|
||||
preferredConnectionId: "future:roof",
|
||||
};
|
||||
const OFFLINE_HOST = {
|
||||
serverId: "srv_e2e_saved_offline_host",
|
||||
label: "Saved offline host",
|
||||
password: "e2e-fake-password",
|
||||
connections: [{ id: "direct:127.0.0.1:59999", type: "directTcp", endpoint: "127.0.0.1:59999" }],
|
||||
preferredConnectionId: "direct:127.0.0.1:59999",
|
||||
};
|
||||
|
||||
interface StoredHost {
|
||||
serverId: string;
|
||||
label?: string;
|
||||
password?: string;
|
||||
connections: unknown[];
|
||||
}
|
||||
|
||||
async function addUnreadableEntriesAndReload(page: Page): Promise<void> {
|
||||
await page.evaluate(
|
||||
({ keys, primaryServerId, unknownConnection, offlineHost, unknownHost }) => {
|
||||
const nonce = localStorage.getItem(keys.nonce);
|
||||
if (!nonce) {
|
||||
throw new Error("Expected the e2e seed nonce before overriding the host registry.");
|
||||
}
|
||||
const registry: StoredHost[] = JSON.parse(localStorage.getItem(keys.registry) ?? "[]");
|
||||
registry
|
||||
.find((host) => host.serverId === primaryServerId)
|
||||
?.connections.push(unknownConnection);
|
||||
registry.push(offlineHost, unknownHost);
|
||||
localStorage.setItem(keys.registry, JSON.stringify(registry));
|
||||
localStorage.setItem(keys.disableSeedOnce, nonce);
|
||||
},
|
||||
{
|
||||
keys: {
|
||||
registry: REGISTRY_KEY,
|
||||
nonce: SEED_NONCE_KEY,
|
||||
disableSeedOnce: DISABLE_DEFAULT_SEED_ONCE_KEY,
|
||||
},
|
||||
primaryServerId: getServerId(),
|
||||
unknownConnection: UNKNOWN_CONNECTION,
|
||||
offlineHost: OFFLINE_HOST,
|
||||
unknownHost: UNKNOWN_HOST,
|
||||
},
|
||||
);
|
||||
await page.reload();
|
||||
}
|
||||
|
||||
async function readStoredRegistry(page: Page): Promise<StoredHost[] | null> {
|
||||
return page.evaluate((key) => JSON.parse(localStorage.getItem(key) ?? "null"), REGISTRY_KEY);
|
||||
}
|
||||
|
||||
async function readStoredHost(page: Page, serverId: string): Promise<StoredHost | undefined> {
|
||||
return (await readStoredRegistry(page))?.find((host) => host.serverId === serverId);
|
||||
}
|
||||
|
||||
test("saved hosts survive a registry entry this build can't read, and saving keeps it", async ({
|
||||
page,
|
||||
}) => {
|
||||
await gotoAppShell(page);
|
||||
await addUnreadableEntriesAndReload(page);
|
||||
|
||||
await test.step("both readable hosts are listed", async () => {
|
||||
await page.getByTestId("sidebar-hosts-trigger").click();
|
||||
await expect(page.getByTestId(`sidebar-host-row-${getServerId()}`)).toBeVisible();
|
||||
await expect(page.getByTestId(`sidebar-host-row-${OFFLINE_HOST.serverId}`)).toBeVisible();
|
||||
await expect(page.getByTestId(`sidebar-host-row-${UNKNOWN_HOST.serverId}`)).toHaveCount(0);
|
||||
await page.keyboard.press("Escape");
|
||||
});
|
||||
|
||||
await test.step("renaming a host keeps its password and the entries it can't read", async () => {
|
||||
await openSettings(page);
|
||||
await selectSettingsHost(page, OFFLINE_HOST.serverId);
|
||||
await openHostSection(page, OFFLINE_HOST.serverId, "host");
|
||||
await renameHostFromSettings(page, "Renamed offline host");
|
||||
|
||||
await expect
|
||||
.poll(() => readStoredHost(page, OFFLINE_HOST.serverId))
|
||||
.toMatchObject({ label: "Renamed offline host", password: OFFLINE_HOST.password });
|
||||
const stored = await readStoredRegistry(page);
|
||||
expect(stored?.map((host) => host.serverId)).toEqual([
|
||||
getServerId(),
|
||||
OFFLINE_HOST.serverId,
|
||||
UNKNOWN_HOST.serverId,
|
||||
]);
|
||||
expect(stored?.[0]?.connections).toContainEqual(UNKNOWN_CONNECTION);
|
||||
expect(stored?.[2]).toEqual(UNKNOWN_HOST);
|
||||
});
|
||||
});
|
||||
@@ -33,8 +33,6 @@ import {
|
||||
expectNoHostPasswordControls,
|
||||
removeHostFromHostPage,
|
||||
addDirectHostFromSettings,
|
||||
expectAddHostFieldDrawnAsInput,
|
||||
selectHostConnectionType,
|
||||
expectHostOnlineWithoutError,
|
||||
expectIdleAgentRelease,
|
||||
editRestartRecoveryPrompt,
|
||||
@@ -309,24 +307,6 @@ async function closeAddHostAndChangeTheme(page: import("@playwright/test").Page)
|
||||
await page.keyboard.press("Control+Alt+t");
|
||||
}
|
||||
|
||||
test("Add host draws its text fields as bordered inputs", async ({ page }) => {
|
||||
await gotoAppShell(page);
|
||||
|
||||
await test.step("the pairing link field", async () => {
|
||||
await openSidebarAddHost(page);
|
||||
await selectHostConnectionType(page, "relay");
|
||||
await expectAddHostFieldDrawnAsInput(page, "pair-link-input");
|
||||
await page.getByTestId("pair-link-cancel").click();
|
||||
});
|
||||
|
||||
await test.step("the direct connection fields", async () => {
|
||||
await selectHostConnectionType(page, "direct");
|
||||
await expectAddHostFieldDrawnAsInput(page, "direct-host-input");
|
||||
await expectAddHostFieldDrawnAsInput(page, "direct-port-input");
|
||||
await expectAddHostFieldDrawnAsInput(page, "direct-password-input");
|
||||
});
|
||||
});
|
||||
|
||||
test("sidebar Add host completes without navigating", async ({ page }) => {
|
||||
await gotoAppShell(page);
|
||||
await expect(page).toHaveURL(/\/open-project$/);
|
||||
|
||||
@@ -110,7 +110,6 @@ test.describe("Sidebar items in Appearance settings", () => {
|
||||
|
||||
await test.step("the sidebar starts in the default order", async () => {
|
||||
await expectSidebarOrder(page, ["new-workspace", "history", "search", "schedules"]);
|
||||
await expect(page.locator('[data-testid="sidebar-nav-separator"]:visible')).toHaveCount(1);
|
||||
});
|
||||
|
||||
await test.step("the Sidebar section lists every item in the same order", async () => {
|
||||
@@ -196,9 +195,6 @@ test.describe("Sidebar items in Appearance settings", () => {
|
||||
await expectSidebarItemHidden(page, "history");
|
||||
await expectSidebarItemHidden(page, "search");
|
||||
await expectSidebarItemHidden(page, "schedules");
|
||||
// Nothing is left above the Workspaces section: no drag strip, no empty divider.
|
||||
await expect(page.locator('[data-testid="sidebar-nav-drag-strip"]:visible')).toHaveCount(0);
|
||||
await expect(page.locator('[data-testid="sidebar-nav-separator"]:visible')).toHaveCount(0);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -73,36 +73,35 @@ function labelRow(page: import("@playwright/test").Page, name: string) {
|
||||
return page.getByTestId(`workspace-label-picker-row-${name}`);
|
||||
}
|
||||
|
||||
async function box(locator: import("@playwright/test").Locator) {
|
||||
const measured = await locator.boundingBox();
|
||||
if (!measured) throw new Error("expected a visible element to measure");
|
||||
return measured;
|
||||
}
|
||||
|
||||
async function size(locator: import("@playwright/test").Locator) {
|
||||
const { width, height } = await settled(locator);
|
||||
await settled(locator);
|
||||
const { width, height } = await box(locator);
|
||||
return { width, height };
|
||||
}
|
||||
|
||||
/**
|
||||
* Waits until an element is on screen and stops moving, and returns where it settled.
|
||||
* Waits until an element stops moving.
|
||||
*
|
||||
* The flyout scales in and the sidebar behind it re-lays out as the filter changes, so a rail
|
||||
* measured mid-animation is not a rail — and a measurement built from two `boundingBox()` calls
|
||||
* would take its two halves from two different frames. A row that has not been laid out yet has
|
||||
* no box at all; that is not settled either, so the poll keeps waiting instead of failing.
|
||||
* would take its two halves from two different frames.
|
||||
*/
|
||||
async function settled(locator: import("@playwright/test").Locator) {
|
||||
const last: { box: Awaited<ReturnType<typeof locator.boundingBox>>; key: string | null } = {
|
||||
box: null,
|
||||
key: null,
|
||||
};
|
||||
let previous = "";
|
||||
await expect
|
||||
.poll(async () => {
|
||||
const current = await locator.boundingBox();
|
||||
const key = current ? JSON.stringify(current) : null;
|
||||
const stable = key !== null && key === last.key;
|
||||
last.box = current;
|
||||
last.key = key;
|
||||
const current = JSON.stringify(await box(locator));
|
||||
const stable = current === previous;
|
||||
previous = current;
|
||||
return stable;
|
||||
})
|
||||
.toBe(true);
|
||||
if (!last.box) throw new Error("a settled element has a box");
|
||||
return last.box;
|
||||
}
|
||||
|
||||
async function expectAssigned(
|
||||
|
||||
@@ -6,7 +6,7 @@ import {
|
||||
type ChildProcess,
|
||||
type SpawnOptions,
|
||||
} from "node:child_process";
|
||||
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
||||
import { mkdtemp, rm, writeFile } from "node:fs/promises";
|
||||
import net from "node:net";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
@@ -59,17 +59,7 @@ export async function getAvailableHostDaemonPort(): Promise<number> {
|
||||
return port;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves once this daemon answers on its port. An open TCP port is not
|
||||
* enough: the port is released before the daemon binds it, and whatever takes
|
||||
* it in between also accepts connections while the daemon exits with
|
||||
* EADDRINUSE. Only the daemon's own status reports its server id.
|
||||
*/
|
||||
async function waitForServer(
|
||||
port: number,
|
||||
child: ChildProcess,
|
||||
identity: { serverId: string; paseoHome: string },
|
||||
): Promise<void> {
|
||||
async function waitForServer(port: number, child: ChildProcess): Promise<void> {
|
||||
const deadline = Date.now() + 90_000;
|
||||
let lastError: unknown = null;
|
||||
|
||||
@@ -80,13 +70,22 @@ async function waitForServer(
|
||||
);
|
||||
}
|
||||
try {
|
||||
const serverId = await readServerId(port, identity.paseoHome);
|
||||
if (serverId === identity.serverId) return;
|
||||
lastError = new Error(`Port ${port} is served by ${serverId}, not ${identity.serverId}`);
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
const socket = net.connect(port, "127.0.0.1", () => {
|
||||
socket.end();
|
||||
resolve();
|
||||
});
|
||||
socket.setTimeout(1_000, () => {
|
||||
socket.destroy();
|
||||
reject(new Error(`Connection timed out to isolated daemon port ${port}`));
|
||||
});
|
||||
socket.on("error", reject);
|
||||
});
|
||||
return;
|
||||
} catch (error) {
|
||||
lastError = error;
|
||||
await new Promise((resolve) => setTimeout(resolve, 100));
|
||||
}
|
||||
await new Promise((resolve) => setTimeout(resolve, 100));
|
||||
}
|
||||
|
||||
throw new Error(
|
||||
@@ -96,25 +95,6 @@ async function waitForServer(
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the server id from the daemon's status route. The route needs a bearer
|
||||
* on a password-protected daemon; the daemon accepts the local credential it
|
||||
* writes into its home before listening, as the CLI does for local status.
|
||||
*/
|
||||
async function readServerId(port: number, paseoHome: string): Promise<string> {
|
||||
const localCredential = await readFile(path.join(paseoHome, "local-credential"), "utf8").then(
|
||||
(token) => token.trim(),
|
||||
() => null,
|
||||
);
|
||||
const response = await fetch(`http://127.0.0.1:${port}/api/status`, {
|
||||
headers: localCredential ? { authorization: `Bearer ${localCredential}` } : {},
|
||||
signal: AbortSignal.timeout(1_000),
|
||||
});
|
||||
if (!response.ok) throw new Error(`Status request to port ${port} returned ${response.status}`);
|
||||
const status = (await response.json()) as { serverId?: unknown };
|
||||
return String(status.serverId);
|
||||
}
|
||||
|
||||
function withMutableRelay(
|
||||
config: NonNullable<IsolatedHostDaemonOptions["config"]>,
|
||||
relay: NonNullable<IsolatedHostDaemonOptions["mutableRelay"]>,
|
||||
@@ -241,7 +221,7 @@ export async function startIsolatedHostDaemon(
|
||||
});
|
||||
|
||||
try {
|
||||
await waitForServer(port, spawned, { serverId, paseoHome });
|
||||
await waitForServer(port, spawned);
|
||||
return spawned;
|
||||
} catch (error) {
|
||||
throw new Error(
|
||||
|
||||
@@ -223,14 +223,6 @@ export async function addDirectHostFromSettings(
|
||||
await expect(page.getByTestId("add-host-modal")).toHaveCount(0, { timeout: 30_000 });
|
||||
}
|
||||
|
||||
export async function expectAddHostFieldDrawnAsInput(page: Page, testId: string): Promise<void> {
|
||||
const field = page.getByTestId(testId);
|
||||
await expect(field).toBeVisible();
|
||||
await expect(field).toHaveCSS("border-top-width", "1px");
|
||||
await expect(field).not.toHaveCSS("padding-left", "0px");
|
||||
await expect(field).not.toHaveCSS("background-color", "rgba(0, 0, 0, 0)");
|
||||
}
|
||||
|
||||
export async function toggleHostAdvanced(page: Page): Promise<void> {
|
||||
await page.getByTestId("direct-host-advanced-toggle").click();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
apply plugin: 'com.android.library'
|
||||
|
||||
group = 'sh.paseo.pressfeedback'
|
||||
version = '0.1.0'
|
||||
|
||||
def expoModulesCorePlugin = new File(project(":expo-modules-core").projectDir.absolutePath, "ExpoModulesCorePlugin.gradle")
|
||||
apply from: expoModulesCorePlugin
|
||||
applyKotlinExpoModulesCorePlugin()
|
||||
useCoreDependencies()
|
||||
useExpoPublishing()
|
||||
useDefaultAndroidSdkVersions()
|
||||
|
||||
android {
|
||||
namespace "sh.paseo.pressfeedback"
|
||||
defaultConfig {
|
||||
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android" />
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
package sh.paseo.pressfeedback
|
||||
|
||||
import android.content.Context
|
||||
import android.graphics.Canvas
|
||||
import android.graphics.Color
|
||||
import android.graphics.Paint
|
||||
import expo.modules.kotlin.AppContext
|
||||
import expo.modules.kotlin.modules.Module
|
||||
import expo.modules.kotlin.modules.ModuleDefinition
|
||||
import expo.modules.kotlin.types.ColorCompat
|
||||
import expo.modules.kotlin.views.ExpoView
|
||||
|
||||
class PaseoPressFeedbackModule : Module() {
|
||||
override fun definition() = ModuleDefinition {
|
||||
Name("PaseoPressFeedback")
|
||||
View(PaseoPressFeedbackView::class) {
|
||||
Prop("tint") { view: PaseoPressFeedbackView, color: Color -> view.paint.color = ColorCompat.toArgb(color) }
|
||||
Prop("radius") { view: PaseoPressFeedbackView, radius: Double -> view.radius = radius.toFloat() * view.resources.displayMetrics.density }
|
||||
Prop("resetKey") { view: PaseoPressFeedbackView, key: String -> view.reset(key) }
|
||||
AsyncFunction("acknowledge") { view: PaseoPressFeedbackView -> view.acknowledge() }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class PaseoPressFeedbackView(context: Context, appContext: AppContext) : ExpoView(context, appContext) {
|
||||
val paint = Paint(Paint.ANTI_ALIAS_FLAG)
|
||||
var radius = 0f
|
||||
private var acknowledged = false
|
||||
private var resetKey = ""
|
||||
init { setWillNotDraw(false); importantForAccessibility = IMPORTANT_FOR_ACCESSIBILITY_NO }
|
||||
fun acknowledge() { acknowledged = true; invalidate() }
|
||||
fun reset(key: String) {
|
||||
if (key != resetKey) { resetKey = key; acknowledged = false; invalidate() }
|
||||
}
|
||||
override fun onDraw(canvas: Canvas) {
|
||||
super.onDraw(canvas)
|
||||
if (acknowledged) canvas.drawRoundRect(0f, 0f, width.toFloat(), height.toFloat(), radius, radius, paint)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"platforms": ["android", "ios"],
|
||||
"android": { "modules": ["sh.paseo.pressfeedback.PaseoPressFeedbackModule"] },
|
||||
"ios": { "modules": ["PaseoPressFeedbackModule"] }
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export { useWorkspaceRowPress } from "./src/ui";
|
||||
@@ -0,0 +1,22 @@
|
||||
Pod::Spec.new do |s|
|
||||
s.name = 'PaseoPressFeedback'
|
||||
s.version = '0.1.0'
|
||||
s.summary = 'Native accepted press feedback for Paseo'
|
||||
s.description = 'Paints accepted press feedback independently of React commits'
|
||||
s.license = 'Apache-2.0'
|
||||
s.author = 'Paseo'
|
||||
s.homepage = 'https://paseo.sh'
|
||||
s.platforms = { :ios => '15.1' }
|
||||
s.swift_version = '5.4'
|
||||
s.source = { :path => '.' }
|
||||
s.static_framework = true
|
||||
|
||||
s.dependency 'ExpoModulesCore'
|
||||
|
||||
s.pod_target_xcconfig = {
|
||||
'DEFINES_MODULE' => 'YES',
|
||||
'SWIFT_COMPILATION_MODE' => 'wholemodule'
|
||||
}
|
||||
|
||||
s.source_files = "**/*.{h,m,swift}"
|
||||
end
|
||||
@@ -0,0 +1,33 @@
|
||||
import ExpoModulesCore
|
||||
import UIKit
|
||||
|
||||
public class PaseoPressFeedbackModule: Module {
|
||||
public func definition() -> ModuleDefinition {
|
||||
Name("PaseoPressFeedback")
|
||||
View(PaseoPressFeedbackView.self) {
|
||||
Prop("tint") { (view: PaseoPressFeedbackView, color: UIColor) in view.tint = color }
|
||||
Prop("radius") { (view: PaseoPressFeedbackView, radius: Double) in view.radius = radius }
|
||||
Prop("resetKey") { (view: PaseoPressFeedbackView, key: String) in view.reset(key) }
|
||||
AsyncFunction("acknowledge") { (view: PaseoPressFeedbackView) in view.acknowledge() }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
final class PaseoPressFeedbackView: ExpoView {
|
||||
var tint = UIColor.clear
|
||||
var radius: Double = 0
|
||||
private var acknowledged = false
|
||||
private var resetKey = ""
|
||||
required init(appContext: AppContext? = nil) {
|
||||
super.init(appContext: appContext)
|
||||
isOpaque = false
|
||||
isUserInteractionEnabled = false
|
||||
}
|
||||
func acknowledge() { acknowledged = true; setNeedsDisplay() }
|
||||
func reset(_ key: String) {
|
||||
if key != resetKey { resetKey = key; acknowledged = false; setNeedsDisplay() }
|
||||
}
|
||||
override func draw(_ rect: CGRect) {
|
||||
if acknowledged { tint.setFill(); UIBezierPath(roundedRect: bounds, cornerRadius: radius).fill() }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"name": "paseo-press-feedback",
|
||||
"version": "0.1.0",
|
||||
"private": true
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
import { expect, it } from "vitest";
|
||||
import { acceptWorkspaceRowPress, type WorkspaceRowPress } from "./accept";
|
||||
|
||||
function rowPress(overrides: Partial<WorkspaceRowPress> = {}) {
|
||||
const visible: string[] = [];
|
||||
const press: WorkspaceRowPress = {
|
||||
cancelled: false,
|
||||
native: true,
|
||||
selected: false,
|
||||
sidebar: "overlay",
|
||||
target: "agent-list",
|
||||
acknowledge: () => visible.push("row"),
|
||||
navigate: () => visible.push("workspace"),
|
||||
...overrides,
|
||||
};
|
||||
return { press, visible };
|
||||
}
|
||||
|
||||
it("acknowledges an accepted row before navigation starts", () => {
|
||||
const { press, visible } = rowPress();
|
||||
expect(acceptWorkspaceRowPress(press)).toBe(true);
|
||||
expect(visible).toEqual(["row", "workspace"]);
|
||||
});
|
||||
|
||||
it("does not acknowledge or navigate after scrolling or a long press claims the touch", () => {
|
||||
const { press, visible } = rowPress({ cancelled: true });
|
||||
expect(acceptWorkspaceRowPress(press)).toBe(false);
|
||||
expect(visible).toEqual([]);
|
||||
});
|
||||
|
||||
it("accepts only the first row while its selection closes the sidebar", () => {
|
||||
const { press, visible } = rowPress();
|
||||
press.navigate = () => {
|
||||
press.target = "agent";
|
||||
visible.push("workspace B");
|
||||
};
|
||||
expect(acceptWorkspaceRowPress(press)).toBe(true);
|
||||
expect(acceptWorkspaceRowPress(press)).toBe(false);
|
||||
expect(visible).toEqual(["row", "workspace B"]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
{
|
||||
name: "open phone or tablet overlay",
|
||||
sidebar: "overlay",
|
||||
target: "agent-list",
|
||||
native: true,
|
||||
accepted: true,
|
||||
},
|
||||
{ name: "closing overlay", sidebar: "overlay", target: "agent", native: true, accepted: false },
|
||||
{
|
||||
name: "explorer covering an overlay",
|
||||
sidebar: "overlay",
|
||||
target: "file-explorer",
|
||||
native: true,
|
||||
accepted: false,
|
||||
},
|
||||
{ name: "docked sidebar", sidebar: "dock", target: "agent", native: true, accepted: true },
|
||||
{
|
||||
name: "docked sidebar beside explorer",
|
||||
sidebar: "dock",
|
||||
target: "file-explorer",
|
||||
native: true,
|
||||
accepted: true,
|
||||
},
|
||||
{ name: "hidden sidebar", sidebar: "hidden", target: "agent", native: true, accepted: false },
|
||||
{
|
||||
name: "suspended open overlay",
|
||||
sidebar: "suspended",
|
||||
target: "agent-list",
|
||||
native: true,
|
||||
accepted: true,
|
||||
},
|
||||
{
|
||||
name: "suspended closed overlay",
|
||||
sidebar: "suspended",
|
||||
target: "agent",
|
||||
native: true,
|
||||
accepted: false,
|
||||
},
|
||||
{
|
||||
name: "web sidebar independent of native panel target",
|
||||
sidebar: "overlay",
|
||||
target: "agent",
|
||||
native: false,
|
||||
accepted: true,
|
||||
},
|
||||
] as const)("uses the panel state for $name", ({ accepted, name: _, ...state }) => {
|
||||
const { press, visible } = rowPress(state);
|
||||
expect(acceptWorkspaceRowPress(press)).toBe(accepted);
|
||||
expect(visible).toEqual(accepted ? ["row", "workspace"] : []);
|
||||
});
|
||||
|
||||
it("does not leave an acknowledgement over an already selected docked row", () => {
|
||||
const { press, visible } = rowPress({ selected: true, sidebar: "dock", target: "agent" });
|
||||
expect(acceptWorkspaceRowPress(press)).toBe(true);
|
||||
expect(visible).toEqual(["workspace"]);
|
||||
});
|
||||
|
||||
it("still acknowledges a selected overlay row before the sidebar leaves", () => {
|
||||
const { press, visible } = rowPress({ selected: true });
|
||||
expect(acceptWorkspaceRowPress(press)).toBe(true);
|
||||
expect(visible).toEqual(["row", "workspace"]);
|
||||
});
|
||||
@@ -0,0 +1,20 @@
|
||||
import type { LeftSidebarPresentation, MobilePanelView } from "@/stores/panel-store";
|
||||
|
||||
export interface WorkspaceRowPress {
|
||||
cancelled: boolean;
|
||||
native: boolean;
|
||||
selected: boolean;
|
||||
sidebar: LeftSidebarPresentation;
|
||||
target: MobilePanelView;
|
||||
acknowledge(): void;
|
||||
navigate(): void;
|
||||
}
|
||||
|
||||
export function acceptWorkspaceRowPress(press: WorkspaceRowPress): boolean {
|
||||
if (press.cancelled) return false;
|
||||
if (press.native && press.sidebar !== "dock" && press.target !== "agent-list") return false;
|
||||
// A selected docked row neither changes selection nor leaves the screen to clear the fill.
|
||||
if (!press.selected || press.sidebar !== "dock") press.acknowledge();
|
||||
press.navigate();
|
||||
return true;
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import { requireNativeView } from "expo";
|
||||
import { type Ref } from "react";
|
||||
import { usePanelStore } from "@/stores/panel-store";
|
||||
import { withUnistyles } from "react-native-unistyles";
|
||||
import { View, StyleSheet, type ViewProps } from "react-native";
|
||||
|
||||
export interface RowFeedbackHandle {
|
||||
acknowledge(): Promise<void>;
|
||||
}
|
||||
interface FeedbackProps extends ViewProps {
|
||||
ref?: Ref<RowFeedbackHandle>;
|
||||
resetKey: string;
|
||||
tint?: string;
|
||||
radius?: number;
|
||||
}
|
||||
const NativeFeedback = withUnistyles(requireNativeView<FeedbackProps>("PaseoPressFeedback"));
|
||||
const mapTheme = (theme: import("@/styles/theme").Theme) => ({
|
||||
tint: theme.colors.interactionHighlight,
|
||||
radius: theme.borderRadius.lg,
|
||||
});
|
||||
export function RowFeedback({
|
||||
ref,
|
||||
selected,
|
||||
}: {
|
||||
ref?: Ref<RowFeedbackHandle>;
|
||||
selected: boolean;
|
||||
}) {
|
||||
const revision = usePanelStore((state) => state.mobilePanel.revision);
|
||||
// Selection takes over the fill; a new panel transition clears it before reopening.
|
||||
const resetKey = `${selected}:${revision}`;
|
||||
return (
|
||||
<View pointerEvents="none" style={styles.overlay}>
|
||||
<NativeFeedback
|
||||
ref={ref}
|
||||
resetKey={resetKey}
|
||||
pointerEvents="none"
|
||||
style={styles.fill}
|
||||
uniProps={mapTheme}
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
overlay: { position: "absolute", top: 0, right: 0, bottom: 0, left: 0 },
|
||||
fill: { flex: 1 },
|
||||
});
|
||||
@@ -0,0 +1,7 @@
|
||||
import type { Ref } from "react";
|
||||
export interface RowFeedbackHandle {
|
||||
acknowledge(): Promise<void>;
|
||||
}
|
||||
export function RowFeedback(_props: { ref?: Ref<RowFeedbackHandle>; selected: boolean }) {
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import { useCallback, useRef, type RefObject } from "react";
|
||||
import { isNative } from "@/constants/platform";
|
||||
import { usePanelStore } from "@/stores/panel-store";
|
||||
import { acceptWorkspaceRowPress } from "../accept";
|
||||
import { RowFeedback, type RowFeedbackHandle } from "./feedback";
|
||||
|
||||
export function useWorkspaceRowPress({
|
||||
didLongPressRef,
|
||||
onPress,
|
||||
selected,
|
||||
}: {
|
||||
didLongPressRef?: RefObject<boolean>;
|
||||
onPress(): void;
|
||||
selected: boolean;
|
||||
}) {
|
||||
const feedback = useRef<RowFeedbackHandle>(null);
|
||||
const handlePress = useCallback(() => {
|
||||
const cancelled = didLongPressRef?.current ?? false;
|
||||
if (didLongPressRef) didLongPressRef.current = false;
|
||||
const panel = usePanelStore.getState();
|
||||
acceptWorkspaceRowPress({
|
||||
cancelled,
|
||||
native: isNative,
|
||||
selected,
|
||||
sidebar: panel.layout.leftSidebar,
|
||||
target: panel.mobilePanel.target,
|
||||
// Paint on the native UI thread before navigation occupies JS; never wait for paint.
|
||||
acknowledge: () => {
|
||||
void feedback.current?.acknowledge();
|
||||
},
|
||||
navigate: onPress,
|
||||
});
|
||||
}, [didLongPressRef, onPress, selected]);
|
||||
return {
|
||||
onPress: handlePress,
|
||||
feedback: <RowFeedback ref={feedback} selected={selected} />,
|
||||
};
|
||||
}
|
||||
@@ -17,13 +17,6 @@ import { isNative } from "@/constants/platform";
|
||||
* On macOS, Electron handles edge resize natively.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Marks a scroll viewport as window content: it and its descendants emit no window
|
||||
* regions, because Electron does not clip app-region rects to scroll viewports.
|
||||
* See the `[data-window-content]` rule in public/index.html.
|
||||
*/
|
||||
export const WINDOW_CONTENT_DATASET = { "window-content": "" };
|
||||
|
||||
export const titlebarDragSurfaceStyle: React.CSSProperties = {
|
||||
cursor: "default",
|
||||
// @ts-expect-error — WebkitAppRegion is not in CSSProperties
|
||||
|
||||
@@ -9,16 +9,7 @@ import {
|
||||
type LucideIcon,
|
||||
} from "lucide-react-native";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import {
|
||||
memo,
|
||||
useCallback,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
type ReactNode,
|
||||
type RefObject,
|
||||
} from "react";
|
||||
import { memo, useCallback, useEffect, useMemo, useRef, useState, type RefObject } from "react";
|
||||
import {
|
||||
Pressable,
|
||||
ScrollView,
|
||||
@@ -28,19 +19,12 @@ import {
|
||||
View,
|
||||
type LayoutChangeEvent,
|
||||
} from "react-native";
|
||||
import {
|
||||
Gesture,
|
||||
type GestureType,
|
||||
ScrollView as GHScrollView,
|
||||
} from "react-native-gesture-handler";
|
||||
import { Gesture, ScrollView as GHScrollView } from "react-native-gesture-handler";
|
||||
import Animated, { runOnJS, useAnimatedStyle, useSharedValue } from "react-native-reanimated";
|
||||
import { scheduleOnRN } from "react-native-worklets";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
import { StyleSheet, useUnistyles } from "react-native-unistyles";
|
||||
import {
|
||||
TitlebarDragRegion,
|
||||
WINDOW_CONTENT_DATASET,
|
||||
} from "@/components/desktop/titlebar-drag-region";
|
||||
import { TitlebarDragRegion } from "@/components/desktop/titlebar-drag-region";
|
||||
import { SidebarCloseButton } from "@/components/headers/sidebar-close-button";
|
||||
import {
|
||||
resolveDesktopSidebarInsetLeft,
|
||||
@@ -55,7 +39,7 @@ import { HostPicker } from "@/components/hosts/host-picker";
|
||||
import { SidebarDisplayPreferencesMenu } from "@/components/sidebar/display-preferences/menu";
|
||||
import { SidebarSeparator } from "@/components/sidebar/sidebar-separator";
|
||||
import { SidebarToastRegion } from "@/components/sidebar/sidebar-toast-region";
|
||||
import { SidebarNavRows, useVisibleSidebarNavItems } from "@/components/sidebar/sidebar-nav-rows";
|
||||
import { SidebarNavRows } from "@/components/sidebar/sidebar-nav-rows";
|
||||
import { SidebarFooterIconHighlight } from "@/components/sidebar/sidebar-footer-icon-highlight";
|
||||
import { SidebarHelpMenu } from "@/components/sidebar/sidebar-help-menu";
|
||||
import { SidebarFooterOverflowMenu } from "@/components/sidebar/sidebar-footer-overflow-menu";
|
||||
@@ -638,7 +622,29 @@ function MobileSidebar({
|
||||
>
|
||||
<View style={styles.sidebarContent} pointerEvents="auto">
|
||||
<WindowChromeSafeArea placement="below" />
|
||||
<SidebarNavScroll closeGestureRef={closeGestureRef}>{navRows}</SidebarNavScroll>
|
||||
{platformIsNative ? (
|
||||
<GHScrollView
|
||||
// Same contract as the workspace list: vertical drags scroll the nav
|
||||
// block, a clear horizontal intent still activates the close pan.
|
||||
simultaneousHandlers={closeGestureRef}
|
||||
style={styles.mobileNavScroll}
|
||||
showsVerticalScrollIndicator={false}
|
||||
alwaysBounceVertical={false}
|
||||
testID="sidebar-nav-scroll"
|
||||
>
|
||||
{navRows}
|
||||
</GHScrollView>
|
||||
) : (
|
||||
<ScrollView
|
||||
style={styles.mobileNavScroll}
|
||||
showsVerticalScrollIndicator={false}
|
||||
alwaysBounceVertical={false}
|
||||
testID="sidebar-nav-scroll"
|
||||
>
|
||||
{navRows}
|
||||
</ScrollView>
|
||||
)}
|
||||
<SidebarSeparator />
|
||||
|
||||
<SidebarViewSlot dismiss={handleWorkspacePress}>
|
||||
<SidebarToastRegion active={active}>
|
||||
@@ -683,47 +689,6 @@ function MobileSidebar({
|
||||
);
|
||||
}
|
||||
|
||||
interface SidebarNavScrollProps {
|
||||
closeGestureRef: RefObject<GestureType | undefined>;
|
||||
/** Web only: the viewport emits no window regions (see WINDOW_CONTENT_DATASET). */
|
||||
windowContent?: boolean;
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
// The capped, scrolling nav block shared by the mobile and desktop sidebars, with the
|
||||
// divider below it. The divider is a sibling because Unistyles does not patch the
|
||||
// gesture-handler ScrollView.
|
||||
function SidebarNavScroll({ closeGestureRef, windowContent, children }: SidebarNavScrollProps) {
|
||||
return (
|
||||
<>
|
||||
{platformIsNative ? (
|
||||
<GHScrollView
|
||||
// Same contract as the workspace list: vertical drags scroll the nav
|
||||
// block, a clear horizontal intent still activates the close pan.
|
||||
simultaneousHandlers={closeGestureRef}
|
||||
style={styles.navScroll}
|
||||
showsVerticalScrollIndicator={false}
|
||||
alwaysBounceVertical={false}
|
||||
testID="sidebar-nav-scroll"
|
||||
>
|
||||
{children}
|
||||
</GHScrollView>
|
||||
) : (
|
||||
<ScrollView
|
||||
dataSet={windowContent ? WINDOW_CONTENT_DATASET : undefined}
|
||||
style={styles.navScroll}
|
||||
showsVerticalScrollIndicator={false}
|
||||
alwaysBounceVertical={false}
|
||||
testID="sidebar-nav-scroll"
|
||||
>
|
||||
{children}
|
||||
</ScrollView>
|
||||
)}
|
||||
<SidebarSeparator testID="sidebar-nav-separator" />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function DesktopSidebar({
|
||||
theme,
|
||||
workspaceGroups,
|
||||
@@ -844,14 +809,12 @@ function DesktopSidebar({
|
||||
],
|
||||
[insetsTop, insets.bottom, insets.left, overlay, divisionLayout],
|
||||
);
|
||||
// Below the window controls' row, or in the top band's place, the first row starts flush.
|
||||
const inTopBand = useTopBand() !== null;
|
||||
// Windows and Linux draw their window controls top-right, so the sidebar has no chrome
|
||||
// row there. The strip above the scrolling rows is then its window drag surface.
|
||||
const showsChromeRow = ownsTopLeft || Boolean(DEV_BUILD_LABEL);
|
||||
// With every top item hidden the sidebar starts at the Workspaces section, as before the
|
||||
// nav scroller existed: no strip above it and no divider below it.
|
||||
const hasNavRows = useVisibleSidebarNavItems().length > 0;
|
||||
const showsDragStrip = hasNavRows && !showsChromeRow && !inTopBand;
|
||||
const sidebarHeaderGroupStyle = useMemo(
|
||||
() => [styles.sidebarHeaderGroup, (ownsTopLeft || inTopBand) && styles.sidebarHeaderGroupFlush],
|
||||
[ownsTopLeft, inTopBand],
|
||||
);
|
||||
return (
|
||||
<MobilePanelOverlay
|
||||
panel="agent-list"
|
||||
@@ -862,7 +825,7 @@ function DesktopSidebar({
|
||||
<Animated.View style={desktopSidebarStyle}>
|
||||
<View style={desktopSidebarBorderStyle}>
|
||||
<View style={styles.sidebarDragArea}>
|
||||
{showsChromeRow ? (
|
||||
{ownsTopLeft || DEV_BUILD_LABEL ? (
|
||||
<View style={styles.desktopChromeRow}>
|
||||
<TitlebarDragRegion />
|
||||
{DEV_BUILD_LABEL ? (
|
||||
@@ -879,21 +842,11 @@ function DesktopSidebar({
|
||||
</View>
|
||||
) : null}
|
||||
</View>
|
||||
) : null}
|
||||
{showsDragStrip ? (
|
||||
<View style={styles.desktopDragStrip} testID="sidebar-nav-drag-strip">
|
||||
<TitlebarDragRegion />
|
||||
</View>
|
||||
) : null}
|
||||
) : (
|
||||
<TitlebarDragRegion />
|
||||
)}
|
||||
<SidebarNavRows style={sidebarHeaderGroupStyle} onBeforeNavigate={closeSidebar} />
|
||||
</View>
|
||||
{/* The drag overlay stays above this viewport: Electron does not clip
|
||||
app-region rects to scroll viewports, so a scrolled-out row would
|
||||
still claim its no-drag rect. */}
|
||||
{hasNavRows ? (
|
||||
<SidebarNavScroll closeGestureRef={closeGestureRef} windowContent>
|
||||
<SidebarNavRows style={styles.sidebarHeaderGroup} onBeforeNavigate={closeSidebar} />
|
||||
</SidebarNavScroll>
|
||||
) : null}
|
||||
|
||||
<SidebarViewSlot dismiss={closeSidebar}>
|
||||
<SidebarToastRegion active={active}>
|
||||
@@ -982,18 +935,19 @@ const staticStyles = RNStyleSheet.create({
|
||||
});
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
// The rows start flush: the chrome row, drag strip, or top band above them gives the inset.
|
||||
sidebarHeaderGroup: {
|
||||
paddingTop: theme.spacing[2],
|
||||
gap: 2,
|
||||
paddingBottom: theme.spacing[1.5],
|
||||
borderBottomWidth: 1,
|
||||
borderBottomColor: theme.colors.border,
|
||||
},
|
||||
desktopDragStrip: {
|
||||
position: "relative",
|
||||
height: theme.spacing[2],
|
||||
sidebarHeaderGroupFlush: {
|
||||
paddingTop: 0,
|
||||
},
|
||||
// The nav block caps at half the sidebar; a long item list scrolls inside the
|
||||
// cap instead of crowding the workspace list off a short screen.
|
||||
navScroll: {
|
||||
mobileNavScroll: {
|
||||
flexGrow: 0,
|
||||
flexShrink: 1,
|
||||
maxHeight: "50%",
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { useWorkspaceRowPress } from "../../modules/paseo-press-feedback";
|
||||
import { PressHighlight as Pressable } from "@/components/ui/press-highlight";
|
||||
import { LoadingSpinner } from "@/components/ui/loading-spinner";
|
||||
import {
|
||||
@@ -1090,13 +1091,11 @@ function WorkspaceRowInner({
|
||||
...dragAttributes
|
||||
} = dragHandleProps?.attributes ?? {};
|
||||
|
||||
const handlePress = useCallback(() => {
|
||||
if (interaction.didLongPressRef.current) {
|
||||
interaction.didLongPressRef.current = false;
|
||||
return;
|
||||
}
|
||||
onPress();
|
||||
}, [interaction.didLongPressRef, onPress]);
|
||||
const { onPress: handlePress, feedback } = useWorkspaceRowPress({
|
||||
didLongPressRef: interaction.didLongPressRef,
|
||||
onPress,
|
||||
selected,
|
||||
});
|
||||
|
||||
const accessibilityState = useMemo(() => ({ selected }), [selected]);
|
||||
const isEditingTitle = titleEditor !== null;
|
||||
@@ -1191,6 +1190,7 @@ function WorkspaceRowInner({
|
||||
onTogglePin={onTogglePin}
|
||||
/>
|
||||
</SidebarWorkspaceRowContent>
|
||||
{feedback}
|
||||
</SidebarWorkspaceContextMenu>
|
||||
</View>
|
||||
);
|
||||
|
||||
@@ -35,19 +35,14 @@ interface SidebarNavRowsProps extends SidebarNavRowProps {
|
||||
firstRowTrailing?: ReactNode;
|
||||
}
|
||||
|
||||
/** The top-level items the user keeps visible, in display order. */
|
||||
export function useVisibleSidebarNavItems() {
|
||||
const { items } = useSidebarNavItems("header");
|
||||
return useMemo(() => items.filter((item) => item.visible), [items]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Top-level sidebar navigation, ordered and filtered by the user's
|
||||
* `sidebarNavItems` preference. Renders nothing — not even the bordered group
|
||||
* wrapper — when every item is hidden and there is no `firstRowTrailing`.
|
||||
*/
|
||||
export function SidebarNavRows({ style, onBeforeNavigate, firstRowTrailing }: SidebarNavRowsProps) {
|
||||
const visibleItems = useVisibleSidebarNavItems();
|
||||
const { items } = useSidebarNavItems("header");
|
||||
const visibleItems = useMemo(() => items.filter((item) => item.visible), [items]);
|
||||
const groupRef = useRef<View | null>(null);
|
||||
|
||||
if (visibleItems.length === 0 && !firstRowTrailing) return null;
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { useWorkspaceRowPress } from "../../../modules/paseo-press-feedback";
|
||||
import { PressHighlight as Pressable } from "@/components/ui/press-highlight";
|
||||
import {
|
||||
memo,
|
||||
@@ -846,13 +847,11 @@ function StatusWorkspaceRowInnerContent({
|
||||
const startDragPress = dragInteraction?.handlePressIn;
|
||||
const moveDragPress = dragInteraction?.handleTouchMove;
|
||||
const endDragPress = dragInteraction?.handlePressOut;
|
||||
const handlePress = useCallback(() => {
|
||||
if (didLongPressRef?.current) {
|
||||
didLongPressRef.current = false;
|
||||
return;
|
||||
}
|
||||
onPress();
|
||||
}, [didLongPressRef, onPress]);
|
||||
const { onPress: handlePress, feedback } = useWorkspaceRowPress({
|
||||
didLongPressRef,
|
||||
onPress,
|
||||
selected,
|
||||
});
|
||||
|
||||
return (
|
||||
<SidebarWorkspaceRowFrame
|
||||
@@ -965,6 +964,7 @@ function StatusWorkspaceRowInnerContent({
|
||||
/>
|
||||
) : null}
|
||||
</SidebarWorkspaceRowContent>
|
||||
{feedback}
|
||||
</SidebarWorkspaceContextMenu>
|
||||
</View>
|
||||
);
|
||||
|
||||
@@ -431,7 +431,7 @@ function AddHostModalContent({ visible, onClose, onCancel, onSaved }: AddHostMod
|
||||
<View style={styles.portRow}>
|
||||
<View style={hostFieldStyle}>
|
||||
<Text style={styles.label}>{t("pairing.direct.fields.host")}</Text>
|
||||
<AdaptiveTextInput
|
||||
<ThemedAdaptiveTextInput
|
||||
testID="direct-host-input"
|
||||
nativeID="direct-host-input"
|
||||
accessibilityLabel={t("pairing.direct.fields.host")}
|
||||
@@ -449,7 +449,7 @@ function AddHostModalContent({ visible, onClose, onCancel, onSaved }: AddHostMod
|
||||
</View>
|
||||
<View style={portFieldStyle}>
|
||||
<Text style={styles.label}>{t("pairing.direct.fields.port")}</Text>
|
||||
<AdaptiveTextInput
|
||||
<ThemedAdaptiveTextInput
|
||||
testID="direct-port-input"
|
||||
nativeID="direct-port-input"
|
||||
accessibilityLabel={t("pairing.direct.fields.port")}
|
||||
@@ -491,7 +491,7 @@ function AddHostModalContent({ visible, onClose, onCancel, onSaved }: AddHostMod
|
||||
<View style={styles.field}>
|
||||
<Text style={styles.label}>{t("pairing.direct.fields.password")}</Text>
|
||||
<View style={styles.passwordRow}>
|
||||
<AdaptiveTextInput
|
||||
<ThemedAdaptiveTextInput
|
||||
testID="direct-password-input"
|
||||
nativeID="direct-password-input"
|
||||
accessibilityLabel={t("pairing.direct.fields.password")}
|
||||
@@ -539,7 +539,7 @@ function AddHostModalContent({ visible, onClose, onCancel, onSaved }: AddHostMod
|
||||
<Text style={styles.advancedText}>{t("pairing.direct.advanced.label")}</Text>
|
||||
</PressHighlight>
|
||||
{isAdvancedOpen ? (
|
||||
<AdaptiveTextInput
|
||||
<ThemedAdaptiveTextInput
|
||||
testID="direct-host-uri-input"
|
||||
nativeID="direct-host-uri-input"
|
||||
accessibilityLabel={t("pairing.direct.fields.connectionUri")}
|
||||
@@ -598,3 +598,7 @@ const ThemedChevronRight = withUnistyles(ChevronRight, (theme) => ({
|
||||
const ThemedEye = withUnistyles(Eye, (theme) => ({ color: theme.colors.foregroundMuted }));
|
||||
|
||||
const ThemedEyeOff = withUnistyles(EyeOff, (theme) => ({ color: theme.colors.foregroundMuted }));
|
||||
|
||||
const ThemedAdaptiveTextInput = withUnistyles(AdaptiveTextInput, (theme) => ({
|
||||
placeholderTextColor: theme.colors.foregroundMuted,
|
||||
}));
|
||||
|
||||
@@ -212,7 +212,7 @@ function PairLinkModalContent({
|
||||
|
||||
<View style={styles.field}>
|
||||
<Text style={styles.label}>{t("pairing.link.label")}</Text>
|
||||
<AdaptiveTextInput
|
||||
<ThemedAdaptiveTextInput
|
||||
ref={inputRef}
|
||||
initialValue={initialUrl}
|
||||
testID="pair-link-input"
|
||||
@@ -234,13 +234,11 @@ function PairLinkModalContent({
|
||||
<Text style={styles.label}>
|
||||
{t("pairing.hostPassword.title", { host: parsedHostLabel(offerUrlRef.current) })}
|
||||
</Text>
|
||||
<AdaptiveTextInput
|
||||
<ThemedAdaptiveTextInput
|
||||
testID="pair-link-password-input"
|
||||
resetKey={`pair-link-password-${passwordResetKey}`}
|
||||
accessibilityLabel={t("pairing.hostPassword.label")}
|
||||
placeholder={t("pairing.hostPassword.label")}
|
||||
onChangeText={setPassword}
|
||||
autoFocus
|
||||
secureTextEntry
|
||||
style={styles.input}
|
||||
/>
|
||||
@@ -277,3 +275,7 @@ function PairLinkModalContent({
|
||||
}
|
||||
|
||||
const ThemedLink = withUnistyles(Link, (theme) => ({ color: theme.colors.accentForeground }));
|
||||
|
||||
const ThemedAdaptiveTextInput = withUnistyles(AdaptiveTextInput, (theme) => ({
|
||||
placeholderTextColor: theme.colors.foregroundMuted,
|
||||
}));
|
||||
|
||||
@@ -2256,59 +2256,6 @@ describe("HostRuntimeController", () => {
|
||||
});
|
||||
});
|
||||
|
||||
const REGISTRY_KEY = "@paseo:daemon-registry";
|
||||
const futureConnection = { id: "future:1", type: "futureKind", address: "future.example.com" };
|
||||
const directA: HostConnection = {
|
||||
id: "direct:lan-a:6767",
|
||||
type: "directTcp",
|
||||
endpoint: "lan-a:6767",
|
||||
};
|
||||
const directB: HostConnection = {
|
||||
id: "direct:lan-b:6767",
|
||||
type: "directTcp",
|
||||
endpoint: "lan-b:6767",
|
||||
};
|
||||
// What a build with a connection kind this one doesn't know leaves behind: an extra connection
|
||||
// on a host this build can reach, and a host reached only through it.
|
||||
const storedWithUnreadableEntries = [
|
||||
{
|
||||
...makeHost({ serverId: "srv_a", password: "secret-a" }),
|
||||
connections: [futureConnection, directA],
|
||||
},
|
||||
makeHost({ serverId: "srv_b", password: "secret-b", connections: [directB] }),
|
||||
{ serverId: "srv_future", label: "future host", connections: [futureConnection] },
|
||||
];
|
||||
|
||||
async function bootWithRegistry(registry: string): Promise<{
|
||||
store: HostRuntimeStore;
|
||||
storage: HostRuntimeStorage;
|
||||
}> {
|
||||
const storage = createMemoryHostRuntimeStorage({
|
||||
[REGISTRY_KEY]: registry,
|
||||
"@paseo:e2e": "1",
|
||||
});
|
||||
const store = new HostRuntimeStore({
|
||||
storage,
|
||||
deps: {
|
||||
createClient: () => new FakeDaemonClient() as unknown as DaemonClient,
|
||||
connectToDaemon: async ({ host }) => ({
|
||||
client: makeConnectedProbeClient(5) as unknown as DaemonClient,
|
||||
serverId: host.serverId,
|
||||
hostname: host.label ?? null,
|
||||
}),
|
||||
getClientId: async () => "cid_test_runtime",
|
||||
},
|
||||
revokePushNotifications: async () => undefined,
|
||||
});
|
||||
await store.boot();
|
||||
return { store, storage };
|
||||
}
|
||||
|
||||
async function readRegistry(storage: HostRuntimeStorage): Promise<unknown> {
|
||||
const raw = await storage.getItem(REGISTRY_KEY);
|
||||
return raw === null ? null : JSON.parse(raw);
|
||||
}
|
||||
|
||||
describe("HostRuntimeStore", () => {
|
||||
function gatewayRecoveryFixture() {
|
||||
const parent = new FakeDaemonClient();
|
||||
@@ -2739,98 +2686,6 @@ describe("HostRuntimeStore", () => {
|
||||
session.clearSession(host.serverId);
|
||||
});
|
||||
|
||||
it("keeps readable hosts when the registry holds entries this build can't read", async () => {
|
||||
const { store, storage } = await bootWithRegistry(JSON.stringify(storedWithUnreadableEntries));
|
||||
|
||||
expect(store.getHosts().map((host) => [host.serverId, host.password])).toEqual([
|
||||
["srv_a", "secret-a"],
|
||||
["srv_b", "secret-b"],
|
||||
]);
|
||||
expect(store.getHosts()[0]?.connections.map((connection) => connection.id)).toEqual([
|
||||
directA.id,
|
||||
]);
|
||||
expect(await readRegistry(storage)).toEqual(storedWithUnreadableEntries);
|
||||
|
||||
store.syncHosts([]);
|
||||
});
|
||||
|
||||
it("keeps the entries it can't read when it saves the registry", async () => {
|
||||
const { store, storage } = await bootWithRegistry(JSON.stringify(storedWithUnreadableEntries));
|
||||
|
||||
await store.renameHost("srv_b", "renamed");
|
||||
|
||||
expect(await readRegistry(storage)).toMatchObject([
|
||||
{
|
||||
serverId: "srv_a",
|
||||
password: "secret-a",
|
||||
connections: [{ id: directA.id }, futureConnection],
|
||||
},
|
||||
{ serverId: "srv_b", password: "secret-b", label: "renamed" },
|
||||
storedWithUnreadableEntries[2],
|
||||
]);
|
||||
|
||||
store.syncHosts([]);
|
||||
});
|
||||
|
||||
it("moves a stored connection password to its host and keeps the connection it can't read", async () => {
|
||||
const { store, storage } = await bootWithRegistry(
|
||||
JSON.stringify([
|
||||
{
|
||||
serverId: "srv_legacy",
|
||||
connections: [
|
||||
{ type: "directTcp", endpoint: "lan-a:6767", password: "old-secret" },
|
||||
futureConnection,
|
||||
],
|
||||
},
|
||||
]),
|
||||
);
|
||||
|
||||
expect(store.getHosts().map((host) => [host.serverId, host.password])).toEqual([
|
||||
["srv_legacy", "old-secret"],
|
||||
]);
|
||||
await vi.waitFor(async () =>
|
||||
expect(await readRegistry(storage)).toMatchObject([
|
||||
{ serverId: "srv_legacy", password: "old-secret" },
|
||||
]),
|
||||
);
|
||||
expect(await readRegistry(storage)).toMatchObject([
|
||||
{ connections: [{ ...directA, useTls: false }, futureConnection] },
|
||||
]);
|
||||
const [written] = (await readRegistry(storage)) as Array<{ connections: unknown[] }>;
|
||||
expect(written?.connections[0]).not.toHaveProperty("password");
|
||||
|
||||
store.syncHosts([]);
|
||||
});
|
||||
|
||||
it("forgets an entry it can't read once that host is paired again and removed", async () => {
|
||||
const { store, storage } = await bootWithRegistry(
|
||||
JSON.stringify([{ serverId: "srv_future", connections: [futureConnection] }]),
|
||||
);
|
||||
expect(store.getHosts()).toEqual([]);
|
||||
|
||||
await store.upsertDirectConnection({ serverId: "srv_future", endpoint: directA.endpoint });
|
||||
await vi.waitFor(async () =>
|
||||
expect(await readRegistry(storage)).toMatchObject([
|
||||
{ serverId: "srv_future", connections: [{ id: directA.id }] },
|
||||
]),
|
||||
);
|
||||
|
||||
await store.removeHost("srv_future");
|
||||
expect(await readRegistry(storage)).toEqual([]);
|
||||
|
||||
store.syncHosts([]);
|
||||
});
|
||||
|
||||
it("copies a registry that isn't JSON aside instead of deleting it", async () => {
|
||||
const { store, storage } = await bootWithRegistry("{not json");
|
||||
|
||||
expect(store.getHosts()).toEqual([]);
|
||||
expect(await storage.getItem(`${REGISTRY_KEY}:unreadable`)).toBe("{not json");
|
||||
expect(await storage.getItem(REGISTRY_KEY)).toBe("{not json");
|
||||
|
||||
store.syncHosts([]);
|
||||
});
|
||||
|
||||
it("marks the host registry loaded after boot reads storage", async () => {
|
||||
const previousOverride = process.env.EXPO_PUBLIC_LOCAL_DAEMON;
|
||||
process.env.EXPO_PUBLIC_LOCAL_DAEMON = "not-an-endpoint";
|
||||
|
||||
@@ -17,16 +17,14 @@ import {
|
||||
import {
|
||||
connectionFromListen,
|
||||
createRemoteSshHostConnection,
|
||||
forgetUnreadableHost,
|
||||
normalizeStoredHostProfile,
|
||||
pinRelayProtectedSecurityInProfiles,
|
||||
readHostRegistry,
|
||||
upsertHostConnectionInProfiles,
|
||||
registryHasConnection,
|
||||
relayConnectionFromOffer,
|
||||
writeHostRegistry,
|
||||
StoredHostRegistrySchema,
|
||||
type HostConnection,
|
||||
type HostProfile,
|
||||
type UnreadableHostEntries,
|
||||
} from "@/types/host-connection";
|
||||
import { defaultHostAppearance, type HostBadgeDisplay, type HostColor } from "@/hosts/appearance";
|
||||
import {
|
||||
@@ -45,7 +43,7 @@ import { isWeb } from "@/constants/platform";
|
||||
import { connectToDaemon, getConnectionAuthFailureReason } from "@/utils/test-daemon-connection";
|
||||
import { getOrCreateClientId } from "@/utils/client-id";
|
||||
import { z } from "zod";
|
||||
import { readValidatedString } from "@/storage/validated-storage";
|
||||
import { readValidatedJson, readValidatedString } from "@/storage/validated-storage";
|
||||
import {
|
||||
selectBestConnection,
|
||||
type ConnectionCandidate,
|
||||
@@ -1694,7 +1692,6 @@ export class HostRuntimeStore {
|
||||
private hostListVersion = 0;
|
||||
private hostRegistryLoaded = false;
|
||||
private hosts: HostProfile[] = [];
|
||||
private unreadableHosts: UnreadableHostEntries = { hosts: [], connectionsByServerId: new Map() };
|
||||
private hostAppearanceMutationTail: Promise<void> = Promise.resolve();
|
||||
private hostRegistryStatus: HostRegistryStatus = "loading";
|
||||
private deps: HostRuntimeControllerDeps;
|
||||
@@ -1802,17 +1799,32 @@ export class HostRuntimeStore {
|
||||
let shouldPersistHosts = false;
|
||||
let profiles: HostProfile[] = [];
|
||||
try {
|
||||
const stored = await this.readStoredRegistry();
|
||||
const stored = await readValidatedJson(
|
||||
this.storage,
|
||||
REGISTRY_STORAGE_KEY,
|
||||
StoredHostRegistrySchema,
|
||||
);
|
||||
if (stored) {
|
||||
// An entry this build can't read skips only that host or connection, and stays stored.
|
||||
const registry = readHostRegistry(stored);
|
||||
this.unreadableHosts = registry.unreadable;
|
||||
// COMPAT(connectionPassword): added in v0.9.1, remove after 2027-03-24 with stored-password migration.
|
||||
if (registry.movedConnectionPassword) {
|
||||
shouldPersistHosts = true;
|
||||
const normalizedProfiles: HostProfile[] = [];
|
||||
for (const entry of stored) {
|
||||
const profile = normalizeStoredHostProfile(entry);
|
||||
if (!profile) {
|
||||
await this.storage.removeItem(REGISTRY_STORAGE_KEY);
|
||||
normalizedProfiles.length = 0;
|
||||
break;
|
||||
}
|
||||
// COMPAT(connectionPassword): added in v0.9.1, remove after 2027-03-24 with stored-password migration.
|
||||
if (
|
||||
entry.connections.some(
|
||||
(connection) => connection.type === "directTcp" && connection.password,
|
||||
)
|
||||
) {
|
||||
shouldPersistHosts = true;
|
||||
}
|
||||
normalizedProfiles.push(profile);
|
||||
}
|
||||
profiles = registry.hosts.filter((entry) => !isPlaceholderServerId(entry.serverId));
|
||||
if (profiles.length !== registry.hosts.length) {
|
||||
profiles = normalizedProfiles.filter((entry) => !isPlaceholderServerId(entry.serverId));
|
||||
if (profiles.length !== normalizedProfiles.length) {
|
||||
shouldPersistHosts = true;
|
||||
}
|
||||
}
|
||||
@@ -2308,7 +2320,6 @@ export class HostRuntimeStore {
|
||||
async removeHost(serverId: string): Promise<void> {
|
||||
await this.revokePushNotifications({ client: this.getClient(serverId), serverId });
|
||||
const remaining = this.hosts.filter((daemon) => daemon.serverId !== serverId);
|
||||
this.unreadableHosts = forgetUnreadableHost(this.unreadableHosts, serverId);
|
||||
this.setHostsAndSync(remaining);
|
||||
await this.persistHosts();
|
||||
}
|
||||
@@ -2397,27 +2408,7 @@ export class HostRuntimeStore {
|
||||
}
|
||||
|
||||
private async persistHosts(hosts = this.hosts): Promise<void> {
|
||||
await this.storage.setItem(
|
||||
REGISTRY_STORAGE_KEY,
|
||||
JSON.stringify(writeHostRegistry(hosts, this.unreadableHosts)),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the stored registry without removing it. A value that isn't a JSON array is copied to
|
||||
* `<key>:unreadable` first, because the next save overwrites the key.
|
||||
*/
|
||||
private async readStoredRegistry(): Promise<unknown[] | null> {
|
||||
const raw = await this.storage.getItem(REGISTRY_STORAGE_KEY);
|
||||
if (raw === null) return null;
|
||||
try {
|
||||
const value: unknown = JSON.parse(raw);
|
||||
if (Array.isArray(value)) return value;
|
||||
} catch {
|
||||
// Not JSON: copied aside below.
|
||||
}
|
||||
await this.storage.setItem(`${REGISTRY_STORAGE_KEY}:unreadable`, raw);
|
||||
return null;
|
||||
await this.storage.setItem(REGISTRY_STORAGE_KEY, JSON.stringify(hosts));
|
||||
}
|
||||
|
||||
private emitHostList(): void {
|
||||
|
||||
@@ -21,7 +21,8 @@ import {
|
||||
import { useLocalDaemonServerId } from "@/hooks/use-is-local-daemon";
|
||||
import { PairDeviceModal } from "@/desktop/components/pair-device-modal";
|
||||
import { buildSettingsHostSectionRoute } from "@/utils/host-routes";
|
||||
import { WINDOW_CONTENT_DATASET } from "@/components/desktop/titlebar-drag-region";
|
||||
|
||||
const WINDOW_CONTENT_DATASET = { "window-content": "" };
|
||||
|
||||
export function OpenProjectScreen() {
|
||||
const { t } = useTranslation();
|
||||
|
||||
@@ -106,79 +106,6 @@ describe("workspace-pane-state", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("does not locate a file by an id retained from a previous target", () => {
|
||||
const layout: WorkspaceLayout = {
|
||||
root: {
|
||||
kind: "pane",
|
||||
pane: {
|
||||
id: "main",
|
||||
tabIds: ["file_/repo/a.ts", "agent_agent-a"],
|
||||
focusedTabId: "agent_agent-a",
|
||||
},
|
||||
},
|
||||
focusedPaneId: "main",
|
||||
};
|
||||
const tabs = [
|
||||
createTab("file_/repo/a.ts", { kind: "file", path: "/repo/b.ts" }),
|
||||
createTab("agent_agent-a", { kind: "agent", agentId: "agent-a" }),
|
||||
];
|
||||
const target: WorkspaceTab["target"] = { kind: "file", path: "/repo/a.ts" };
|
||||
|
||||
expect(resolveSideFileOpenPlacement({ layout, sourcePaneId: "main", tabs, target })).toEqual({
|
||||
kind: "split-side-pane",
|
||||
paneId: "main",
|
||||
});
|
||||
expect(deriveWorkspacePaneState({ layout, tabs, preferredTarget: target }).activeTabId).toBe(
|
||||
"agent_agent-a",
|
||||
);
|
||||
});
|
||||
|
||||
it("matches a retained file instance when only the requested line range differs", () => {
|
||||
const pane = {
|
||||
id: "main",
|
||||
tabIds: ["retained-file", "agent_agent-a"],
|
||||
focusedTabId: "agent_agent-a",
|
||||
};
|
||||
const layout: WorkspaceLayout = { root: { kind: "pane", pane }, focusedPaneId: "main" };
|
||||
const tabs = [
|
||||
createTab("retained-file", { kind: "file", path: "/repo/a.ts", lineStart: 2 }),
|
||||
createTab("agent_agent-a", { kind: "agent", agentId: "agent-a" }),
|
||||
];
|
||||
const target: WorkspaceTab["target"] = {
|
||||
kind: "file",
|
||||
path: "/repo/a.ts",
|
||||
lineStart: 12,
|
||||
lineEnd: 20,
|
||||
};
|
||||
|
||||
expect(resolveSideFileOpenPlacement({ layout, sourcePaneId: "main", tabs, target })).toEqual({
|
||||
kind: "open-in-source",
|
||||
});
|
||||
expect(deriveWorkspacePaneState({ layout, tabs, preferredTarget: target }).activeTabId).toBe(
|
||||
"retained-file",
|
||||
);
|
||||
});
|
||||
|
||||
it("prefers an exact file navigation target over another instance of the same resource", () => {
|
||||
const pane = {
|
||||
id: "main",
|
||||
tabIds: ["first", "second"],
|
||||
focusedTabId: "first",
|
||||
};
|
||||
const tabs = [
|
||||
createTab("first", { kind: "file", path: "/repo/a.ts", lineStart: 2 }),
|
||||
createTab("second", { kind: "file", path: "/repo/a.ts", lineStart: 12 }),
|
||||
];
|
||||
|
||||
expect(
|
||||
deriveWorkspacePaneState({
|
||||
pane,
|
||||
tabs,
|
||||
preferredTarget: { kind: "file", path: "/repo/a.ts", lineStart: 12 },
|
||||
}).activeTabId,
|
||||
).toBe("second");
|
||||
});
|
||||
|
||||
it("resolves side file opens to an existing file tab", () => {
|
||||
const layout: WorkspaceLayout = {
|
||||
root: {
|
||||
|
||||
@@ -5,9 +5,12 @@ import {
|
||||
} from "@/stores/workspace-layout-store";
|
||||
import type { WorkspaceTab, WorkspaceTabTarget } from "@/workspace-tabs/model";
|
||||
import type { WorkspaceTabDescriptor } from "@/screens/workspace/workspace-tabs-types";
|
||||
import { normalizeWorkspaceTabTarget, workspaceTabTargetsEqual } from "@/workspace-tabs/identity";
|
||||
import {
|
||||
buildDeterministicWorkspaceTabId,
|
||||
normalizeWorkspaceTabTarget,
|
||||
workspaceTabTargetsEqual,
|
||||
} from "@/workspace-tabs/identity";
|
||||
import { findAdjacentPane } from "@/utils/split-navigation";
|
||||
import { panelResourceKey } from "@/panels/panel-manifest";
|
||||
|
||||
export interface WorkspaceDerivedTab {
|
||||
descriptor: WorkspaceTabDescriptor;
|
||||
@@ -121,10 +124,8 @@ function getActiveTabId(input: {
|
||||
}
|
||||
const matchingTab =
|
||||
input.tabs.find((tab) => workspaceTabTargetsEqual(tab.descriptor.target, preferredTarget)) ??
|
||||
input.tabs.find(
|
||||
(tab) => panelResourceKey(tab.descriptor.target) === panelResourceKey(preferredTarget),
|
||||
);
|
||||
return matchingTab?.descriptor.tabId ?? null;
|
||||
null;
|
||||
return matchingTab?.descriptor.tabId ?? buildDeterministicWorkspaceTabId(preferredTarget);
|
||||
})();
|
||||
|
||||
if (preferredTabId && input.openTabIds.has(preferredTabId)) {
|
||||
@@ -210,8 +211,10 @@ export function resolveSideFileOpenPlacement(input: {
|
||||
tabs: WorkspaceTab[];
|
||||
target: WorkspaceTabTarget;
|
||||
}): WorkspaceSideFileOpenPlacement {
|
||||
const targetKey = panelResourceKey(input.target);
|
||||
const existingTab = input.tabs.find((tab) => panelResourceKey(tab.target) === targetKey);
|
||||
const targetTabId = buildDeterministicWorkspaceTabId(input.target);
|
||||
const existingTab = input.tabs.find(
|
||||
(tab) => tab.tabId === targetTabId || workspaceTabTargetsEqual(tab.target, input.target),
|
||||
);
|
||||
if (existingTab) {
|
||||
return { kind: "open-in-source" };
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@ import type { JsonValue } from "@getpaseo/protocol/agent-types";
|
||||
import type { WorkspaceTab, WorkspaceTabTarget } from "@/workspace-tabs/model";
|
||||
import { MIN_SPLIT_SIZE } from "@/stores/workspace-layout-constants";
|
||||
import { panelResourceKey, panelSupportsHost } from "@/panels/panel-manifest";
|
||||
import { allocateWorkspaceTabId, defaultWorkspaceLayoutIds } from "@/stores/workspace-layout-ids";
|
||||
import { defaultWorkspaceLayoutIds } from "@/stores/workspace-layout-ids";
|
||||
import type { WorkspaceLayoutNodeIdPrefix } from "@/stores/workspace-layout-ids";
|
||||
import {
|
||||
buildDeterministicWorkspaceTabId,
|
||||
@@ -137,8 +137,6 @@ interface OpenTabInLayoutInput {
|
||||
placement: WorkspaceTabPlacement;
|
||||
/** Required so a new caller cannot silently opt out of Explorer placement rules. */
|
||||
explorerSidebarPaneId: string | null;
|
||||
/** Live sheets share the workspace's panel-instance namespace with its tabs. */
|
||||
reservedTabIds?: ReadonlySet<string>;
|
||||
}
|
||||
|
||||
interface CreateTabInLayoutInput extends OpenTabInLayoutInput {
|
||||
@@ -263,7 +261,6 @@ interface ReorderPaneTabsInLayoutInput {
|
||||
|
||||
export interface WorkspaceTabReconcileState {
|
||||
layout: WorkspaceLayout;
|
||||
reservedTabIds?: ReadonlySet<string>;
|
||||
pinnedAgentIds?: ReadonlySet<string> | null;
|
||||
hiddenAgentIds?: ReadonlySet<string> | null;
|
||||
explorerSidebarPaneId: string | null;
|
||||
@@ -401,11 +398,15 @@ function normalizeWorkspaceTabs(input: unknown): WorkspaceTab[] {
|
||||
if (!Array.isArray(input)) {
|
||||
return [];
|
||||
}
|
||||
// Preserve colliding entries until the whole layout can assign each an identity.
|
||||
const next: WorkspaceTab[] = [];
|
||||
const seen = new Set<string>();
|
||||
for (const value of input) {
|
||||
const tab = normalizeWorkspaceTab(value);
|
||||
if (tab) next.push(tab);
|
||||
if (!tab || seen.has(tab.tabId)) {
|
||||
continue;
|
||||
}
|
||||
seen.add(tab.tabId);
|
||||
next.push(tab);
|
||||
}
|
||||
return next;
|
||||
}
|
||||
@@ -1021,65 +1022,13 @@ function insertSplitInternal(input: InsertSplitInternalInput): InsertSplitIntern
|
||||
};
|
||||
}
|
||||
|
||||
function repairDuplicateTabIds(root: SplitNodeInternal): {
|
||||
root: SplitNodeInternal;
|
||||
ambiguousIds: ReadonlySet<string>;
|
||||
} {
|
||||
const keepers = new Map<string, WorkspaceTab>();
|
||||
const ambiguousIds = new Set<string>();
|
||||
for (const tab of collectAllTabs(root)) {
|
||||
const keeper = keepers.get(tab.tabId);
|
||||
if (!keeper) {
|
||||
keepers.set(tab.tabId, tab);
|
||||
continue;
|
||||
}
|
||||
ambiguousIds.add(tab.tabId);
|
||||
if (
|
||||
buildDeterministicWorkspaceTabId(tab.target) === tab.tabId &&
|
||||
buildDeterministicWorkspaceTabId(keeper.target) !== keeper.tabId
|
||||
) {
|
||||
keepers.set(tab.tabId, tab);
|
||||
}
|
||||
}
|
||||
if (ambiguousIds.size === 0) return { root, ambiguousIds };
|
||||
|
||||
// Reserve every original id before assigning replacements, including hidden panes.
|
||||
const occupiedIds = new Set(keepers.keys());
|
||||
function repair(node: SplitNodeInternal): SplitNodeInternal {
|
||||
if (node.kind === "group") {
|
||||
return { ...node, group: { ...node.group, children: node.group.children.map(repair) } };
|
||||
}
|
||||
const focusedCandidates = node.pane.tabs.filter((tab) => tab.tabId === node.pane.focusedTabId);
|
||||
const focusedTab =
|
||||
focusedCandidates.find((tab) => keepers.get(tab.tabId) === tab) ?? focusedCandidates[0];
|
||||
let focusedTabId = node.pane.focusedTabId;
|
||||
const tabs = node.pane.tabs.map((tab) => {
|
||||
if (keepers.get(tab.tabId) === tab) return tab;
|
||||
const tabId = allocateWorkspaceTabId(
|
||||
buildDeterministicWorkspaceTabId(tab.target),
|
||||
occupiedIds,
|
||||
);
|
||||
occupiedIds.add(tabId);
|
||||
if (tab === focusedTab) focusedTabId = tabId;
|
||||
return { ...tab, tabId };
|
||||
});
|
||||
return {
|
||||
...node,
|
||||
pane: { ...node.pane, tabs, tabIds: tabs.map((tab) => tab.tabId), focusedTabId },
|
||||
};
|
||||
}
|
||||
return { root: repair(root), ambiguousIds };
|
||||
}
|
||||
|
||||
export function normalizeLayout(layout: unknown): WorkspaceLayout {
|
||||
if (!layout || typeof layout !== "object") {
|
||||
return createDefaultLayout();
|
||||
}
|
||||
|
||||
const rawLayout = layout as WorkspaceLayout;
|
||||
const { root, ambiguousIds } = repairDuplicateTabIds(
|
||||
normalizeNode(rawLayout.root) ?? asInternalNode(createDefaultLayout().root),
|
||||
);
|
||||
const root = normalizeNode(rawLayout.root) ?? asInternalNode(createDefaultLayout().root);
|
||||
const focusedPaneId =
|
||||
rawLayout.focusedPaneId === null ? null : trimNonEmpty(rawLayout.focusedPaneId);
|
||||
const resolvedFocusedPaneId =
|
||||
@@ -1098,16 +1047,7 @@ export function normalizeLayout(layout: unknown): WorkspaceLayout {
|
||||
openTabIds: new Set(collectAllTabs(root).map((tab) => tab.tabId)),
|
||||
});
|
||||
|
||||
if (parentTabIdByTabId) {
|
||||
// A duplicated id cannot identify either end of a parent relationship unambiguously.
|
||||
for (const [childId, parentId] of Object.entries(parentTabIdByTabId)) {
|
||||
if (ambiguousIds.has(childId) || ambiguousIds.has(parentId))
|
||||
delete parentTabIdByTabId[childId];
|
||||
}
|
||||
if (Object.keys(parentTabIdByTabId).length > 0)
|
||||
return { ...normalizedLayout, parentTabIdByTabId };
|
||||
}
|
||||
return normalizedLayout;
|
||||
return parentTabIdByTabId ? { ...normalizedLayout, parentTabIdByTabId } : normalizedLayout;
|
||||
}
|
||||
|
||||
export function findPaneById(root: SplitNode, paneId: string | null | undefined): SplitPane | null {
|
||||
@@ -1424,9 +1364,7 @@ function insertNewTabIntoPane(
|
||||
return null;
|
||||
}
|
||||
|
||||
const occupiedIds = new Set(input.reservedTabIds);
|
||||
for (const tab of collectAllTabs(layout.root)) occupiedIds.add(tab.tabId);
|
||||
const tabId = allocateWorkspaceTabId(input.createTabId(), occupiedIds);
|
||||
const tabId = input.createTabId();
|
||||
const nextTab: WorkspaceTab = {
|
||||
tabId,
|
||||
target: input.target,
|
||||
@@ -2346,7 +2284,6 @@ function openEntityTabWithoutFocusing(input: {
|
||||
layout: WorkspaceLayout;
|
||||
target: WorkspaceTabTarget;
|
||||
explorerSidebarPaneId: string | null;
|
||||
reservedTabIds: ReadonlySet<string> | undefined;
|
||||
}): WorkspaceLayout {
|
||||
return (
|
||||
insertNewTabIntoPane({
|
||||
@@ -2355,7 +2292,6 @@ function openEntityTabWithoutFocusing(input: {
|
||||
now: Date.now(),
|
||||
placement: AMBIENT_PLACEMENT,
|
||||
explorerSidebarPaneId: input.explorerSidebarPaneId,
|
||||
reservedTabIds: input.reservedTabIds,
|
||||
createTabId: () => buildDeterministicWorkspaceTabId(input.target),
|
||||
focus: false,
|
||||
})?.layout ?? input.layout
|
||||
@@ -2446,7 +2382,6 @@ function addMissingEntityTabs(input: {
|
||||
hasActivePendingTerminalCreate: boolean;
|
||||
hasActivePendingDraftCreate: boolean;
|
||||
explorerSidebarPaneId: string | null;
|
||||
reservedTabIds: ReadonlySet<string> | undefined;
|
||||
}): WorkspaceLayout {
|
||||
const {
|
||||
autoOpenAgentIds,
|
||||
@@ -2477,7 +2412,6 @@ function addMissingEntityTabs(input: {
|
||||
layout: nextLayout,
|
||||
target: { kind: "agent", agentId },
|
||||
explorerSidebarPaneId,
|
||||
reservedTabIds: input.reservedTabIds,
|
||||
});
|
||||
currentAgentIds.add(agentId);
|
||||
}
|
||||
@@ -2492,7 +2426,6 @@ function addMissingEntityTabs(input: {
|
||||
layout: nextLayout,
|
||||
target: { kind: "terminal", terminalId },
|
||||
explorerSidebarPaneId,
|
||||
reservedTabIds: input.reservedTabIds,
|
||||
});
|
||||
currentTerminalIds.add(terminalId);
|
||||
}
|
||||
@@ -2592,7 +2525,6 @@ export function reconcileWorkspaceTabs(
|
||||
hasActivePendingTerminalCreate: snapshot.hasActivePendingTerminalCreate ?? false,
|
||||
hasActivePendingDraftCreate: snapshot.hasActivePendingDraftCreate ?? false,
|
||||
explorerSidebarPaneId: state.explorerSidebarPaneId,
|
||||
reservedTabIds: state.reservedTabIds,
|
||||
});
|
||||
|
||||
if (reconciledFocusedTabId) {
|
||||
|
||||
@@ -11,22 +11,6 @@ function createRandomIdValue(): string {
|
||||
: `${Date.now()}-${Math.random().toString(16).slice(2)}`;
|
||||
}
|
||||
|
||||
export function createWorkspaceTabInstanceId(): string {
|
||||
return `tab_${createRandomIdValue()}`;
|
||||
}
|
||||
|
||||
/** A resource-derived id may still belong to a preview slot showing another target. */
|
||||
export function allocateWorkspaceTabId(
|
||||
preferredId: string,
|
||||
occupiedIds: ReadonlySet<string>,
|
||||
): string {
|
||||
let tabId = preferredId;
|
||||
for (let suffix = 2; occupiedIds.has(tabId); suffix += 1) {
|
||||
tabId = `${preferredId}:${suffix}`;
|
||||
}
|
||||
return tabId;
|
||||
}
|
||||
|
||||
export const defaultWorkspaceLayoutIds: WorkspaceLayoutIdSource = {
|
||||
createNodeId: (prefix) => `${prefix}_${createRandomIdValue()}`,
|
||||
createFocusRestorationToken: () => `workspace-focus-${createRandomIdValue()}`,
|
||||
|
||||
@@ -59,84 +59,6 @@ it("skips unchanged reconciliations and immediately saves real layout changes",
|
||||
);
|
||||
});
|
||||
|
||||
it("hydrates a saved preview collision and persists the repaired identities", async () => {
|
||||
const workspaceKey = "server:workspace";
|
||||
const duplicateId = "file_a.ts";
|
||||
const values = new Map([
|
||||
[
|
||||
"workspace-layout-state",
|
||||
JSON.stringify({
|
||||
version: 2,
|
||||
state: {
|
||||
layoutByWorkspace: {
|
||||
[workspaceKey]: {
|
||||
root: {
|
||||
kind: "group",
|
||||
group: {
|
||||
id: "split",
|
||||
direction: "horizontal",
|
||||
sizes: [0.5, 0.5],
|
||||
children: [
|
||||
{ id: "main", path: "b.ts" },
|
||||
{ id: "right", path: "a.ts" },
|
||||
].map(({ id, path }) => ({
|
||||
kind: "pane",
|
||||
pane: {
|
||||
id,
|
||||
tabIds: [duplicateId],
|
||||
focusedTabId: duplicateId,
|
||||
tabs: [{ tabId: duplicateId, target: { kind: "file", path }, createdAt: 1 }],
|
||||
},
|
||||
})),
|
||||
},
|
||||
},
|
||||
focusedPaneId: "right",
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
],
|
||||
]);
|
||||
const storage: StateStorage = {
|
||||
getItem: (name) => values.get(name) ?? null,
|
||||
setItem: (name, value) => {
|
||||
values.set(name, value);
|
||||
},
|
||||
removeItem: (name) => {
|
||||
values.delete(name);
|
||||
},
|
||||
};
|
||||
const store = createWorkspaceLayoutStore(undefined, storage);
|
||||
await store.persist.rehydrate();
|
||||
const layout = store.getState().layoutByWorkspace[workspaceKey];
|
||||
const tabs = collectAllTabs(layout.root);
|
||||
|
||||
expect(tabs.filter((tab) => tab.target.kind === "file").map((tab) => tab.tabId)).toEqual([
|
||||
"file_b.ts",
|
||||
"file_a.ts",
|
||||
]);
|
||||
expect(
|
||||
deriveWorkspacePaneState({ layout, tabs, paneId: "main" }).activeTab?.descriptor.target,
|
||||
).toEqual({
|
||||
kind: "file",
|
||||
path: "b.ts",
|
||||
});
|
||||
expect(
|
||||
deriveWorkspacePaneState({ layout, tabs, paneId: "right" }).activeTab?.descriptor.target,
|
||||
).toEqual({
|
||||
kind: "file",
|
||||
path: "a.ts",
|
||||
});
|
||||
store.getState().focusTab(workspaceKey, "file_b.ts");
|
||||
expect(store.getState().layoutByWorkspace[workspaceKey].focusedPaneId).toBe("main");
|
||||
|
||||
const reloaded = createWorkspaceLayoutStore(undefined, storage);
|
||||
await reloaded.persist.rehydrate();
|
||||
expect(reloaded.getState().layoutByWorkspace[workspaceKey]).toEqual(
|
||||
store.getState().layoutByWorkspace[workspaceKey],
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps the saved layout when the shell publishes its layout mode before hydration", async () => {
|
||||
const values = new Map<string, string>();
|
||||
const storage: StateStorage = {
|
||||
|
||||
@@ -906,91 +906,6 @@ describe("workspace-layout-store actions", () => {
|
||||
).toEqual(override);
|
||||
});
|
||||
|
||||
it("keeps reused file tabs unique and focuses the matching split pane", () => {
|
||||
const workspaceKey = createWorkspaceKey();
|
||||
const store = workspaceLayoutStore.getState();
|
||||
const firstTabId = store.openTab({
|
||||
workspaceKey,
|
||||
target: { kind: "file", path: "src/a.ts" },
|
||||
intent: "reveal",
|
||||
})!;
|
||||
store.replaceTab(workspaceKey, firstTabId, { kind: "file", path: "src/b.ts" });
|
||||
const rightPaneId = store.splitPaneEmpty(workspaceKey, {
|
||||
targetPaneId: "main",
|
||||
position: "right",
|
||||
});
|
||||
if (!rightPaneId) throw new Error("Expected a right split pane");
|
||||
const rightTabId = store.openTab({
|
||||
workspaceKey,
|
||||
target: { kind: "file", path: "src/a.ts" },
|
||||
intent: "reveal",
|
||||
placement: { mode: "pane", paneId: rightPaneId },
|
||||
})!;
|
||||
|
||||
store.openTab({
|
||||
workspaceKey,
|
||||
target: { kind: "file", path: "src/b.ts" },
|
||||
intent: "reveal",
|
||||
});
|
||||
store.focusTab(workspaceKey, rightTabId);
|
||||
|
||||
const layout = workspaceLayoutStore.getState().layoutByWorkspace[workspaceKey];
|
||||
const fileTabs = collectAllTabs(layout.root).filter((tab) => tab.target.kind === "file");
|
||||
expect({
|
||||
fileTabCount: fileTabs.length,
|
||||
uniqueFileTabCount: new Set(fileTabs.map((tab) => tab.tabId)).size,
|
||||
fileTargets: fileTabs.map((tab) => tab.target),
|
||||
focusedPaneId: layout.focusedPaneId,
|
||||
}).toEqual({
|
||||
fileTabCount: 2,
|
||||
uniqueFileTabCount: 2,
|
||||
fileTargets: [
|
||||
{ kind: "file", path: "src/b.ts" },
|
||||
{ kind: "file", path: "src/a.ts" },
|
||||
],
|
||||
focusedPaneId: rightPaneId,
|
||||
});
|
||||
});
|
||||
|
||||
it("allocates distinct ids across retained tabs, sheets, and background opens", () => {
|
||||
const workspaceKey = createWorkspaceKey();
|
||||
const layoutStore = createWorkspaceLayoutStore(workspaceLayoutIds);
|
||||
const store = layoutStore.getState();
|
||||
const fileTabId = store.openTab({
|
||||
workspaceKey,
|
||||
target: { kind: "file", path: "src/a.ts" },
|
||||
intent: "reveal",
|
||||
})!;
|
||||
store.replaceTab(workspaceKey, fileTabId, { kind: "file", path: "src/b.ts" });
|
||||
layoutStore.setState({ layoutMode: "compact" });
|
||||
const sheetTabId = store.openTab({
|
||||
workspaceKey,
|
||||
target: { kind: "file", path: "src/a.ts" },
|
||||
intent: "reveal",
|
||||
})!;
|
||||
const selectedSheet = selectSheetTab(layoutStore.getState(), {
|
||||
workspaceKey,
|
||||
target: { kind: "file", path: "src/a.ts" },
|
||||
});
|
||||
expect(selectedSheet?.tab.tabId).toBe(sheetTabId);
|
||||
const backgroundTabId = store.openTab({
|
||||
workspaceKey,
|
||||
target: { kind: "file", path: "src/a.ts" },
|
||||
intent: "background",
|
||||
})!;
|
||||
|
||||
expect(new Set([fileTabId, sheetTabId, backgroundTabId]).size).toBe(3);
|
||||
expect(layoutStore.getState().sheetsByWorkspace[workspaceKey]).toHaveLength(1);
|
||||
expect(
|
||||
collectAllTabs(layoutStore.getState().layoutByWorkspace[workspaceKey].root)
|
||||
.filter((tab) => tab.target.kind === "file")
|
||||
.map((tab) => tab.target),
|
||||
).toEqual([
|
||||
{ kind: "file", path: "src/b.ts" },
|
||||
{ kind: "file", path: "src/a.ts" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps the tab instance when a panel receives a same-kind replacement", () => {
|
||||
const workspaceKey = createWorkspaceKey();
|
||||
const store = workspaceLayoutStore.getState();
|
||||
@@ -3285,75 +3200,6 @@ describe("workspace-layout-store actions", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it("repairs persisted duplicate ids without losing tabs, pane focus, or unambiguous parents", () => {
|
||||
const file = (tabId: string, path: string) => ({
|
||||
tabId,
|
||||
target: { kind: "file", path },
|
||||
createdAt: 1,
|
||||
state: { treeVisible: true, treeWidth: 280 },
|
||||
});
|
||||
const leftTabs = [file("file_a.ts", "b.ts"), file("file_a.ts", "c.ts")];
|
||||
const rightTabs = [
|
||||
file("file_a.ts", "a.ts"),
|
||||
file("file_b.ts", "b.ts"),
|
||||
file("file_b.ts:2", "b.ts"),
|
||||
file("child", "child.ts"),
|
||||
file("parent", "parent.ts"),
|
||||
];
|
||||
const layout = normalizeLayout({
|
||||
root: {
|
||||
kind: "group",
|
||||
group: {
|
||||
id: "root",
|
||||
direction: "horizontal",
|
||||
sizes: [0.4, 0.6],
|
||||
children: [
|
||||
{
|
||||
kind: "pane",
|
||||
pane: {
|
||||
id: "main",
|
||||
tabs: leftTabs,
|
||||
tabIds: leftTabs.map((tab) => tab.tabId),
|
||||
focusedTabId: "file_a.ts",
|
||||
},
|
||||
},
|
||||
{
|
||||
kind: "pane",
|
||||
pane: {
|
||||
id: "right",
|
||||
tabs: rightTabs,
|
||||
tabIds: rightTabs.map((tab) => tab.tabId),
|
||||
focusedTabId: "file_a.ts",
|
||||
hidden: true,
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
focusedPaneId: "main",
|
||||
parentTabIdByTabId: {
|
||||
"file_a.ts": "parent",
|
||||
"file_b.ts": "file_a.ts",
|
||||
child: "parent",
|
||||
},
|
||||
});
|
||||
const tabs = collectAllTabs(layout.root);
|
||||
|
||||
expect(tabs).toHaveLength(7);
|
||||
expect(new Set(tabs.map((tab) => tab.tabId)).size).toBe(7);
|
||||
expect(tabs[0]).toEqual({ ...leftTabs[0], tabId: "file_b.ts:3" });
|
||||
expect(tabs[1]).toEqual({ ...leftTabs[1], tabId: "file_c.ts" });
|
||||
expect(tabs.slice(2)).toEqual(rightTabs);
|
||||
expect(findPaneById(layout.root, "main")?.tabIds).toEqual(["file_b.ts:3", "file_c.ts"]);
|
||||
expect(findPaneById(layout.root, "main")?.focusedTabId).toBe("file_b.ts:3");
|
||||
expect(findPaneById(layout.root, "right")).toMatchObject({
|
||||
hidden: true,
|
||||
focusedTabId: "file_a.ts",
|
||||
});
|
||||
expect(layout.parentTabIdByTabId).toEqual({ child: "parent" });
|
||||
expect(normalizeLayout(layout)).toEqual(layout);
|
||||
});
|
||||
|
||||
it("hydrates duplicate Changes and Pull request instances without collapsing their ids or state", () => {
|
||||
const tabs = [
|
||||
{
|
||||
@@ -5264,50 +5110,6 @@ describe("compact workspace sheet", () => {
|
||||
expect(sheetTargets(store)).toEqual([fileTarget, nextTarget]);
|
||||
});
|
||||
|
||||
it("reserves a retargeted sheet's id when reconciling a new root agent tab", () => {
|
||||
seedAgents([
|
||||
{ id: "root", parentAgentId: null, workspaceId: "sheet-ws" },
|
||||
{ id: "child-a", parentAgentId: "root", workspaceId: "sheet-ws" },
|
||||
{ id: "child-b", parentAgentId: "root", workspaceId: "sheet-ws" },
|
||||
]);
|
||||
const store = createCompactStore();
|
||||
store.getState().openTab({
|
||||
workspaceKey,
|
||||
target: { kind: "agent", agentId: "child-a" },
|
||||
intent: "reveal",
|
||||
});
|
||||
const sheetId = requireTopSheet(store).tab.tabId;
|
||||
store.getState().replaceTab(workspaceKey, sheetId, { kind: "agent", agentId: "child-b" });
|
||||
seedAgents([
|
||||
{ id: "root", parentAgentId: null, workspaceId: "sheet-ws" },
|
||||
{ id: "child-a", parentAgentId: null, workspaceId: "sheet-ws" },
|
||||
{ id: "child-b", parentAgentId: "root", workspaceId: "sheet-ws" },
|
||||
]);
|
||||
|
||||
store.getState().reconcileTabs(workspaceKey, {
|
||||
agentsHydrated: true,
|
||||
terminalsHydrated: true,
|
||||
activeAgentIds: ["root", "child-a", "child-b"],
|
||||
autoOpenAgentIds: ["child-a"],
|
||||
knownTerminalIds: ["term-1"],
|
||||
standaloneTerminalIds: ["term-1"],
|
||||
});
|
||||
const tab = collectAllTabs(store.getState().layoutByWorkspace[workspaceKey].root).find(
|
||||
(candidate) => candidate.target.kind === "agent" && candidate.target.agentId === "child-a",
|
||||
);
|
||||
if (!tab) throw new Error("Expected the root agent's tab");
|
||||
expect(tab.tabId).not.toBe(sheetId);
|
||||
|
||||
store.getState().closeTab(workspaceKey, tab.tabId);
|
||||
expect(requireTopSheet(store).tab).toMatchObject({
|
||||
tabId: sheetId,
|
||||
target: { kind: "agent", agentId: "child-b" },
|
||||
});
|
||||
expect(
|
||||
collectAllTabs(store.getState().layoutByWorkspace[workspaceKey].root),
|
||||
).not.toContainEqual(tab);
|
||||
});
|
||||
|
||||
it("closes the sheet when its agent stops being a subagent, leaving one tab for it", () => {
|
||||
seedAgents([
|
||||
{ id: "root", parentAgentId: null, workspaceId: "sheet-ws" },
|
||||
|
||||
@@ -7,8 +7,6 @@ import { WorkspaceLayoutPersistedStateSchema } from "./workspace-layout-storage"
|
||||
import type { JsonValue } from "@getpaseo/protocol/agent-types";
|
||||
import type { WorkspaceTab, WorkspaceTabTarget } from "@/workspace-tabs/model";
|
||||
import {
|
||||
allocateWorkspaceTabId,
|
||||
createWorkspaceTabInstanceId,
|
||||
defaultWorkspaceLayoutIds,
|
||||
type WorkspaceLayoutIdSource,
|
||||
} from "@/stores/workspace-layout-ids";
|
||||
@@ -433,6 +431,14 @@ function trimNonEmpty(value: string | null | undefined): string | null {
|
||||
return trimmed.length > 0 ? trimmed : null;
|
||||
}
|
||||
|
||||
function createWorkspaceTabInstanceId(): string {
|
||||
const value =
|
||||
typeof globalThis.crypto?.randomUUID === "function"
|
||||
? globalThis.crypto.randomUUID()
|
||||
: `${Date.now()}-${Math.random().toString(16).slice(2)}`;
|
||||
return `tab_${value}`;
|
||||
}
|
||||
|
||||
function addAgentIdToWorkspaceSet(
|
||||
state: Record<string, Set<string>>,
|
||||
workspaceKey: string,
|
||||
@@ -525,10 +531,7 @@ export function selectExplorerSidebarPaneId(
|
||||
*/
|
||||
export function selectSheetTab(
|
||||
state: Pick<WorkspaceLayoutStore, "layoutMode" | "layoutByWorkspace" | "sheetsByWorkspace">,
|
||||
input: Pick<OpenWorkspaceTabInput, "workspaceKey" | "target" | "parentTabId"> & {
|
||||
/** A host outside the sheet stack owns its instance identity. */
|
||||
preferredTabId?: string;
|
||||
},
|
||||
input: Pick<OpenWorkspaceTabInput, "workspaceKey" | "target" | "parentTabId">,
|
||||
): SheetTab | null {
|
||||
const workspaceKey = trimNonEmpty(input.workspaceKey);
|
||||
const target = normalizeWorkspaceTabTarget(input.target);
|
||||
@@ -536,14 +539,9 @@ export function selectSheetTab(
|
||||
const policy = resolveSheetPolicy(state, workspaceKey, target, "reveal");
|
||||
if (!policy) return null;
|
||||
return placeTargetInSheet({
|
||||
occupiedTabIds: collectWorkspaceTabIds(state, workspaceKey),
|
||||
kept: input.preferredTabId
|
||||
? undefined
|
||||
: getSheets(state, workspaceKey).find(
|
||||
(sheet) => panelResourceKey(sheet.tab.target) === panelResourceKey(target),
|
||||
),
|
||||
kept: undefined,
|
||||
target,
|
||||
createTabId: () => input.preferredTabId ?? buildDeterministicWorkspaceTabId(target),
|
||||
intent: "reveal",
|
||||
policy,
|
||||
parentTabId: resolveOpenParentTabId(state, workspaceKey, input.parentTabId),
|
||||
state: undefined,
|
||||
@@ -640,7 +638,6 @@ function getOpenTabPlacement(
|
||||
layout: WorkspaceLayout;
|
||||
placement: WorkspaceTabPlacement;
|
||||
explorerSidebarPaneId: string | null;
|
||||
reservedTabIds: Set<string>;
|
||||
} {
|
||||
const layout = getWorkspaceLayout(state.layoutByWorkspace, workspaceKey);
|
||||
const explorerSidebarPaneId = resolveExplorerSidebarPaneId(
|
||||
@@ -673,7 +670,6 @@ function getOpenTabPlacement(
|
||||
layout,
|
||||
placement: resolvedPlacement,
|
||||
explorerSidebarPaneId,
|
||||
reservedTabIds: new Set(getSheets(state, workspaceKey).map((sheet) => sheet.tab.tabId)),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -819,23 +815,11 @@ function resolveOpenParentTabId(
|
||||
return findSheet(state, workspaceKey, parentTabId)?.parentTabId ?? parentTabId;
|
||||
}
|
||||
|
||||
function collectWorkspaceTabIds(
|
||||
state: Pick<WorkspaceLayoutStore, "layoutByWorkspace" | "sheetsByWorkspace">,
|
||||
workspaceKey: string,
|
||||
): Set<string> {
|
||||
const layout = state.layoutByWorkspace[workspaceKey];
|
||||
return new Set([
|
||||
...(layout ? collectAllTabs(layout.root).map((tab) => tab.tabId) : []),
|
||||
...getSheets(state, workspaceKey).map((sheet) => sheet.tab.tabId),
|
||||
]);
|
||||
}
|
||||
|
||||
function placeTargetInSheet(input: {
|
||||
occupiedTabIds: ReadonlySet<string>;
|
||||
/** The sheet whose tab the target keeps, if any. */
|
||||
kept: SheetTab | undefined;
|
||||
target: WorkspaceTabTarget;
|
||||
createTabId: () => string;
|
||||
intent: WorkspaceTabOpenIntent;
|
||||
policy: CompactSheetPolicy;
|
||||
parentTabId: string | null;
|
||||
state: JsonValue | undefined;
|
||||
@@ -845,7 +829,10 @@ function placeTargetInSheet(input: {
|
||||
}
|
||||
return {
|
||||
tab: {
|
||||
tabId: allocateWorkspaceTabId(input.createTabId(), input.occupiedTabIds),
|
||||
tabId:
|
||||
input.intent === "reveal"
|
||||
? buildDeterministicWorkspaceTabId(input.target)
|
||||
: createWorkspaceTabInstanceId(),
|
||||
target: input.target,
|
||||
createdAt: Date.now(),
|
||||
...(input.state !== undefined ? { state: input.state } : {}),
|
||||
@@ -866,7 +853,6 @@ function promoteSheetToTab(
|
||||
): { tabId: string; patch: Partial<WorkspaceLayoutStore> } | null {
|
||||
const { tab } = sheet;
|
||||
const placement = getOpenTabPlacement(state, workspaceKey, tab.target, FOCUSED_PANE_PLACEMENT);
|
||||
placement.reservedTabIds.delete(tab.tabId);
|
||||
const input = {
|
||||
...placement,
|
||||
target: tab.target,
|
||||
@@ -1136,13 +1122,9 @@ export function createWorkspaceLayoutStore(
|
||||
const sheets = getSheets(get(), normalizedWorkspaceKey);
|
||||
const { keptIndex } = sheetPlacement;
|
||||
const sheet = placeTargetInSheet({
|
||||
occupiedTabIds: collectWorkspaceTabIds(get(), normalizedWorkspaceKey),
|
||||
kept: keptIndex === null ? undefined : sheets[keptIndex],
|
||||
target: normalizedTarget,
|
||||
createTabId: () =>
|
||||
input.intent === "reveal"
|
||||
? buildDeterministicWorkspaceTabId(normalizedTarget)
|
||||
: createWorkspaceTabInstanceId(),
|
||||
intent: input.intent,
|
||||
policy: sheetPlacement.policy,
|
||||
parentTabId,
|
||||
state: input.state,
|
||||
@@ -1724,14 +1706,9 @@ export function createWorkspaceLayoutStore(
|
||||
explorerSidebarPaneId,
|
||||
rawLayout.focusedPaneId,
|
||||
);
|
||||
const sheets = getSheets(state, normalizedWorkspaceKey);
|
||||
const fittingSheets = sheets.filter(
|
||||
(sheet) => !sheetAgentNoLongerFits(normalizedWorkspaceKey, sheet, snapshot),
|
||||
);
|
||||
const nextState = reconcileWorkspaceTabs(
|
||||
{
|
||||
layout: currentLayout,
|
||||
reservedTabIds: new Set(fittingSheets.map((sheet) => sheet.tab.tabId)),
|
||||
pinnedAgentIds: state.pinnedAgentIdsByWorkspace[normalizedWorkspaceKey] ?? null,
|
||||
hiddenAgentIds: state.hiddenAgentIdsByWorkspace[normalizedWorkspaceKey] ?? null,
|
||||
explorerSidebarPaneId,
|
||||
@@ -1753,6 +1730,10 @@ export function createWorkspaceLayoutStore(
|
||||
);
|
||||
}
|
||||
}
|
||||
const sheets = getSheets(state, normalizedWorkspaceKey);
|
||||
const fittingSheets = sheets.filter(
|
||||
(sheet) => !sheetAgentNoLongerFits(normalizedWorkspaceKey, sheet, snapshot),
|
||||
);
|
||||
const sheetAgentGone = fittingSheets.length !== sheets.length;
|
||||
if (
|
||||
state.layoutByWorkspace[normalizedWorkspaceKey] &&
|
||||
|
||||
@@ -138,88 +138,6 @@ describe("useSubagentSheetTab", () => {
|
||||
expect(result.current?.tab.tabId).toBe(tabId);
|
||||
});
|
||||
|
||||
it("keeps an open menu sheet's id when an unrelated reused tab disappears", () => {
|
||||
const row = seedParentWithChild();
|
||||
const store = useWorkspaceLayoutStore.getState();
|
||||
const reusedId = store.openTab({
|
||||
workspaceKey,
|
||||
target: { kind: "agent", agentId: "child" },
|
||||
intent: "reveal",
|
||||
asTab: true,
|
||||
});
|
||||
if (!reusedId) throw new Error("Expected a child tab");
|
||||
store.replaceTab(workspaceKey, reusedId, { kind: "agent", agentId: "other" });
|
||||
store.setLayoutMode("compact");
|
||||
const { result } = renderHook(() => useSubagentSheetTab(workspaceKey, "parent-tab")(row));
|
||||
const sheetId = result.current?.tab.tabId;
|
||||
expect(result.current?.tab.target).toEqual({ kind: "agent", agentId: "child" });
|
||||
expect(sheetId).not.toBe(reusedId);
|
||||
|
||||
act(() => {
|
||||
store.reconcileTabs(workspaceKey, {
|
||||
agentsHydrated: true,
|
||||
terminalsHydrated: true,
|
||||
activeAgentIds: ["parent", "child"],
|
||||
autoOpenAgentIds: [],
|
||||
knownTerminalIds: [],
|
||||
standaloneTerminalIds: [],
|
||||
});
|
||||
});
|
||||
expect(store.getWorkspaceTabs(workspaceKey).map((tab) => tab.tabId)).not.toContain(reusedId);
|
||||
expect(result.current?.tab.tabId).toBe(sheetId);
|
||||
expect(result.current?.tab.target).toEqual({ kind: "agent", agentId: "child" });
|
||||
});
|
||||
|
||||
it("promotes a menu sheet to the subagent's own tab", () => {
|
||||
const row = seedParentWithChild();
|
||||
const store = useWorkspaceLayoutStore.getState();
|
||||
store.setLayoutMode("compact");
|
||||
const { result } = renderHook(() => useSubagentSheetTab(workspaceKey, "parent-tab")(row));
|
||||
const sheet = result.current;
|
||||
if (!sheet) throw new Error("Expected a menu sheet");
|
||||
|
||||
let promotedId: string | null = null;
|
||||
act(() => {
|
||||
promotedId = store.openTabInFront(workspaceKey, sheet);
|
||||
});
|
||||
expect(promotedId).toBe("agent_child");
|
||||
expect(
|
||||
store.getWorkspaceTabs(workspaceKey).filter((tab) => tab.target.kind === "agent"),
|
||||
).toEqual([
|
||||
expect.objectContaining({
|
||||
tabId: "agent_child",
|
||||
target: { kind: "agent", agentId: "child" },
|
||||
}),
|
||||
]);
|
||||
});
|
||||
|
||||
it("does not reuse a menu id retained by a promoted tab showing another target", () => {
|
||||
const row = seedParentWithChild();
|
||||
const store = useWorkspaceLayoutStore.getState();
|
||||
store.setLayoutMode("compact");
|
||||
const { result } = renderHook(() => useSubagentSheetTab(workspaceKey, "parent-tab")(row));
|
||||
const sheet = result.current;
|
||||
if (!sheet) throw new Error("Expected a menu sheet");
|
||||
act(() => {
|
||||
store.openTabInFront(workspaceKey, sheet);
|
||||
});
|
||||
expect(result.current).toBeNull();
|
||||
|
||||
act(() => {
|
||||
store.replaceTab(workspaceKey, sheet.tab.tabId, { kind: "agent", agentId: "other" });
|
||||
});
|
||||
expect(result.current?.tab.target).toEqual({ kind: "agent", agentId: "child" });
|
||||
expect(result.current?.tab.tabId).not.toBe(sheet.tab.tabId);
|
||||
expect(
|
||||
store.getWorkspaceTabs(workspaceKey).filter((tab) => tab.target.kind === "agent"),
|
||||
).toEqual([
|
||||
expect.objectContaining({
|
||||
tabId: sheet.tab.tabId,
|
||||
target: { kind: "agent", agentId: "other" },
|
||||
}),
|
||||
]);
|
||||
});
|
||||
|
||||
it("hands a re-rendered row the same sheet", () => {
|
||||
const row = seedParentWithChild();
|
||||
useWorkspaceLayoutStore.getState().setLayoutMode("compact");
|
||||
|
||||
@@ -4,7 +4,6 @@ import {
|
||||
useWorkspaceLayoutStore,
|
||||
type SheetTab,
|
||||
} from "@/stores/workspace-layout-store";
|
||||
import { buildDeterministicWorkspaceTabId } from "@/workspace-tabs/identity";
|
||||
import type { WorkspaceTabTarget } from "@/workspace-tabs/model";
|
||||
import type { SubagentRow } from "./select";
|
||||
|
||||
@@ -33,9 +32,6 @@ export function useSubagentSheetTab(
|
||||
const sheets = useWorkspaceLayoutStore((state) =>
|
||||
workspaceKey ? state.sheetsByWorkspace[workspaceKey] : undefined,
|
||||
);
|
||||
// Menu pages never enter the sheet stack. Each starts from the subagent's own tab id, so opening
|
||||
// it as a tab lands on that id, and keeps the id it was given across layout updates.
|
||||
const tabIds = useMemo(() => new Map<string, string>(), []);
|
||||
return useMemo(() => {
|
||||
// One answer per row until the state it reads changes, so a re-render of the list hands an
|
||||
// open sheet the same tab rather than a fresh one.
|
||||
@@ -47,19 +43,16 @@ export function useSubagentSheetTab(
|
||||
layoutByWorkspace: layout ? { [workspaceKey]: layout } : {},
|
||||
sheetsByWorkspace: sheets ? { [workspaceKey]: sheets } : {},
|
||||
};
|
||||
const key = JSON.stringify([workspaceKey, parentTabId, row.kind, row.id]);
|
||||
const key = `${row.kind}:${row.id}`;
|
||||
const known = answers.get(key);
|
||||
if (known !== undefined) return known;
|
||||
const target = subagentRowTarget(row);
|
||||
const sheet = selectSheetTab(state, {
|
||||
workspaceKey,
|
||||
target,
|
||||
target: subagentRowTarget(row),
|
||||
parentTabId,
|
||||
preferredTabId: tabIds.get(key) ?? buildDeterministicWorkspaceTabId(target),
|
||||
});
|
||||
if (sheet) tabIds.set(key, sheet.tab.tabId);
|
||||
answers.set(key, sheet);
|
||||
return sheet;
|
||||
};
|
||||
}, [layout, layoutMode, parentTabId, sheets, tabIds, workspaceKey]);
|
||||
}, [layout, layoutMode, parentTabId, sheets, workspaceKey]);
|
||||
}
|
||||
|
||||
@@ -5,11 +5,9 @@ import {
|
||||
normalizeStoredHostProfile,
|
||||
orderHostsLocalFirst,
|
||||
pinRelayProtectedSecurityInProfiles,
|
||||
readHostRegistry,
|
||||
relayConnectionFromOffer,
|
||||
resolveActiveHostServerId,
|
||||
upsertHostConnectionInProfiles,
|
||||
writeHostRegistry,
|
||||
type HostConnection,
|
||||
type HostProfile,
|
||||
} from "./host-connection";
|
||||
@@ -89,25 +87,6 @@ describe("normalizeStoredHostProfile", () => {
|
||||
expect(profile?.connections[0]).not.toHaveProperty("password");
|
||||
});
|
||||
|
||||
it("drops a connection kind this build doesn't know and keeps the host", () => {
|
||||
const profile = normalizeStoredHostProfile({
|
||||
serverId: "srv_mixed",
|
||||
password: "secret",
|
||||
connections: [
|
||||
{ id: "future:1", type: "futureKind", address: "future.example.com" },
|
||||
{ id: "direct:lan:6767", type: "directTcp", endpoint: "lan:6767", futureField: true },
|
||||
{ id: "direct:remote:6767", type: "directTcp", endpoint: "remote:6767" },
|
||||
],
|
||||
preferredConnectionId: "direct:remote:6767",
|
||||
});
|
||||
|
||||
expect(profile?.password).toBe("secret");
|
||||
expect(profile?.connections).toEqual([
|
||||
{ id: "direct:remote:6767", type: "directTcp", endpoint: "remote:6767", useTls: false },
|
||||
]);
|
||||
expect(profile?.preferredConnectionId).toBe("direct:remote:6767");
|
||||
});
|
||||
|
||||
it("preserves legacy relay ids when TLS is absent", () => {
|
||||
const profile = normalizeStoredHostProfile({
|
||||
serverId: "srv_relay",
|
||||
@@ -198,59 +177,6 @@ describe("normalizeStoredHostProfile", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("readHostRegistry and writeHostRegistry", () => {
|
||||
const direct: HostConnection = {
|
||||
id: "direct:lan:6767",
|
||||
type: "directTcp",
|
||||
endpoint: "lan:6767",
|
||||
useTls: false,
|
||||
};
|
||||
const future = { id: "future:1", type: "futureKind", address: "future.example.com" };
|
||||
|
||||
it("writes back every entry it could not read", () => {
|
||||
const unreadableHost = { serverId: "srv_future", connections: [future] };
|
||||
const hostWithFutureField = { serverId: "srv_field", connections: [direct], futureField: 1 };
|
||||
const stored = [
|
||||
{ ...makeHost("srv_a"), connections: [direct, future] },
|
||||
unreadableHost,
|
||||
hostWithFutureField,
|
||||
"not a host",
|
||||
];
|
||||
|
||||
const { hosts, unreadable } = readHostRegistry(stored);
|
||||
expect(hosts.map((host) => host.serverId)).toEqual(["srv_a"]);
|
||||
expect(hosts[0]?.connections).toEqual([direct]);
|
||||
|
||||
expect(writeHostRegistry(hosts, unreadable)).toEqual([
|
||||
{ ...hosts[0], connections: [direct, future] },
|
||||
unreadableHost,
|
||||
hostWithFutureField,
|
||||
"not a host",
|
||||
]);
|
||||
});
|
||||
|
||||
it("writes a host saved again by this build in place of the entry it could not read", () => {
|
||||
const { hosts, unreadable } = readHostRegistry([{ serverId: "srv_a", connections: [future] }]);
|
||||
expect(hosts).toEqual([]);
|
||||
|
||||
const saved = { ...makeHost("srv_a"), connections: [direct] };
|
||||
expect(writeHostRegistry([saved], unreadable)).toEqual([saved]);
|
||||
});
|
||||
|
||||
it("moves a stored direct TCP password to its host next to a connection it can't read", () => {
|
||||
const registry = readHostRegistry([
|
||||
{
|
||||
serverId: "srv_legacy",
|
||||
connections: [future, { type: "directTcp", endpoint: "lan:6767", password: "old-secret" }],
|
||||
},
|
||||
]);
|
||||
|
||||
expect(registry.movedConnectionPassword).toBe(true);
|
||||
expect(registry.hosts[0]?.password).toBe("old-secret");
|
||||
expect(registry.hosts[0]?.connections).toEqual([direct]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("createRemoteSshHostConnection", () => {
|
||||
it("keeps optional SSH settings absent", () => {
|
||||
expect(createRemoteSshHostConnection({ host: "build-box" })).toEqual({
|
||||
|
||||
@@ -522,12 +522,12 @@ const StoredHostProfileSchema = z.strictObject({
|
||||
label: z.string().optional(),
|
||||
appearance: HostAppearanceSchema.optional(),
|
||||
lifecycle: z.strictObject({}).optional(),
|
||||
// Read one by one, so a connection kind another build wrote skips only that connection.
|
||||
connections: z.array(z.unknown()).min(1),
|
||||
connections: z.array(StoredHostConnectionSchema).min(1),
|
||||
preferredConnectionId: z.string().nullable().optional(),
|
||||
createdAt: z.string().datetime({ offset: true }).optional(),
|
||||
updatedAt: z.string().datetime({ offset: true }).optional(),
|
||||
});
|
||||
export const StoredHostRegistrySchema = z.array(StoredHostProfileSchema);
|
||||
type StoredHostConnection = z.infer<typeof StoredHostConnectionSchema>;
|
||||
|
||||
function normalizeStoredConnection(connection: StoredHostConnection): HostConnection | null {
|
||||
@@ -590,37 +590,20 @@ function normalizeStoredConnection(connection: StoredHostConnection): HostConnec
|
||||
}
|
||||
|
||||
export function normalizeStoredHostProfile(entry: unknown): HostProfile | null {
|
||||
return readStoredHost(entry)?.profile ?? null;
|
||||
}
|
||||
|
||||
interface StoredHostRead {
|
||||
profile: HostProfile;
|
||||
unreadableConnections: unknown[];
|
||||
movedConnectionPassword: boolean;
|
||||
}
|
||||
|
||||
function readStoredHost(entry: unknown): StoredHostRead | null {
|
||||
const result = StoredHostProfileSchema.safeParse(entry);
|
||||
if (!result.success) {
|
||||
return null;
|
||||
}
|
||||
const record = result.data;
|
||||
const serverId = record.serverId;
|
||||
const storedConnections: StoredHostConnection[] = [];
|
||||
const unreadableConnections: unknown[] = [];
|
||||
for (const stored of record.connections) {
|
||||
const parsed = StoredHostConnectionSchema.safeParse(stored);
|
||||
if (parsed.success) storedConnections.push(parsed.data);
|
||||
else unreadableConnections.push(stored);
|
||||
}
|
||||
// COMPAT(connectionPassword): added in v0.9.1, remove after 2027-03-24 once stored direct passwords have migrated.
|
||||
const legacyPassword = storedConnections.find(
|
||||
const legacyPassword = record.connections.find(
|
||||
(connection) => connection.type === "directTcp" && connection.password,
|
||||
);
|
||||
const password =
|
||||
record.password ?? (legacyPassword?.type === "directTcp" ? legacyPassword.password : undefined);
|
||||
|
||||
const connections = storedConnections
|
||||
const connections = record.connections
|
||||
.map((connection) => normalizeStoredConnection(connection))
|
||||
.filter((connection): connection is HostConnection => connection !== null);
|
||||
if (connections.length === 0) {
|
||||
@@ -637,90 +620,18 @@ function readStoredHost(entry: unknown): StoredHostRead | null {
|
||||
: (connections[0]?.id ?? null);
|
||||
|
||||
return {
|
||||
profile: {
|
||||
serverId,
|
||||
...(password ? { password } : {}),
|
||||
label,
|
||||
appearance: record.appearance ?? defaultHostAppearance(),
|
||||
lifecycle: defaultLifecycle(),
|
||||
connections,
|
||||
preferredConnectionId,
|
||||
createdAt: record.createdAt ?? now,
|
||||
updatedAt: record.updatedAt ?? now,
|
||||
},
|
||||
unreadableConnections,
|
||||
movedConnectionPassword: legacyPassword !== undefined,
|
||||
serverId,
|
||||
...(password ? { password } : {}),
|
||||
label,
|
||||
appearance: record.appearance ?? defaultHostAppearance(),
|
||||
lifecycle: defaultLifecycle(),
|
||||
connections,
|
||||
preferredConnectionId,
|
||||
createdAt: record.createdAt ?? now,
|
||||
updatedAt: record.updatedAt ?? now,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Stored registry entries this build can't read, such as a connection kind added by a newer
|
||||
* build. `writeHostRegistry` writes them back so that build still finds them.
|
||||
*/
|
||||
export interface UnreadableHostEntries {
|
||||
hosts: unknown[];
|
||||
connectionsByServerId: Map<string, unknown[]>;
|
||||
}
|
||||
|
||||
export function readHostRegistry(stored: unknown[]): {
|
||||
hosts: HostProfile[];
|
||||
unreadable: UnreadableHostEntries;
|
||||
// COMPAT(connectionPassword): added in v0.9.1, remove after 2027-03-24 with stored-password migration.
|
||||
movedConnectionPassword: boolean;
|
||||
} {
|
||||
const hosts: HostProfile[] = [];
|
||||
const unreadable: UnreadableHostEntries = { hosts: [], connectionsByServerId: new Map() };
|
||||
let movedConnectionPassword = false;
|
||||
for (const entry of stored) {
|
||||
const read = readStoredHost(entry);
|
||||
if (!read) {
|
||||
unreadable.hosts.push(entry);
|
||||
continue;
|
||||
}
|
||||
hosts.push(read.profile);
|
||||
if (read.unreadableConnections.length > 0) {
|
||||
unreadable.connectionsByServerId.set(read.profile.serverId, read.unreadableConnections);
|
||||
}
|
||||
movedConnectionPassword ||= read.movedConnectionPassword;
|
||||
}
|
||||
return { hosts, unreadable, movedConnectionPassword };
|
||||
}
|
||||
|
||||
export function writeHostRegistry(
|
||||
hosts: HostProfile[],
|
||||
unreadable: UnreadableHostEntries,
|
||||
): unknown[] {
|
||||
const savedServerIds = new Set(hosts.map((host) => host.serverId));
|
||||
const written: unknown[] = hosts.map((host) => {
|
||||
const kept = unreadable.connectionsByServerId.get(host.serverId);
|
||||
return kept ? { ...host, connections: [...host.connections, ...kept] } : host;
|
||||
});
|
||||
for (const entry of unreadable.hosts) {
|
||||
// A host this build saved again replaces the entry it couldn't read.
|
||||
const serverId = readStoredServerId(entry);
|
||||
if (serverId === null || !savedServerIds.has(serverId)) written.push(entry);
|
||||
}
|
||||
return written;
|
||||
}
|
||||
|
||||
/** Drops the entries this build couldn't read for a host you removed. */
|
||||
export function forgetUnreadableHost(
|
||||
unreadable: UnreadableHostEntries,
|
||||
serverId: string,
|
||||
): UnreadableHostEntries {
|
||||
const connectionsByServerId = new Map(unreadable.connectionsByServerId);
|
||||
connectionsByServerId.delete(serverId);
|
||||
return {
|
||||
hosts: unreadable.hosts.filter((entry) => readStoredServerId(entry) !== serverId),
|
||||
connectionsByServerId,
|
||||
};
|
||||
}
|
||||
|
||||
function readStoredServerId(entry: unknown): string | null {
|
||||
if (typeof entry !== "object" || entry === null || !("serverId" in entry)) return null;
|
||||
return typeof entry.serverId === "string" ? entry.serverId.trim() : null;
|
||||
}
|
||||
|
||||
export function hostHasConnection(host: HostProfile, connection: HostConnection): boolean {
|
||||
return host.connections.some((existing) => hostConnectionEquals(existing, connection));
|
||||
}
|
||||
|
||||
@@ -1,64 +0,0 @@
|
||||
import type { Page } from "@playwright/test";
|
||||
import { test, expect } from "../../app/e2e/support/fixtures";
|
||||
import { gotoAppShell } from "../../app/e2e/support/helpers/app";
|
||||
|
||||
// Windows and Linux draw their window controls top-right, so the desktop sidebar has no
|
||||
// chrome row of its own. Its window-drag surface is the strip above the navigation rows.
|
||||
const CUSTOM_CHROME_HOSTS = [
|
||||
{ platform: "linux", windowChromeMode: "custom-linux" },
|
||||
{ platform: "win32", windowChromeMode: "custom-windows" },
|
||||
] as const;
|
||||
|
||||
async function installDesktopHost(
|
||||
page: Page,
|
||||
host: (typeof CUSTOM_CHROME_HOSTS)[number],
|
||||
): Promise<void> {
|
||||
await page.addInitScript((desktopHost) => {
|
||||
window.paseoDesktop = {
|
||||
...desktopHost,
|
||||
events: { on: () => () => {} },
|
||||
invoke: async (command: string) => {
|
||||
if (command === "get_desktop_settings") {
|
||||
return {
|
||||
releaseChannel: "stable",
|
||||
daemon: { manageBuiltInDaemon: true, keepRunningAfterQuit: true },
|
||||
};
|
||||
}
|
||||
return null;
|
||||
},
|
||||
};
|
||||
}, host);
|
||||
}
|
||||
|
||||
async function sidebarDragGeometry(page: Page) {
|
||||
const navScroll = page.locator('[data-testid="sidebar-nav-scroll"]:visible').first();
|
||||
await expect(navScroll).toBeVisible();
|
||||
return navScroll.evaluate((node) => {
|
||||
const nav = node.getBoundingClientRect();
|
||||
const dragRegions = [];
|
||||
for (const element of document.querySelectorAll<HTMLElement>("*")) {
|
||||
if (getComputedStyle(element).getPropertyValue("-webkit-app-region") !== "drag") continue;
|
||||
const rect = element.getBoundingClientRect();
|
||||
const overSidebar = rect.left < nav.right && rect.right > nav.left;
|
||||
if (overSidebar && rect.height > 0) dragRegions.push({ top: rect.top, bottom: rect.bottom });
|
||||
}
|
||||
return { navTop: nav.top, navBottom: nav.bottom, dragRegions };
|
||||
});
|
||||
}
|
||||
|
||||
for (const host of CUSTOM_CHROME_HOSTS) {
|
||||
test.describe(`Desktop sidebar on ${host.platform}`, () => {
|
||||
test.use({ viewport: { width: 1280, height: 480 } });
|
||||
|
||||
test("keeps a window drag strip above the scrolling navigation", async ({ page }) => {
|
||||
await installDesktopHost(page, host);
|
||||
await gotoAppShell(page);
|
||||
|
||||
const geometry = await sidebarDragGeometry(page);
|
||||
expect(geometry.dragRegions).not.toEqual([]);
|
||||
for (const region of geometry.dragRegions) {
|
||||
expect(region.bottom).toBeLessThanOrEqual(geometry.navTop + 1);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -14,19 +14,18 @@ const BASE_RECORD: StoredAgentRecord = {
|
||||
config: null,
|
||||
};
|
||||
|
||||
const ARCHIVE = {
|
||||
archivedAt: "2025-01-03T00:00:00.000Z",
|
||||
updatedAt: "2025-01-03T00:00:00.000Z",
|
||||
};
|
||||
|
||||
test("archives a stored agent without changing terminal statuses", () => {
|
||||
const statuses: Array<StoredAgentRecord["lastStatus"]> = ["idle", "error", "closed"];
|
||||
|
||||
for (const status of statuses) {
|
||||
const archived = buildArchivedAgentRecord({ ...BASE_RECORD, lastStatus: status }, ARCHIVE);
|
||||
const archived = buildArchivedAgentRecord(
|
||||
{ ...BASE_RECORD, lastStatus: status },
|
||||
{ archivedAt: "2025-01-03T00:00:00.000Z" },
|
||||
);
|
||||
|
||||
expect(archived.lastStatus).toBe(status);
|
||||
expect(archived.archivedAt).toBe("2025-01-03T00:00:00.000Z");
|
||||
expect(archived.updatedAt).toBe(BASE_RECORD.updatedAt);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -34,7 +33,10 @@ test("archives busy stored agents as idle", () => {
|
||||
const statuses: Array<StoredAgentRecord["lastStatus"]> = ["initializing", "running"];
|
||||
|
||||
for (const status of statuses) {
|
||||
const archived = buildArchivedAgentRecord({ ...BASE_RECORD, lastStatus: status }, ARCHIVE);
|
||||
const archived = buildArchivedAgentRecord(
|
||||
{ ...BASE_RECORD, lastStatus: status },
|
||||
{ archivedAt: "2025-01-03T00:00:00.000Z" },
|
||||
);
|
||||
|
||||
expect(archived.lastStatus).toBe("idle");
|
||||
}
|
||||
@@ -48,7 +50,7 @@ test("clears persisted attention when archiving", () => {
|
||||
attentionReason: "finished",
|
||||
attentionTimestamp: "2025-01-02T12:00:00.000Z",
|
||||
},
|
||||
ARCHIVE,
|
||||
{ archivedAt: "2025-01-03T00:00:00.000Z" },
|
||||
);
|
||||
|
||||
expect(archived).toMatchObject({
|
||||
@@ -58,19 +60,11 @@ test("clears persisted attention when archiving", () => {
|
||||
});
|
||||
});
|
||||
|
||||
test("moves updatedAt to the archive time", () => {
|
||||
const archived = buildArchivedAgentRecord(BASE_RECORD, ARCHIVE);
|
||||
test("can stamp updatedAt to the archive timestamp", () => {
|
||||
const archived = buildArchivedAgentRecord(BASE_RECORD, {
|
||||
archivedAt: "2025-01-03T00:00:00.000Z",
|
||||
updatedAt: "2025-01-03T00:00:00.000Z",
|
||||
});
|
||||
|
||||
expect(archived.updatedAt).toBe("2025-01-03T00:00:00.000Z");
|
||||
});
|
||||
|
||||
test("keeps a later updatedAt when the archive time is earlier", () => {
|
||||
// Putting an original archive back after a failed unarchive must not move updatedAt backwards.
|
||||
const archived = buildArchivedAgentRecord(
|
||||
{ ...BASE_RECORD, updatedAt: "2025-01-04T00:00:00.000Z" },
|
||||
ARCHIVE,
|
||||
);
|
||||
|
||||
expect(archived.archivedAt).toBe("2025-01-03T00:00:00.000Z");
|
||||
expect(archived.updatedAt).toBe("2025-01-04T00:00:00.000Z");
|
||||
});
|
||||
|
||||
@@ -3,19 +3,19 @@ import type { StoredAgentRecord } from "./agent-storage.js";
|
||||
export type ArchivedStoredAgentRecord = StoredAgentRecord & { archivedAt: string };
|
||||
|
||||
interface BuildArchivedAgentRecordOptions {
|
||||
archivedAt: string;
|
||||
/** When this archive happened. Re-archiving keeps the original archivedAt but still records it. */
|
||||
updatedAt: string;
|
||||
archivedAt?: string;
|
||||
updatedAt?: string;
|
||||
}
|
||||
|
||||
export function buildArchivedAgentRecord(
|
||||
record: StoredAgentRecord,
|
||||
options: BuildArchivedAgentRecordOptions,
|
||||
options?: BuildArchivedAgentRecordOptions,
|
||||
): ArchivedStoredAgentRecord {
|
||||
const archivedAt = options?.archivedAt ?? new Date().toISOString();
|
||||
return {
|
||||
...record,
|
||||
archivedAt: options.archivedAt,
|
||||
updatedAt: latestTimestamp(record.updatedAt, options.updatedAt),
|
||||
archivedAt,
|
||||
updatedAt: options?.updatedAt ?? record.updatedAt,
|
||||
lastStatus: normalizeArchivedStatus(record.lastStatus),
|
||||
requiresAttention: false,
|
||||
attentionReason: null,
|
||||
@@ -23,13 +23,6 @@ export function buildArchivedAgentRecord(
|
||||
};
|
||||
}
|
||||
|
||||
// Archiving is the agent's latest change. An earlier archive time (an original archive put back
|
||||
// after a failed unarchive) keeps the newer updatedAt, since clients drop an agent update that is
|
||||
// older than the one they hold.
|
||||
function latestTimestamp(current: string, archiveTime: string): string {
|
||||
return Date.parse(archiveTime) > Date.parse(current) ? archiveTime : current;
|
||||
}
|
||||
|
||||
function normalizeArchivedStatus(
|
||||
status: StoredAgentRecord["lastStatus"],
|
||||
): StoredAgentRecord["lastStatus"] {
|
||||
|
||||
@@ -6494,114 +6494,6 @@ test("archiveSnapshot dispatches archived state for stored-only agents", async (
|
||||
expect(last.lifecycle).toBe("closed");
|
||||
});
|
||||
|
||||
test("archiveSnapshot moves a stored-only agent's updatedAt to its archive time, as a live archive does", async () => {
|
||||
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-archive-snapshot-updated-at-"));
|
||||
const storage = new AgentStorage(join(workdir, "agents"), logger);
|
||||
const manager = new AgentManager({
|
||||
clients: { codex: new TestAgentClient() },
|
||||
registry: storage,
|
||||
logger,
|
||||
});
|
||||
|
||||
const created = await manager.createAgent(
|
||||
{ provider: "codex", cwd: workdir, title: "Stored archive updatedAt" },
|
||||
undefined,
|
||||
{ workspaceId: undefined },
|
||||
);
|
||||
await manager.closeAgent(created.id);
|
||||
const before = await storage.get(created.id);
|
||||
expect(before?.updatedAt).toEqual(expect.any(String));
|
||||
|
||||
// Later than anything the agent did: lists sorted by updated_at put it first, as they do
|
||||
// for an agent archived while loaded.
|
||||
const archivedAt = new Date(Date.parse(before!.updatedAt) + 60_000).toISOString();
|
||||
const archived = await manager.archiveSnapshot(created.id, archivedAt);
|
||||
|
||||
expect(archived.updatedAt).toBe(archivedAt);
|
||||
expect((await storage.get(created.id))?.updatedAt).toBe(archivedAt);
|
||||
});
|
||||
|
||||
test("archiveSnapshot restoring an earlier archive time keeps updatedAt at the unarchive", async () => {
|
||||
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-archive-snapshot-restore-"));
|
||||
const storage = new AgentStorage(join(workdir, "agents"), logger);
|
||||
const manager = new AgentManager({
|
||||
clients: { codex: new TestAgentClient() },
|
||||
registry: storage,
|
||||
logger,
|
||||
});
|
||||
|
||||
const created = await manager.createAgent(
|
||||
{ provider: "codex", cwd: workdir, title: "Restore archive updatedAt" },
|
||||
undefined,
|
||||
{ workspaceId: undefined },
|
||||
);
|
||||
await manager.closeAgent(created.id);
|
||||
const originalArchivedAt = (await manager.archiveSnapshot(created.id, new Date().toISOString()))
|
||||
.archivedAt!;
|
||||
await new Promise((resolve) => setTimeout(resolve, 5));
|
||||
await manager.unarchiveSnapshot(created.id);
|
||||
const unarchivedAt = (await storage.get(created.id))!.updatedAt;
|
||||
|
||||
const events: ManagedAgent[] = [];
|
||||
manager.subscribe(
|
||||
(event) => {
|
||||
if (event.type === "agent_state" && event.agent.id === created.id) {
|
||||
events.push(event.agent);
|
||||
}
|
||||
},
|
||||
{ agentId: created.id, replayState: false },
|
||||
);
|
||||
|
||||
// A send that could not load the agent puts its original archive back.
|
||||
await manager.archiveSnapshot(created.id, originalArchivedAt);
|
||||
|
||||
// Clients keep the newer of two updates, so an older updatedAt would leave them showing it active.
|
||||
const stored = await storage.get(created.id);
|
||||
expect(stored?.archivedAt).toBe(originalArchivedAt);
|
||||
expect(stored?.updatedAt).toBe(unarchivedAt);
|
||||
expect(events.at(-1)?.updatedAt.toISOString()).toBe(unarchivedAt);
|
||||
});
|
||||
|
||||
test("archiveSnapshot restoring an earlier archive time on a loaded agent keeps updatedAt at the unarchive", async () => {
|
||||
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-archive-snapshot-restore-loaded-"));
|
||||
const storage = new AgentStorage(join(workdir, "agents"), logger);
|
||||
const manager = new AgentManager({
|
||||
clients: { codex: new TestAgentClient() },
|
||||
registry: storage,
|
||||
logger,
|
||||
});
|
||||
|
||||
const created = await manager.createAgent(
|
||||
{ provider: "codex", cwd: workdir, title: "Restore loaded archive updatedAt" },
|
||||
undefined,
|
||||
{ workspaceId: undefined },
|
||||
);
|
||||
const { archivedAt: originalArchivedAt } = await manager.archiveAgent(created.id);
|
||||
await new Promise((resolve) => setTimeout(resolve, 5));
|
||||
await manager.unarchiveSnapshot(created.id);
|
||||
const unarchivedAt = Date.parse((await storage.get(created.id))!.updatedAt);
|
||||
// The send resumed the agent before a later loading step failed, so it is still loaded.
|
||||
await ensureAgentLoaded(created.id, { agentManager: manager, agentStorage: storage, logger });
|
||||
expect(manager.getAgent(created.id)).not.toBeNull();
|
||||
|
||||
const events: ManagedAgent[] = [];
|
||||
manager.subscribe(
|
||||
(event) => {
|
||||
if (event.type === "agent_state" && event.agent.id === created.id) {
|
||||
events.push(event.agent);
|
||||
}
|
||||
},
|
||||
{ agentId: created.id, replayState: false },
|
||||
);
|
||||
|
||||
await manager.archiveSnapshot(created.id, originalArchivedAt);
|
||||
|
||||
const stored = await storage.get(created.id);
|
||||
expect(stored?.archivedAt).toBe(originalArchivedAt);
|
||||
expect(Date.parse(stored!.updatedAt)).toBeGreaterThanOrEqual(unarchivedAt);
|
||||
expect(events.at(-1)?.updatedAt.getTime()).toBeGreaterThanOrEqual(unarchivedAt);
|
||||
});
|
||||
|
||||
test("markAgentUnread restores error attention on a read errored agent", async () => {
|
||||
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-mark-unread-error-"));
|
||||
const storage = new AgentStorage(join(workdir, "agents"), logger);
|
||||
@@ -14714,16 +14606,14 @@ test("workspace archive preserves a loaded history agent stamp and stamps cascad
|
||||
labels: { [PARENT_AGENT_ID_LABEL]: parent.id },
|
||||
workspaceId: undefined,
|
||||
});
|
||||
// Archive stamps are taken when the archive happens, so they follow the agents' activity.
|
||||
const stamp = new Date(Date.now() + 60_000).toISOString();
|
||||
const laterStamp = new Date(Date.now() + 120_000).toISOString();
|
||||
const stamp = "2026-11-09T00:00:00.000Z";
|
||||
await manager.archiveAgent(parent.id, stamp);
|
||||
expect((await storage.get(parent.id))?.archivedAt).toBe(stamp);
|
||||
expect((await storage.get(child.id))?.archivedAt).toBe(stamp);
|
||||
await ensureAgentLoaded(parent.id, { agentManager: manager, agentStorage: storage, logger });
|
||||
await manager.archiveAgent(parent.id, laterStamp);
|
||||
await manager.archiveAgent(parent.id, "2026-11-09T01:00:00.000Z");
|
||||
expect((await storage.get(parent.id))?.archivedAt).toBe(stamp);
|
||||
expect((await storage.get(parent.id))?.updatedAt).toBe(laterStamp);
|
||||
expect((await storage.get(parent.id))?.updatedAt).toBe("2026-11-09T01:00:00.000Z");
|
||||
} finally {
|
||||
await storage.flush();
|
||||
rmSync(workdir, { recursive: true, force: true });
|
||||
|
||||
@@ -2350,7 +2350,7 @@ export class AgentManager {
|
||||
|
||||
private async persistArchivedRecord(
|
||||
record: StoredAgentRecord,
|
||||
options: { archivedAt: string; updatedAt: string },
|
||||
options: { archivedAt: string; updatedAt?: string },
|
||||
): Promise<ArchivedStoredAgentRecord> {
|
||||
const archivedRecord = buildArchivedAgentRecord(record, options);
|
||||
await this.requireRegistry().upsert(archivedRecord);
|
||||
@@ -2870,11 +2870,7 @@ export class AgentManager {
|
||||
throw new Error(`Agent not found: ${agentId}`);
|
||||
}
|
||||
|
||||
// Archiving is the agent's latest change, as markRecordArchived records it for a loaded agent.
|
||||
const nextRecord = await this.persistArchivedRecord(record, {
|
||||
archivedAt,
|
||||
updatedAt: archivedAt,
|
||||
});
|
||||
const nextRecord = await this.persistArchivedRecord(record, { archivedAt });
|
||||
|
||||
await this.syncNativeArchiveState(record.provider, record.persistence, "archive");
|
||||
|
||||
|
||||
@@ -2437,36 +2437,6 @@ describe("Codex app-server provider", () => {
|
||||
appServer.assertNoErrors();
|
||||
});
|
||||
|
||||
test("lets idle cleanup release a session opened only to read its history", async () => {
|
||||
let spawns = 0;
|
||||
const appServer = createFakeCodexAppServer({
|
||||
"thread/resume": () =>
|
||||
Promise.reject(new Error(archivedThreadErrorMessage("archived-thread-id"))),
|
||||
"thread/read": () => ({ thread: { turns: [] } }),
|
||||
});
|
||||
const provider = new CodexAppServerAgentClient(createTestLogger(), undefined, {
|
||||
appServerProcess: createFakeCodexAppServerProcess(() => {
|
||||
spawns += 1;
|
||||
return appServer.child;
|
||||
}),
|
||||
});
|
||||
const internals = castInternals<{
|
||||
goalsEnabledPromise: Promise<boolean> | null;
|
||||
autoReviewEnabledPromise: Promise<boolean> | null;
|
||||
}>(provider);
|
||||
internals.goalsEnabledPromise = Promise.resolve(false);
|
||||
internals.autoReviewEnabledPromise = Promise.resolve(false);
|
||||
|
||||
const session = await provider.resumeSession(archivedThreadHandle(), undefined, undefined, {
|
||||
purpose: "history",
|
||||
});
|
||||
|
||||
expect(await session.canStopRuntime!()).toBe(true);
|
||||
expect(spawns).toBe(1);
|
||||
await session.close();
|
||||
appServer.assertNoErrors();
|
||||
});
|
||||
|
||||
test("unarchives Codex when an active Paseo agent resumes an archived thread", async () => {
|
||||
const threadRequests: string[] = [];
|
||||
let resumeAttempts = 0;
|
||||
|
||||
@@ -5385,8 +5385,6 @@ export class CodexAppServerAgentSession implements AgentSession {
|
||||
}
|
||||
|
||||
async canStopRuntime(): Promise<boolean> {
|
||||
// A history session released its app-server once it read the thread, so nothing runs.
|
||||
if (this.connectionState === "history-ready") return true;
|
||||
if (
|
||||
!this.client ||
|
||||
this.client.hasPendingRequests() ||
|
||||
|
||||
@@ -2477,42 +2477,6 @@ describe("OpenCode adapter startTurn error handling", () => {
|
||||
await session.close();
|
||||
});
|
||||
|
||||
test("reports a question rejected by a human steer as resolved", async () => {
|
||||
const { parent: session, openCode } = await createParentSession("ses_steer_question");
|
||||
openCode.sessionPromptAsyncEvents = [];
|
||||
const events: AgentStreamEvent[] = [];
|
||||
session.subscribe((event) => events.push(event));
|
||||
const { turnId } = await session.startTurn("first");
|
||||
openCode.emitEvent({
|
||||
type: "question.asked",
|
||||
properties: {
|
||||
id: "question-steer",
|
||||
sessionID: "ses_steer_question",
|
||||
questions: [{ question: "Which color?", header: "Color", options: [] }],
|
||||
},
|
||||
});
|
||||
await vi.waitFor(() => expect(session.getPendingPermissions()).toHaveLength(1));
|
||||
|
||||
await expect(
|
||||
session.steerActiveTurn?.("never mind", {
|
||||
expectedTurnId: turnId,
|
||||
clearPendingPermissions: true,
|
||||
}),
|
||||
).resolves.toEqual({ status: "accepted" });
|
||||
|
||||
expect(openCode.calls.questionReject).toContainEqual(
|
||||
expect.objectContaining({ requestID: "question-steer" }),
|
||||
);
|
||||
expect(events).toContainEqual(
|
||||
expect.objectContaining({
|
||||
type: "permission_resolved",
|
||||
requestId: "question-steer",
|
||||
resolution: expect.objectContaining({ behavior: "deny" }),
|
||||
}),
|
||||
);
|
||||
await session.close();
|
||||
});
|
||||
|
||||
test("keeps multiple native steers correlated in admission order", async () => {
|
||||
const { parent: session, openCode } = await createParentSession("ses_native_steer_fifo");
|
||||
openCode.sessionPromptAsyncEvents = [];
|
||||
|
||||
@@ -5049,24 +5049,22 @@ class OpenCodeAgentSession implements AgentSession {
|
||||
answers,
|
||||
});
|
||||
}
|
||||
} else {
|
||||
const reply = resolveOpenCodePermissionReply(response);
|
||||
await this.client.permission.reply({
|
||||
requestID: requestId,
|
||||
directory,
|
||||
reply,
|
||||
message: response.behavior === "deny" ? response.message : undefined,
|
||||
});
|
||||
|
||||
this.pendingPermissions.delete(requestId);
|
||||
this.pendingPermissionDirectories.delete(requestId);
|
||||
return;
|
||||
}
|
||||
|
||||
const reply = resolveOpenCodePermissionReply(response);
|
||||
await this.client.permission.reply({
|
||||
requestID: requestId,
|
||||
directory,
|
||||
reply,
|
||||
message: response.behavior === "deny" ? response.message : undefined,
|
||||
});
|
||||
|
||||
this.pendingPermissions.delete(requestId);
|
||||
this.pendingPermissionDirectories.delete(requestId);
|
||||
this.notifySubscribers({
|
||||
type: "permission_resolved",
|
||||
provider: "opencode",
|
||||
requestId,
|
||||
resolution: response,
|
||||
});
|
||||
}
|
||||
|
||||
describePersistence(): AgentPersistenceHandle | null {
|
||||
|
||||
@@ -31,7 +31,6 @@ function createPullRequest(
|
||||
baseRefName: "main",
|
||||
headRefName: "feature",
|
||||
headSha: "same-head",
|
||||
commitOids: ["same-head"],
|
||||
isMerged: true,
|
||||
...overrides,
|
||||
};
|
||||
@@ -350,7 +349,7 @@ afterEach(() => {
|
||||
|
||||
describe("archiveIfSafe", () => {
|
||||
test("denies archive when checkout facts do not establish safety", async () => {
|
||||
for (const git of [{ headSha: undefined }, { isDirty: null }]) {
|
||||
for (const git of [{ headSha: undefined }, { behindOfOrigin: 1 }, { isDirty: null }]) {
|
||||
const harness = createHarness({ snapshot: createSnapshot({ git }) });
|
||||
await runArchiveIfSafe(harness);
|
||||
expect(harness.deps.archiveByScope).not.toHaveBeenCalled();
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { pullRequestContainsCommit } from "../../services/pull-request-contains-commit.js";
|
||||
import type { Logger } from "pino";
|
||||
|
||||
import type { AgentManager } from "../agent/agent-manager.js";
|
||||
@@ -66,8 +65,8 @@ export async function archiveIfSafe(input: {
|
||||
|
||||
if (
|
||||
!pullRequest?.isMerged ||
|
||||
!pullRequest.headSha ||
|
||||
!snapshot.git.headSha ||
|
||||
snapshot.git.headSha !== pullRequest.headSha ||
|
||||
snapshot.forge.error
|
||||
) {
|
||||
return;
|
||||
@@ -75,18 +74,13 @@ export async function archiveIfSafe(input: {
|
||||
if (snapshot.git.isDirty !== false) {
|
||||
return;
|
||||
}
|
||||
if (snapshot.git.aheadOfOrigin !== null && snapshot.git.aheadOfOrigin !== 0) {
|
||||
if (
|
||||
(snapshot.git.aheadOfOrigin !== null && snapshot.git.aheadOfOrigin !== 0) ||
|
||||
(snapshot.git.behindOfOrigin !== null && snapshot.git.behindOfOrigin !== 0)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (
|
||||
!pullRequestContainsCommit({
|
||||
workspaceCommit: snapshot.git.headSha,
|
||||
pullRequestCommits: pullRequest.commitOids,
|
||||
})
|
||||
)
|
||||
return;
|
||||
|
||||
const ownership = await deps.isPaseoOwnedWorktreeCwd(cwd, {
|
||||
paseoHome: options.paseoHome,
|
||||
worktreesRoot: options.paseoWorktreesBaseRoot,
|
||||
|
||||
@@ -179,7 +179,6 @@ async function createUnobservedWorkspace(journeyOptions?: {
|
||||
});
|
||||
let observation: PullRequestObservation | null = null;
|
||||
let remoteHeadSha = execFileSync("git", ["rev-parse", "HEAD"], { cwd, encoding: "utf8" }).trim();
|
||||
const workspaceHeadSha = remoteHeadSha;
|
||||
const reads: Array<string | undefined> = [];
|
||||
const archives: string[] = [];
|
||||
let archiveDecisions = 0;
|
||||
@@ -195,7 +194,6 @@ async function createUnobservedWorkspace(journeyOptions?: {
|
||||
status: observation && {
|
||||
...observation,
|
||||
headSha: remoteHeadSha,
|
||||
commitOids: [workspaceHeadSha, remoteHeadSha],
|
||||
title: observation.headRefName,
|
||||
baseRefName: "main",
|
||||
isMerged: observation.state === "merged",
|
||||
@@ -262,23 +260,7 @@ async function createUnobservedWorkspace(journeyOptions?: {
|
||||
metrics: () => service.getMetrics(),
|
||||
isActive: () => active,
|
||||
advanceRemoteHead: () => {
|
||||
remoteHeadSha = execFileSync(
|
||||
"git",
|
||||
[
|
||||
"-c",
|
||||
"user.name=Test",
|
||||
"-c",
|
||||
"user.email=test@example.com",
|
||||
"commit-tree",
|
||||
"HEAD^{tree}",
|
||||
"-p",
|
||||
"HEAD",
|
||||
"-m",
|
||||
"remote update",
|
||||
],
|
||||
{ cwd, encoding: "utf8" },
|
||||
).trim();
|
||||
run(cwd, ["update-ref", "refs/remotes/origin/workspace", remoteHeadSha]);
|
||||
remoteHeadSha = "a".repeat(40);
|
||||
},
|
||||
makeDirty: () => writeFileSync(path.join(cwd, "README.md"), "uncommitted work\n"),
|
||||
commitUnpushed: () => {
|
||||
@@ -325,7 +307,7 @@ describe("workspace auto-archive behavior", () => {
|
||||
expect(workspace.isActive()).toBe(true);
|
||||
});
|
||||
|
||||
test("archives a clean workspace contained in the advanced merged PR head", async () => {
|
||||
test("keeps a merged PR visible and the workspace active when its remote head advances", async () => {
|
||||
const workspace = await createUnobservedWorkspace();
|
||||
const open = await workspace.observe("open");
|
||||
workspace.advanceRemoteHead();
|
||||
@@ -333,9 +315,8 @@ describe("workspace auto-archive behavior", () => {
|
||||
await vi.waitFor(() => expect(workspace.archiveDecisions()).toBe(1));
|
||||
expect(merged.forge.pullRequest?.url).toBe(open.forge.pullRequest?.url);
|
||||
expect(merged.forge.pullRequest?.headSha).not.toBe(merged.git.headSha);
|
||||
expect(merged.git.behindOfOrigin).toBe(1);
|
||||
expect(workspace.isActive()).toBe(false);
|
||||
expect(workspace.archives).toHaveLength(1);
|
||||
expect(workspace.isActive()).toBe(true);
|
||||
expect(workspace.archives).toEqual([]);
|
||||
});
|
||||
|
||||
test("archives a clean owned workspace on an unobserved open-to-merged transition only once", async () => {
|
||||
|
||||
@@ -51,7 +51,6 @@ describe("checkout status projection", () => {
|
||||
const payload = normalizeCheckoutPrStatusPayload(
|
||||
{
|
||||
number: 123,
|
||||
commitOids: ["server-only-membership"],
|
||||
repoOwner: "internal-owner",
|
||||
repoName: "internal-repo",
|
||||
url: "https://github.com/getpaseo/paseo/pull/123",
|
||||
@@ -77,7 +76,6 @@ describe("checkout status projection", () => {
|
||||
"github",
|
||||
);
|
||||
|
||||
expect(payload).not.toHaveProperty("commitOids");
|
||||
expect(payload).toHaveProperty("repoOwner", "internal-owner");
|
||||
expect(payload).toHaveProperty("repoName", "internal-repo");
|
||||
expect(payload).toHaveProperty("forge", "github");
|
||||
|
||||
@@ -1,87 +0,0 @@
|
||||
import { beforeAll, beforeEach, describe, test, expect } from "vitest";
|
||||
import { mkdtempSync, rmSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import pino from "pino";
|
||||
|
||||
import { createTestPaseoDaemon } from "../test-utils/paseo-daemon.js";
|
||||
import { DaemonClient } from "../test-utils/daemon-client.js";
|
||||
import {
|
||||
canRunRealProvider,
|
||||
createRealProviderClients,
|
||||
getRealProviderConfig,
|
||||
} from "./real-provider-test-config.js";
|
||||
|
||||
async function readStatusAndPendingIds(
|
||||
client: DaemonClient,
|
||||
agentId: string,
|
||||
): Promise<{ status: string; pendingIds: string[] }> {
|
||||
const fetched = await client.fetchAgent(agentId);
|
||||
const snapshot = fetched!.agent;
|
||||
const pendingIds = (snapshot.pendingPermissions ?? []).map((pending) => pending.id);
|
||||
return { status: snapshot.status, pendingIds };
|
||||
}
|
||||
|
||||
describe("daemon E2E (real opencode) - a message sent instead of answering a question", () => {
|
||||
let canRun = false;
|
||||
|
||||
beforeAll(async () => {
|
||||
canRun = await canRunRealProvider("opencode");
|
||||
});
|
||||
|
||||
beforeEach((context) => {
|
||||
if (!canRun) {
|
||||
context.skip();
|
||||
}
|
||||
});
|
||||
|
||||
test("removes the superseded question from the pending list", async () => {
|
||||
const cwd = mkdtempSync(path.join(tmpdir(), "daemon-real-opencode-question-"));
|
||||
const logger = pino({ level: "silent" });
|
||||
const daemon = await createTestPaseoDaemon({
|
||||
agentClients: createRealProviderClients(["opencode"], logger),
|
||||
logger,
|
||||
});
|
||||
const client = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws` });
|
||||
await client.connect();
|
||||
await client.fetchAgents({ subscribe: {} });
|
||||
|
||||
try {
|
||||
const agent = await client.createAgent({
|
||||
...getRealProviderConfig("opencode"),
|
||||
cwd,
|
||||
title: "OpenCode superseded question",
|
||||
});
|
||||
|
||||
await client.sendMessage(
|
||||
agent.id,
|
||||
[
|
||||
"Use the question tool to ask me exactly one clarifying question:",
|
||||
"What color should the button be?",
|
||||
"Wait for my answer before doing anything else.",
|
||||
].join(" "),
|
||||
);
|
||||
await client.waitForAgentUpsert(
|
||||
agent.id,
|
||||
(snapshot) => snapshot.pendingPermissions?.[0]?.kind === "question",
|
||||
120_000,
|
||||
);
|
||||
|
||||
// The app sends with the default send setting, which steers the running turn.
|
||||
await client.sendMessage(agent.id, "Never mind the question. Reply with the word done.", {
|
||||
activeTurnBehavior: "steer",
|
||||
});
|
||||
// OpenCode rejects the question and runs the steer message to completion.
|
||||
await expect
|
||||
.poll(() => readStatusAndPendingIds(client, agent.id), {
|
||||
timeout: 120_000,
|
||||
interval: 1_000,
|
||||
})
|
||||
.toEqual({ status: "idle", pendingIds: [] });
|
||||
} finally {
|
||||
await client.close().catch(() => undefined);
|
||||
await daemon.close();
|
||||
rmSync(cwd, { recursive: true, force: true });
|
||||
}
|
||||
}, 300_000);
|
||||
});
|
||||
@@ -193,11 +193,10 @@ test("classifies a removed file as deleted", async () => {
|
||||
});
|
||||
|
||||
await rm(target);
|
||||
// macOS FSEvents can replay the write above as a create after the subscription starts,
|
||||
// so the delete is the latest event for the path, not the first. Native recursive delivery
|
||||
// can also be coalesced before the backend's deletion audit, hence the longer timeout.
|
||||
// Native recursive delivery can be coalesced before the backend's deletion audit.
|
||||
// Assert eventual classification without imposing Vitest's one-second default.
|
||||
await expect
|
||||
.poll(() => events.findLast((event) => event.path === target)?.type, { timeout: 10_000 })
|
||||
.poll(() => events.find((event) => event.path === target)?.type, { timeout: 10_000 })
|
||||
.toBe("delete");
|
||||
await subscription.unsubscribe();
|
||||
});
|
||||
|
||||
@@ -6188,17 +6188,9 @@ export class Session {
|
||||
private buildWorkspaceGitHubRuntimePayload(
|
||||
snapshot: WorkspaceGitRuntimeSnapshot,
|
||||
): NonNullable<WorkspaceDescriptorPayload["githubRuntime"]> {
|
||||
if (!snapshot.forge.pullRequest) {
|
||||
return {
|
||||
featuresEnabled: snapshot.forge.featuresEnabled,
|
||||
pullRequest: null,
|
||||
error: snapshot.forge.error,
|
||||
};
|
||||
}
|
||||
const { commitOids: _commitOids, ...pullRequest } = snapshot.forge.pullRequest;
|
||||
return {
|
||||
featuresEnabled: snapshot.forge.featuresEnabled,
|
||||
pullRequest,
|
||||
pullRequest: snapshot.forge.pullRequest,
|
||||
error: snapshot.forge.error,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -201,8 +201,6 @@ export interface WorkspaceGitRuntimeSnapshot {
|
||||
baseRefName: string;
|
||||
headRefName: string;
|
||||
headSha?: string;
|
||||
/** Server-only commit membership evidence; never projected onto the wire. */
|
||||
commitOids?: string[];
|
||||
isMerged: boolean;
|
||||
isDraft?: boolean;
|
||||
mergeable?: PullRequestMergeable;
|
||||
|
||||
@@ -129,8 +129,6 @@ export interface CurrentPullRequestStatus {
|
||||
baseRefName: string;
|
||||
headRefName: string;
|
||||
headSha?: string;
|
||||
/** Server-only commit membership evidence; never projected onto the wire. */
|
||||
commitOids?: string[];
|
||||
isMerged: boolean;
|
||||
isDraft?: boolean;
|
||||
mergeable: PullRequestMergeable;
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
import { createPullRequestHistory } from "../test-utils/pull-request-history.js";
|
||||
import { onTestFinished } from "vitest";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import type { PullRequestCommandStatus, PullRequestTimelineItem } from "./forge-service.js";
|
||||
@@ -2050,8 +2048,6 @@ describe("createGiteaService", () => {
|
||||
if (args[0] === "pr" && args[1] === "list" && argValue(args, "--state") === "open") {
|
||||
return ok(JSON.stringify([]));
|
||||
}
|
||||
if (args[1]?.includes("/commits?"))
|
||||
return ok(JSON.stringify(args[1].includes("page=1") ? [{ sha: headSha }] : []));
|
||||
if (args[0] === "api" && args[1].includes("/pulls?state=all")) {
|
||||
return ok(JSON.stringify([closedPr]));
|
||||
}
|
||||
@@ -2071,38 +2067,6 @@ describe("createGiteaService", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it("follows commit pagination headers and stops without probing past the last page", async () => {
|
||||
const closed = currentPullRequestApi({
|
||||
number: 8,
|
||||
state: "closed",
|
||||
headRef: "feature",
|
||||
headSha: "remote-head",
|
||||
});
|
||||
const { service, calls } = makeService((args) => {
|
||||
if (args[0] === "pr" && args[1] === "list") return ok("[]");
|
||||
if (args[1]?.includes("/pulls?")) return ok(JSON.stringify([closed]));
|
||||
if (args[1]?.includes("/commits?")) {
|
||||
const page = new URL(args[1], "https://gitea.test").searchParams.get("page");
|
||||
if (page === "1")
|
||||
return {
|
||||
stdout: JSON.stringify([{ sha: "other" }]),
|
||||
stderr: 'HTTP/1.1 200 OK\nLink: <https://gitea.test/commits?page=2>; rel="next"\n',
|
||||
};
|
||||
if (page === "2") return ok(JSON.stringify([{ sha: "own" }]));
|
||||
throw new Error("HTTP 500: page past end");
|
||||
}
|
||||
throw new Error("Unexpected call");
|
||||
});
|
||||
await expect(
|
||||
service.getCurrentPullRequestStatus({
|
||||
cwd: "/repo",
|
||||
headRef: "feature",
|
||||
headSha: "own",
|
||||
}),
|
||||
).resolves.toMatchObject({ number: 8 });
|
||||
expect(calls.filter((args) => args[1]?.includes("/commits?"))).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("uses tea repository context when origin identity is unavailable", async () => {
|
||||
const headSha = "8888888888888888888888888888888888888888";
|
||||
const closedPr = currentPullRequestApi({
|
||||
@@ -2114,8 +2078,6 @@ describe("createGiteaService", () => {
|
||||
const { service, calls } = makeService(
|
||||
(args) => {
|
||||
if (args[0] === "pr" && args[1] === "list") return ok("[]");
|
||||
if (args[1]?.includes("/commits?"))
|
||||
return ok(JSON.stringify(args[1].includes("page=1") ? [{ sha: headSha }] : []));
|
||||
if (args[0] === "api" && args[1].startsWith("repos/{owner}/{repo}/pulls?")) {
|
||||
return ok(JSON.stringify([closedPr]));
|
||||
}
|
||||
@@ -2138,20 +2100,15 @@ describe("createGiteaService", () => {
|
||||
});
|
||||
|
||||
it("keeps a merged PR when its remote head advances beyond the checkout", async () => {
|
||||
const history = createPullRequestHistory();
|
||||
onTestFinished(history.dispose);
|
||||
const { cwd, workspaceCommit, pullRequestCommit } = history;
|
||||
const stale = currentPullRequestApi({
|
||||
number: 8,
|
||||
state: "closed",
|
||||
headRef: "dev",
|
||||
headSha: pullRequestCommit,
|
||||
headSha: "1111111111111111111111111111111111111111",
|
||||
merged: true,
|
||||
});
|
||||
const { service } = makeService((args) => {
|
||||
if (args[0] === "pr" && args[1] === "list") return ok("[]");
|
||||
if (args[1]?.includes("/commits?"))
|
||||
return ok(JSON.stringify(args[1].includes("page=1") ? [{ sha: workspaceCommit }] : []));
|
||||
if (args[0] === "api" && args[1].includes("/pulls?state=all")) {
|
||||
return ok(JSON.stringify([stale]));
|
||||
}
|
||||
@@ -2160,9 +2117,9 @@ describe("createGiteaService", () => {
|
||||
|
||||
await expect(
|
||||
service.getCurrentPullRequestStatus({
|
||||
cwd,
|
||||
cwd: "/repo",
|
||||
headRef: "dev",
|
||||
headSha: workspaceCommit,
|
||||
headSha: "2222222222222222222222222222222222222222",
|
||||
}),
|
||||
).resolves.toMatchObject({ number: 8, state: "merged" });
|
||||
});
|
||||
|
||||
@@ -1,7 +1,3 @@
|
||||
import {
|
||||
pullRequestContainsCommit,
|
||||
createPullRequestCommitReader,
|
||||
} from "./pull-request-contains-commit.js";
|
||||
import { z } from "zod";
|
||||
import { CHECK_TRAIT_ACTION_REQUIRED, CHECK_TRAIT_WARNING } from "@getpaseo/protocol/check-traits";
|
||||
import { mapGiteaCommitState } from "@getpaseo/protocol/gitea-status";
|
||||
@@ -167,7 +163,6 @@ const GiteaPrListItemSchema = z
|
||||
labels: z.string().optional(),
|
||||
ci: z.string().optional(),
|
||||
headSha: z.string().optional(),
|
||||
commitOids: z.array(z.string()).optional(),
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
@@ -1404,7 +1399,6 @@ function throwFirstNonTeaAuthSearchRejection(results: PromiseSettledResult<unkno
|
||||
}
|
||||
|
||||
export function createGiteaService(options: CreateGiteaServiceOptions = {}): ForgeService {
|
||||
const readRequestCommits = createPullRequestCommitReader();
|
||||
const runner = options.runner ?? runTeaCommand;
|
||||
const resolveTea = createCachedCliPathResolver(options.resolveTeaPath ?? resolveTeaPath);
|
||||
const resolveRemoteUrl = options.resolveRemoteUrl ?? defaultResolveRemoteUrl;
|
||||
@@ -1412,25 +1406,19 @@ export function createGiteaService(options: CreateGiteaServiceOptions = {}): For
|
||||
const now = options.now ?? Date.now;
|
||||
const currentPrHeadShaCache = new Map<string, { sha: string; expiresAt: number }>();
|
||||
|
||||
async function runResult(
|
||||
args: string[],
|
||||
runOptions: TeaCommandRunnerOptions,
|
||||
): Promise<TeaCommandResult> {
|
||||
async function run(args: string[], runOptions: TeaCommandRunnerOptions): Promise<string> {
|
||||
const teaPath = await resolveTea();
|
||||
if (!teaPath) {
|
||||
throw new TeaCliMissingError();
|
||||
}
|
||||
try {
|
||||
return await runner(args, runOptions);
|
||||
const result = await runner(args, runOptions);
|
||||
return result.stdout.trim();
|
||||
} catch (error) {
|
||||
throw teaCliRunner.normalizeError(error, { args: redactTeaArgs(args), cwd: runOptions.cwd });
|
||||
}
|
||||
}
|
||||
|
||||
async function run(args: string[], runOptions: TeaCommandRunnerOptions): Promise<string> {
|
||||
return (await runResult(args, runOptions)).stdout.trim();
|
||||
}
|
||||
|
||||
function runJsonParse<T>(
|
||||
args: string[],
|
||||
runOptions: TeaCommandRunnerOptions,
|
||||
@@ -1606,7 +1594,7 @@ export function createGiteaService(options: CreateGiteaServiceOptions = {}): For
|
||||
if (!match) {
|
||||
return null;
|
||||
}
|
||||
const status = { ...toCurrentPullRequestStatus(match), commitOids: match.commitOids };
|
||||
const status = toCurrentPullRequestStatus(match);
|
||||
return loadCurrentPullRequestChecks(input.cwd, match, status);
|
||||
}
|
||||
|
||||
@@ -1668,47 +1656,17 @@ export function createGiteaService(options: CreateGiteaServiceOptions = {}): For
|
||||
// owner gate.
|
||||
return input.headSha !== undefined && item.head.sha === input.headSha;
|
||||
});
|
||||
const open = candidates.find((candidate) => mapGiteaState(candidate.state) === "open");
|
||||
if (open) return currentPullRequestApiToListItem(open);
|
||||
candidates.sort(
|
||||
(left, right) =>
|
||||
Number(right.head.sha === input.headSha) - Number(left.head.sha === input.headSha),
|
||||
);
|
||||
for (const item of candidates) {
|
||||
const commitOids = await readRequestCommits(
|
||||
`${input.cwd}:${repoPath}/${item.number}@${item.head.sha}`,
|
||||
async () => {
|
||||
const result: string[] = [];
|
||||
for (let page = 1; ; page++) {
|
||||
const args = [
|
||||
"api",
|
||||
`${repoPath}/pulls/${item.number}/commits?limit=50&page=${page}&files=false&verification=false`,
|
||||
"--include",
|
||||
];
|
||||
const response = await runResult(args, { cwd: input.cwd });
|
||||
const commits = runJsonParse(
|
||||
args,
|
||||
{ cwd: input.cwd },
|
||||
response.stdout,
|
||||
z.array(z.object({ sha: z.string() })),
|
||||
);
|
||||
result.push(...commits.map((commit) => commit.sha));
|
||||
// tea writes response headers to stderr. Following Link also respects
|
||||
// server-side page caps and avoids probing beyond the final page.
|
||||
if (!/<[^>]+>;\s*rel="next"/i.test(response.stderr)) return result;
|
||||
}
|
||||
},
|
||||
);
|
||||
if (
|
||||
pullRequestContainsCommit({
|
||||
workspaceCommit: input.headSha,
|
||||
pullRequestCommits: commitOids,
|
||||
})
|
||||
) {
|
||||
return { ...currentPullRequestApiToListItem(item), commitOids };
|
||||
}
|
||||
}
|
||||
return null;
|
||||
const match =
|
||||
candidates.find((item) => mapGiteaState(item.state) === "open") ??
|
||||
candidates.find(
|
||||
(item) =>
|
||||
mapGiteaState(item.state) !== "open" &&
|
||||
input.headSha !== undefined &&
|
||||
item.head.sha === input.headSha,
|
||||
) ??
|
||||
candidates[0] ??
|
||||
null;
|
||||
return match ? currentPullRequestApiToListItem(match) : null;
|
||||
}
|
||||
|
||||
async function findOpenPullRequestForHeadRef(
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
import { createPullRequestCommitReader } from "./pull-request-contains-commit.js";
|
||||
import { createPullRequestHistory } from "../test-utils/pull-request-history.js";
|
||||
import { onTestFinished } from "vitest";
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
@@ -221,21 +218,6 @@ function currentPullRequestJson(overrides: Record<string, unknown> = {}): string
|
||||
});
|
||||
}
|
||||
|
||||
function commitPageJson(commitOids: string[]): Record<string, unknown> {
|
||||
return {
|
||||
pullRequest: {
|
||||
commits: {
|
||||
nodes: commitOids.map((oid) => ({ commit: { oid } })),
|
||||
pageInfo: { hasPreviousPage: false, startCursor: null },
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function directCommitsJson(commitOids: string[]): string {
|
||||
return JSON.stringify({ data: { repository: commitPageJson(commitOids) } });
|
||||
}
|
||||
|
||||
function currentPullRequestGithubFactsJson(overrides: Record<string, unknown> = {}): string {
|
||||
return JSON.stringify({
|
||||
data: {
|
||||
@@ -1129,252 +1111,6 @@ describe("ForgeService", () => {
|
||||
expect(currentPullRequestStatusCalls(runner.calls)).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("rejects failed commit reads and retries without retaining the failure", async () => {
|
||||
const read = createPullRequestCommitReader();
|
||||
await expect(
|
||||
read("bad@head", async () => {
|
||||
throw new Error("offline");
|
||||
}),
|
||||
).rejects.toThrow("offline");
|
||||
await expect(read("good@head", async () => ["own-commit"])).resolves.toEqual(["own-commit"]);
|
||||
await expect(read("bad@head", async () => ["recovered"])).resolves.toEqual(["recovered"]);
|
||||
await expect(
|
||||
read("good@head", async () => {
|
||||
throw new Error("must use cache");
|
||||
}),
|
||||
).resolves.toEqual(["own-commit"]);
|
||||
});
|
||||
|
||||
it.each(["transport", "alias"])(
|
||||
"preserves a failed workspace even with an older match and isolates a complete open workspace (%s)",
|
||||
async (failure) => {
|
||||
const runner = createScriptedRunner([
|
||||
batchPollStatusJson({
|
||||
t0: batchPollRepositoryJson([
|
||||
batchPollPrNodeJson({
|
||||
number: 60,
|
||||
headRefName: "a",
|
||||
}),
|
||||
batchPollPrNodeJson({
|
||||
number: 50,
|
||||
headRefName: "a",
|
||||
}),
|
||||
]),
|
||||
t1: batchPollRepositoryJson([
|
||||
batchPollPrNodeJson({ headRefName: "b", state: "OPEN", mergedAt: null }),
|
||||
]),
|
||||
}),
|
||||
batchPollStatusJson({
|
||||
t0: {
|
||||
pullRequest: {
|
||||
commits: { nodes: [], pageInfo: { hasPreviousPage: true, startCursor: "next" } },
|
||||
},
|
||||
},
|
||||
t1: commitPageJson(["own-a"]),
|
||||
}),
|
||||
failure === "transport"
|
||||
? { error: new Error("HTTP 502") }
|
||||
: batchPollStatusJson({ t0: null }),
|
||||
batchPollStatusJson({ t0: batchPollChecksAliasJson([]) }),
|
||||
]);
|
||||
const service = createGitHubService({
|
||||
runner: runner.runner,
|
||||
resolveGhPath: async () => "/usr/bin/gh",
|
||||
resolveRepoHost: async () => null,
|
||||
resolveRepoSlug: async () => "acme/widgets",
|
||||
});
|
||||
const errorsA: unknown[] = [],
|
||||
errorsB: unknown[] = [];
|
||||
const statusesA: Array<CurrentPullRequestStatus | null> = [];
|
||||
const statusesB: Array<CurrentPullRequestStatus | null> = [];
|
||||
service.retainCurrentPullRequestStatusPoll?.({
|
||||
cwd: "/a",
|
||||
headRef: "a",
|
||||
headSha: "own-a",
|
||||
onError: (error) => errorsA.push(error),
|
||||
onStatus: (status) => statusesA.push(status),
|
||||
});
|
||||
service.retainCurrentPullRequestStatusPoll?.({
|
||||
cwd: "/b",
|
||||
headRef: "b",
|
||||
headSha: "own-b",
|
||||
onError: (error) => errorsB.push(error),
|
||||
onStatus: (status) => statusesB.push(status),
|
||||
});
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
await flushMicrotasks();
|
||||
service.dispose?.();
|
||||
expect(errorsA).toHaveLength(1);
|
||||
expect(statusesA).toEqual([]);
|
||||
expect(errorsB).toEqual([]);
|
||||
expect(statusesB).toEqual([expect.objectContaining({ state: "open" })]);
|
||||
},
|
||||
);
|
||||
|
||||
it.each(["cached", "failed-lower", "paged-lower", "pending-higher"])(
|
||||
"ignores a lower-ranked unresolved PR after the preferred match (%s)",
|
||||
async (scenario) => {
|
||||
let now = 0;
|
||||
const cold = true;
|
||||
const pendingHigher = scenario === "pending-higher";
|
||||
const own = batchPollPrNodeJson({
|
||||
number: 50,
|
||||
headRefName: "a",
|
||||
});
|
||||
const older = batchPollPrNodeJson({ number: 42, headRefName: "a" });
|
||||
const runner = createScriptedRunner([
|
||||
batchPollStatusJson({ t0: batchPollRepositoryJson([older, own]) }),
|
||||
...(cold
|
||||
? [
|
||||
batchPollStatusJson({
|
||||
t0: {
|
||||
pullRequest: {
|
||||
commits: {
|
||||
nodes: [{ commit: { oid: pendingHigher ? "another" : "own-a" } }],
|
||||
pageInfo: {
|
||||
hasPreviousPage: pendingHigher,
|
||||
startCursor: pendingHigher ? "next" : null,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
t1:
|
||||
scenario === "failed-lower" || pendingHigher
|
||||
? null
|
||||
: {
|
||||
pullRequest: {
|
||||
commits: {
|
||||
nodes: [{ commit: { oid: "other" } }],
|
||||
pageInfo: { hasPreviousPage: true, startCursor: "older-page" },
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
]
|
||||
: []),
|
||||
...(pendingHigher
|
||||
? [
|
||||
batchPollStatusJson({
|
||||
t0: {
|
||||
pullRequest: {
|
||||
commits: {
|
||||
nodes: [{ commit: { oid: "own-a" } }],
|
||||
pageInfo: { hasPreviousPage: false, startCursor: null },
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
]
|
||||
: []),
|
||||
batchPollStatusJson({ t0: batchPollChecksAliasJson([]) }),
|
||||
...(scenario === "cached"
|
||||
? [batchPollStatusJson({ t0: batchPollRepositoryJson([older, own]) })]
|
||||
: []),
|
||||
]);
|
||||
const service = createGitHubService({
|
||||
now: () => now,
|
||||
runner: runner.runner,
|
||||
resolveGhPath: async () => "/usr/bin/gh",
|
||||
resolveRepoHost: async () => null,
|
||||
resolveRepoSlug: async () => "acme/widgets",
|
||||
});
|
||||
const statuses: Array<CurrentPullRequestStatus | null> = [],
|
||||
errors: unknown[] = [];
|
||||
service.retainCurrentPullRequestStatusPoll?.({
|
||||
cwd: "/a",
|
||||
headRef: "a",
|
||||
headSha: "own-a",
|
||||
onStatus: (status) => statuses.push(status),
|
||||
onError: (error) => errors.push(error),
|
||||
});
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
await flushMicrotasks();
|
||||
if (scenario === "cached") {
|
||||
now = EXPECTED_GITHUB_SLOW_POLL_MS;
|
||||
await vi.advanceTimersByTimeAsync(EXPECTED_GITHUB_SLOW_POLL_MS);
|
||||
await flushMicrotasks();
|
||||
}
|
||||
service.dispose?.();
|
||||
expect(errors).toEqual([]);
|
||||
expect(statuses).toHaveLength(scenario === "cached" ? 2 : 1);
|
||||
expect(statuses.every((status) => status?.number === 50)).toBe(true);
|
||||
expect(
|
||||
runner.calls.filter(({ args }) => args.join(" ").includes("PaseoBatchCommitPages")),
|
||||
).toHaveLength(Number(cold) + Number(pendingHigher));
|
||||
},
|
||||
);
|
||||
|
||||
it.each([false, true])(
|
||||
"filters terminal PRs in a batched poll (pagination: %s)",
|
||||
async (paginate) => {
|
||||
vi.useRealTimers();
|
||||
const history = createPullRequestHistory();
|
||||
onTestFinished(history.dispose);
|
||||
const { cwd, workspaceCommit, pullRequestCommit } = history;
|
||||
const runner = createScriptedRunner([
|
||||
batchPollStatusJson({
|
||||
t0: batchPollRepositoryJson([
|
||||
batchPollPrNodeJson({
|
||||
headRefName: "feature",
|
||||
headRefOid: pullRequestCommit,
|
||||
}),
|
||||
]),
|
||||
}),
|
||||
batchPollStatusJson({
|
||||
t0: {
|
||||
pullRequest: {
|
||||
commits: {
|
||||
nodes: [{ commit: { oid: paginate ? "other" : workspaceCommit } }],
|
||||
pageInfo: { hasPreviousPage: paginate, startCursor: "cursor-1" },
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
...(paginate
|
||||
? [
|
||||
batchPollStatusJson({
|
||||
t0: {
|
||||
pullRequest: {
|
||||
commits: {
|
||||
nodes: [{ commit: { oid: workspaceCommit } }],
|
||||
pageInfo: { hasPreviousPage: false, startCursor: "cursor-2" },
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
]
|
||||
: []),
|
||||
batchPollStatusJson({ t0: batchPollChecksAliasJson([]) }),
|
||||
]);
|
||||
const service = createGitHubService({
|
||||
runner: runner.runner,
|
||||
resolveGhPath: async () => "/usr/bin/gh",
|
||||
resolveRepoHost: async () => null,
|
||||
resolveRepoSlug: async () => "acme/widgets",
|
||||
});
|
||||
onTestFinished(() => service.dispose?.());
|
||||
const statuses: Array<CurrentPullRequestStatus | null> = [];
|
||||
const subscription = service.retainCurrentPullRequestStatusPoll?.({
|
||||
cwd,
|
||||
headRef: "feature",
|
||||
headSha: workspaceCommit,
|
||||
onStatus: (status) => statuses.push(status),
|
||||
});
|
||||
onTestFinished(() => subscription?.unsubscribe());
|
||||
await vi.waitFor(() => expect(statuses).toHaveLength(1));
|
||||
expect(statuses[0]).toMatchObject({ state: "merged", headSha: pullRequestCommit });
|
||||
expect(runner.calls).toHaveLength(paginate ? 4 : 3);
|
||||
expect(runner.calls[0]?.args[3]).not.toContain("commits(");
|
||||
expect(runner.calls[1]?.args[3]).toContain("commits(last:100");
|
||||
expect(
|
||||
runner.calls.every((call) => call.args[0] === "api" && call.args[1] === "graphql"),
|
||||
).toBe(true);
|
||||
expect(history.git(["rev-parse", "HEAD"])).toBe(workspaceCommit);
|
||||
expect(history.git(["rev-parse", "@{upstream}"])).toBe(workspaceCommit);
|
||||
expect(() => history.git(["rev-parse", "--verify", "FETCH_HEAD"])).toThrow();
|
||||
},
|
||||
);
|
||||
|
||||
it("batches PR status polls across workspaces into one GraphQL request", async () => {
|
||||
let now = 0;
|
||||
const runner = createScriptedRunner([
|
||||
@@ -1396,7 +1132,6 @@ describe("ForgeService", () => {
|
||||
}),
|
||||
]),
|
||||
}),
|
||||
batchPollStatusJson({ t0: commitPageJson(["oid-a"]), t1: commitPageJson(["oid-b"]) }),
|
||||
batchPollStatusJson({
|
||||
t0: batchPollChecksAliasJson([
|
||||
{ __typename: "StatusContext", context: "ci", state: "SUCCESS" },
|
||||
@@ -1452,7 +1187,7 @@ describe("ForgeService", () => {
|
||||
await flushMicrotasks();
|
||||
|
||||
expect(currentPullRequestStatusCalls(runner.calls)).toHaveLength(0);
|
||||
expect(runner.calls).toHaveLength(3);
|
||||
expect(runner.calls).toHaveLength(2);
|
||||
expect(runner.calls[0]?.args.slice(0, 2)).toEqual(["api", "graphql"]);
|
||||
expect(runner.calls[0]?.args[3]).toContain('t0: repository(owner: "acme", name: "widgets")');
|
||||
expect(runner.calls[0]?.args[3]).toContain('t1: repository(owner: "acme", name: "gadgets")');
|
||||
@@ -1479,7 +1214,7 @@ describe("ForgeService", () => {
|
||||
await vi.advanceTimersByTimeAsync(EXPECTED_GITHUB_SLOW_POLL_MS);
|
||||
await flushMicrotasks();
|
||||
|
||||
expect(runner.calls).toHaveLength(4);
|
||||
expect(runner.calls).toHaveLength(3);
|
||||
expect(statusesA).toHaveLength(2);
|
||||
expect(statusesA[1]).toEqual(expect.objectContaining({ number: 41, checksStatus: "success" }));
|
||||
|
||||
@@ -1513,7 +1248,6 @@ describe("ForgeService", () => {
|
||||
}),
|
||||
]),
|
||||
}),
|
||||
batchPollStatusJson({ t0: commitPageJson(["oid-a"]), t1: commitPageJson(["oid-b"]) }),
|
||||
batchPollStatusJson({
|
||||
t0: batchPollChecksAliasJson([]),
|
||||
t1: batchPollChecksAliasJson([]),
|
||||
@@ -1557,7 +1291,7 @@ describe("ForgeService", () => {
|
||||
await flushMicrotasks();
|
||||
|
||||
expect(currentPullRequestStatusCalls(runner.calls)).toHaveLength(0);
|
||||
expect(runner.calls).toHaveLength(3);
|
||||
expect(runner.calls).toHaveLength(2);
|
||||
expect(runner.calls[0]?.args.slice(0, 2)).toEqual(["api", "graphql"]);
|
||||
expect(runner.calls[0]?.args[3]).toContain('t0: repository(owner: "acme", name: "widgets")');
|
||||
expect(runner.calls[0]?.args[3]).toContain('t1: repository(owner: "acme", name: "gadgets")');
|
||||
@@ -1757,7 +1491,6 @@ describe("ForgeService", () => {
|
||||
t0: batchPollRepositoryJson([], { isFork: true, parent }),
|
||||
}),
|
||||
batchPollStatusJson({ t0: batchPollRepositoryJson([forkPr]) }),
|
||||
batchPollStatusJson({ t0: commitPageJson(["oid-a"]) }),
|
||||
batchPollStatusJson({
|
||||
t0: batchPollChecksAliasJson([
|
||||
{ __typename: "StatusContext", context: "ci", state: "SUCCESS" },
|
||||
@@ -1799,7 +1532,7 @@ describe("ForgeService", () => {
|
||||
await vi.advanceTimersByTimeAsync(EXPECTED_GITHUB_SLOW_POLL_MS);
|
||||
await flushMicrotasks();
|
||||
|
||||
expect(runner.calls[4]?.args[3]).toContain(
|
||||
expect(runner.calls[3]?.args[3]).toContain(
|
||||
't0: repository(owner: "upstream", name: "widgets")',
|
||||
);
|
||||
|
||||
@@ -1878,83 +1611,6 @@ describe("ForgeService", () => {
|
||||
service.dispose?.();
|
||||
});
|
||||
|
||||
it.each(["reserve", "error"])(
|
||||
"preserves known checks when commit paging pauses the host (%s)",
|
||||
async (failure) => {
|
||||
let now = 0;
|
||||
const open = batchPollRepositoryJson([
|
||||
batchPollPrNodeJson({ state: "OPEN", mergedAt: null, headRefName: "open" }),
|
||||
]);
|
||||
const runner = createScriptedRunner([
|
||||
batchPollStatusJson({ t0: open }),
|
||||
batchPollStatusJson({
|
||||
t0: batchPollChecksAliasJson([
|
||||
{ __typename: "StatusContext", context: "ci", state: "FAILURE" },
|
||||
]),
|
||||
}),
|
||||
batchPollStatusJson({
|
||||
t0: open,
|
||||
t1: batchPollRepositoryJson([batchPollPrNodeJson()]),
|
||||
}),
|
||||
...(failure === "reserve"
|
||||
? [
|
||||
batchPollStatusWithRateLimitJson({
|
||||
aliases: {},
|
||||
limit: 5000,
|
||||
remaining: 0,
|
||||
resetAt: new Date(3600000).toISOString(),
|
||||
}),
|
||||
]
|
||||
: [
|
||||
{
|
||||
error: Object.assign(new Error("gh exited 1"), {
|
||||
code: 1,
|
||||
stderr: "GraphQL: API rate limit already exceeded for user ID 123",
|
||||
}),
|
||||
},
|
||||
JSON.stringify({ resources: { graphql: { remaining: 0, reset: 3600 } } }),
|
||||
]),
|
||||
]);
|
||||
const service = createGitHubService({
|
||||
runner: runner.runner,
|
||||
ttlMs: 3600000,
|
||||
resolveGhPath: async () => "/usr/bin/gh",
|
||||
resolveRepoHost: async () => null,
|
||||
resolveRepoSlug: async () => "acme/widgets",
|
||||
now: () => now,
|
||||
});
|
||||
const statuses: Array<CurrentPullRequestStatus | null> = [];
|
||||
const errors: unknown[] = [],
|
||||
terminalErrors: unknown[] = [];
|
||||
service.retainCurrentPullRequestStatusPoll?.({
|
||||
cwd: "/open",
|
||||
headRef: "open",
|
||||
onStatus: (status) => statuses.push(status),
|
||||
onError: (error) => errors.push(error),
|
||||
});
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
await flushMicrotasks();
|
||||
expect(statuses).toEqual([expect.objectContaining({ checksStatus: "failure" })]);
|
||||
service.retainCurrentPullRequestStatusPoll?.({
|
||||
cwd: "/terminal",
|
||||
headRef: "feat-a",
|
||||
headSha: "oid-42",
|
||||
onError: (error) => terminalErrors.push(error),
|
||||
});
|
||||
now = EXPECTED_GITHUB_SLOW_POLL_MS;
|
||||
await vi.advanceTimersByTimeAsync(EXPECTED_GITHUB_SLOW_POLL_MS);
|
||||
await flushMicrotasks();
|
||||
expect(statuses).toEqual([expect.objectContaining({ checksStatus: "failure" })]);
|
||||
expect(errors).toHaveLength(1);
|
||||
expect(terminalErrors).toHaveLength(1);
|
||||
await expect(
|
||||
service.getCurrentPullRequestStatus({ cwd: "/open", headRef: "open" }),
|
||||
).resolves.toMatchObject({ checksStatus: "failure" });
|
||||
expect(runner.calls).toHaveLength(failure === "reserve" ? 4 : 5);
|
||||
service.dispose?.();
|
||||
},
|
||||
);
|
||||
|
||||
it("pauses a host until reset when a batch reaches the GraphQL reserve", async () => {
|
||||
let now = 0;
|
||||
const resetAt = new Date(EXPECTED_GITHUB_ERROR_BACKOFF_CAP_MS).toISOString();
|
||||
@@ -2061,7 +1717,6 @@ describe("ForgeService", () => {
|
||||
});
|
||||
const runner = createScriptedRunner([
|
||||
batchPollStatusJson({ t0: batchPollRepositoryJson([closedNode]) }),
|
||||
batchPollStatusJson({ t0: commitPageJson(["oid-closed"]) }),
|
||||
batchPollStatusJson({
|
||||
t0: batchPollChecksAliasJson([
|
||||
{ __typename: "StatusContext", context: "ci", state: "PENDING" },
|
||||
@@ -2093,7 +1748,7 @@ describe("ForgeService", () => {
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
await flushMicrotasks();
|
||||
|
||||
expect(runner.calls).toHaveLength(3);
|
||||
expect(runner.calls).toHaveLength(2);
|
||||
expect(statuses).toEqual([expect.objectContaining({ number: 9, checksStatus: "pending" })]);
|
||||
|
||||
// Pending checks are never frozen, so the next cycle re-runs the checks
|
||||
@@ -2102,7 +1757,7 @@ describe("ForgeService", () => {
|
||||
await vi.advanceTimersByTimeAsync(EXPECTED_GITHUB_FAST_POLL_MS);
|
||||
await flushMicrotasks();
|
||||
|
||||
expect(runner.calls).toHaveLength(5);
|
||||
expect(runner.calls).toHaveLength(4);
|
||||
expect(statuses[1]).toEqual(expect.objectContaining({ number: 9, checksStatus: "success" }));
|
||||
|
||||
subscription?.unsubscribe();
|
||||
@@ -2215,7 +1870,6 @@ describe("ForgeService", () => {
|
||||
stderr: "GraphQL: Could not resolve to a Repository",
|
||||
}),
|
||||
},
|
||||
batchPollStatusJson({ t0: commitPageJson(["oid-a"]) }),
|
||||
batchPollStatusJson({
|
||||
t0: batchPollChecksAliasJson([
|
||||
{ __typename: "StatusContext", context: "ci", state: "SUCCESS" },
|
||||
@@ -2248,7 +1902,7 @@ describe("ForgeService", () => {
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
await flushMicrotasks();
|
||||
|
||||
expect(runner.calls).toHaveLength(3);
|
||||
expect(runner.calls).toHaveLength(2);
|
||||
expect(statuses).toEqual([
|
||||
expect.objectContaining({ number: 41, state: "merged", checksStatus: "success" }),
|
||||
]);
|
||||
@@ -3484,42 +3138,6 @@ describe("ForgeService", () => {
|
||||
expect(details.truncated).toBe(true);
|
||||
});
|
||||
|
||||
it("chooses an open PR before reading an older terminal candidate's commits", async () => {
|
||||
const terminal = JSON.parse(
|
||||
currentPullRequestJson({
|
||||
number: 1,
|
||||
state: "MERGED",
|
||||
mergedAt: "2026-01-01T00:00:00Z",
|
||||
headRefName: "feature",
|
||||
headRepositoryOwner: { login: "acme" },
|
||||
}),
|
||||
);
|
||||
const open = JSON.parse(
|
||||
currentPullRequestJson({
|
||||
number: 2,
|
||||
headRefName: "feature",
|
||||
headRepositoryOwner: { login: "acme" },
|
||||
}),
|
||||
);
|
||||
const runner = createScriptedRunner([
|
||||
JSON.stringify(terminal),
|
||||
JSON.stringify({ owner: { login: "acme" }, name: "repo", parent: null }),
|
||||
JSON.stringify([open, terminal]),
|
||||
]);
|
||||
const service = createGitHubService({
|
||||
runner: runner.runner,
|
||||
resolveGhPath: async () => "/usr/bin/gh",
|
||||
});
|
||||
await expect(
|
||||
service.getCurrentPullRequestStatus({
|
||||
cwd: "/repo",
|
||||
headRef: "feature",
|
||||
headSha: "own",
|
||||
}),
|
||||
).resolves.toMatchObject({ number: 2, state: "open" });
|
||||
expect(runner.calls.some(({ args }) => args.join(" ").includes("commits(last:"))).toBe(false);
|
||||
});
|
||||
|
||||
it("retries current PR view without statusCheckRollup when token permissions are insufficient", async () => {
|
||||
const runner = createScriptedRunner([
|
||||
{
|
||||
@@ -3662,16 +3280,12 @@ describe("ForgeService", () => {
|
||||
|
||||
it("keeps a merged PR when headRefOid matches the checkout HEAD", async () => {
|
||||
const headSha = "2222222222222222222222222222222222222222";
|
||||
const candidate = currentPullRequestJson({
|
||||
state: "MERGED",
|
||||
mergedAt: "2026-07-17T12:00:00Z",
|
||||
headRefOid: headSha,
|
||||
headRepositoryOwner: { login: "forkOwner" },
|
||||
});
|
||||
const runner = createScriptedRunner([
|
||||
candidate,
|
||||
JSON.stringify([JSON.parse(candidate)]),
|
||||
directCommitsJson([headSha]),
|
||||
const runner = createRunner([
|
||||
currentPullRequestJson({
|
||||
state: "MERGED",
|
||||
mergedAt: "2026-07-17T12:00:00Z",
|
||||
headRefOid: headSha,
|
||||
}),
|
||||
]);
|
||||
const service = createGitHubService({
|
||||
runner: runner.runner,
|
||||
@@ -3682,7 +3296,6 @@ describe("ForgeService", () => {
|
||||
cwd: "/repo",
|
||||
headRef: "feature/fork",
|
||||
headSha,
|
||||
headRepositoryOwner: "forkOwner",
|
||||
});
|
||||
|
||||
expect(status?.number).toBe(42);
|
||||
@@ -3690,20 +3303,16 @@ describe("ForgeService", () => {
|
||||
});
|
||||
|
||||
it("keeps a merged PR when its remote head advances beyond the checkout", async () => {
|
||||
const history = createPullRequestHistory();
|
||||
onTestFinished(history.dispose);
|
||||
const { cwd, workspaceCommit, pullRequestCommit } = history;
|
||||
const stale = currentPullRequestJson({
|
||||
headRepositoryOwner: { login: "parentOwner" },
|
||||
state: "MERGED",
|
||||
mergedAt: "2026-07-17T12:00:00Z",
|
||||
headRefOid: pullRequestCommit,
|
||||
headRefOid: "1111111111111111111111111111111111111111",
|
||||
});
|
||||
const runner = createScriptedRunner([
|
||||
stale,
|
||||
JSON.stringify({ owner: { login: "parentOwner" }, name: "parentRepo", parent: null }),
|
||||
JSON.stringify([JSON.parse(stale)]),
|
||||
directCommitsJson([workspaceCommit, pullRequestCommit]),
|
||||
]);
|
||||
const service = createGitHubService({
|
||||
runner: runner.runner,
|
||||
@@ -3712,9 +3321,9 @@ describe("ForgeService", () => {
|
||||
|
||||
await expect(
|
||||
service.getCurrentPullRequestStatus({
|
||||
cwd,
|
||||
cwd: "/repo",
|
||||
headRef: "feature/fork",
|
||||
headSha: workspaceCommit,
|
||||
headSha: "2222222222222222222222222222222222222222",
|
||||
}),
|
||||
).resolves.toMatchObject({ state: "merged" });
|
||||
expect(runner.calls.some((call) => call.args[0] === "pr" && call.args[1] === "list")).toBe(
|
||||
@@ -3722,117 +3331,7 @@ describe("ForgeService", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it.each(["CLOSED", "MERGED"])(
|
||||
"hides a %s PR when a reused branch is ahead of its head",
|
||||
async (state) => {
|
||||
const history = createPullRequestHistory();
|
||||
onTestFinished(history.dispose);
|
||||
const candidate = JSON.parse(
|
||||
currentPullRequestJson({
|
||||
state,
|
||||
mergedAt: state === "MERGED" ? "2026-07-17T12:00:00Z" : null,
|
||||
headRefOid: history.workspaceCommit,
|
||||
headRepositoryOwner: { login: "forkOwner" },
|
||||
}),
|
||||
);
|
||||
const runner = createScriptedRunner([
|
||||
JSON.stringify(candidate),
|
||||
JSON.stringify([candidate]),
|
||||
directCommitsJson([history.workspaceCommit]),
|
||||
]);
|
||||
const service = createGitHubService({
|
||||
runner: runner.runner,
|
||||
resolveGhPath: async () => "/usr/bin/gh",
|
||||
});
|
||||
await expect(
|
||||
service.getCurrentPullRequestStatus({
|
||||
cwd: history.remote,
|
||||
headRef: "feature/fork",
|
||||
headRepositoryOwner: "forkOwner",
|
||||
headSha: history.pullRequestCommit,
|
||||
}),
|
||||
).resolves.toBeNull();
|
||||
},
|
||||
);
|
||||
|
||||
it.each(["CLOSED", "MERGED"])(
|
||||
"hides a %s PR when the workspace only shares its inherited base",
|
||||
async (state) => {
|
||||
const history = createPullRequestHistory();
|
||||
onTestFinished(history.dispose);
|
||||
const candidate = JSON.parse(
|
||||
currentPullRequestJson({
|
||||
state,
|
||||
headRefOid: history.pullRequestCommit,
|
||||
headRepositoryOwner: { login: "forkOwner" },
|
||||
}),
|
||||
);
|
||||
const runner = createScriptedRunner([
|
||||
JSON.stringify(candidate),
|
||||
JSON.stringify([candidate]),
|
||||
directCommitsJson([history.pullRequestCommit]),
|
||||
]);
|
||||
const service = createGitHubService({
|
||||
runner: runner.runner,
|
||||
resolveGhPath: async () => "/usr/bin/gh",
|
||||
});
|
||||
await expect(
|
||||
service.getCurrentPullRequestStatus({
|
||||
cwd: history.cwd,
|
||||
headRef: "feature/fork",
|
||||
headRepositoryOwner: "forkOwner",
|
||||
headSha: history.workspaceCommit,
|
||||
}),
|
||||
).resolves.toBeNull();
|
||||
},
|
||||
);
|
||||
|
||||
it("reads only commit IDs for a cold terminal lookup and reuses the list", async () => {
|
||||
const candidate = currentPullRequestJson({
|
||||
number: 987,
|
||||
state: "MERGED",
|
||||
headRefOid: "cold-own-head",
|
||||
|
||||
headRepositoryOwner: { login: "forkOwner" },
|
||||
});
|
||||
const runner = createScriptedRunner([
|
||||
candidate,
|
||||
JSON.stringify([JSON.parse(candidate)]),
|
||||
JSON.stringify({
|
||||
data: {
|
||||
repository: {
|
||||
pullRequest: {
|
||||
commits: {
|
||||
nodes: [{ commit: { oid: "cold-own-head" } }],
|
||||
pageInfo: { hasPreviousPage: false, startCursor: null },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
]);
|
||||
const service = createGitHubService({
|
||||
runner: runner.runner,
|
||||
resolveGhPath: async () => "/usr/bin/gh",
|
||||
});
|
||||
await expect(
|
||||
service.getCurrentPullRequestStatus({
|
||||
cwd: "/repo",
|
||||
headRef: "feature/fork",
|
||||
headRepositoryOwner: "forkOwner",
|
||||
headSha: "cold-own-head",
|
||||
}),
|
||||
).resolves.toMatchObject({ number: 987 });
|
||||
expect(runner.calls).toHaveLength(4);
|
||||
expect(runner.calls.filter((call) => call.args[3]?.includes("commits(last:100"))).toHaveLength(
|
||||
1,
|
||||
);
|
||||
expect(runner.calls[0]?.args.at(-1)).not.toContain("commits");
|
||||
expect(runner.calls[2]?.args[3]).toContain("commits(last:100");
|
||||
expect(runner.calls[2]?.args[3]).not.toContain("authors");
|
||||
});
|
||||
|
||||
it("rejects an unrelated terminal PR on a reused branch", async () => {
|
||||
it("prefers an exact terminal head and otherwise the most recently updated terminal PR", async () => {
|
||||
const owner = { login: "forkOwner" };
|
||||
const terminal = ({
|
||||
number,
|
||||
@@ -3869,15 +3368,9 @@ describe("ForgeService", () => {
|
||||
});
|
||||
for (const [headSha, expected] of [
|
||||
["old", 41],
|
||||
["other", undefined],
|
||||
["other", 42],
|
||||
] as const) {
|
||||
const runner = createScriptedRunner([
|
||||
JSON.stringify(older),
|
||||
JSON.stringify([older, newer]),
|
||||
...(headSha === "old"
|
||||
? [directCommitsJson(["old"])]
|
||||
: [directCommitsJson(["old"]), directCommitsJson(["new"])]),
|
||||
]);
|
||||
const runner = createScriptedRunner([JSON.stringify(older), JSON.stringify([older, newer])]);
|
||||
const service = createGitHubService({
|
||||
runner: runner.runner,
|
||||
resolveGhPath: async () => "/usr/bin/gh",
|
||||
@@ -3917,7 +3410,6 @@ describe("ForgeService", () => {
|
||||
const runner = createScriptedRunner([
|
||||
JSON.stringify(closedDraft),
|
||||
JSON.stringify([closedDraft, merged]),
|
||||
directCommitsJson(["exact"]),
|
||||
]);
|
||||
const service = createGitHubService({
|
||||
runner: runner.runner,
|
||||
@@ -3990,7 +3482,6 @@ describe("ForgeService", () => {
|
||||
parent: { owner: { login: "acme" }, name: "app" },
|
||||
}),
|
||||
"[]",
|
||||
directCommitsJson(["checkout-head"]),
|
||||
]);
|
||||
const service = createGitHubService({
|
||||
runner: runner.runner,
|
||||
@@ -4019,7 +3510,7 @@ describe("ForgeService", () => {
|
||||
for (const [state, headSha, updatedAt, expected] of [
|
||||
["OPEN", "other", "2026-07-16T12:00:00Z", 8],
|
||||
["CLOSED", "other", "2026-07-18T12:00:00Z", 7],
|
||||
["CLOSED", "other", "2026-07-18T12:00:00Z", undefined],
|
||||
["CLOSED", "other", "2026-07-18T12:00:00Z", 8],
|
||||
] as const) {
|
||||
const parent = {
|
||||
...local,
|
||||
@@ -4030,11 +3521,6 @@ describe("ForgeService", () => {
|
||||
headRefOid: headSha,
|
||||
updatedAt,
|
||||
};
|
||||
const commitResponses: string[] = [];
|
||||
if (state !== "OPEN") {
|
||||
commitResponses.push(directCommitsJson(["local-head"]));
|
||||
if (expected !== 7) commitResponses.push(directCommitsJson(["other"]));
|
||||
}
|
||||
const runner = createScriptedRunner([
|
||||
JSON.stringify(local),
|
||||
JSON.stringify({
|
||||
@@ -4044,7 +3530,6 @@ describe("ForgeService", () => {
|
||||
}),
|
||||
JSON.stringify([{ number: 8 }]),
|
||||
JSON.stringify(parent),
|
||||
...commitResponses,
|
||||
]);
|
||||
const service = createGitHubService({
|
||||
runner: runner.runner,
|
||||
@@ -4141,8 +3626,6 @@ describe("ForgeService", () => {
|
||||
stderr: "",
|
||||
};
|
||||
}
|
||||
if (args[0] === "api" && args[1] === "graphql")
|
||||
return { stdout: directCommitsJson([checkoutSha]), stderr: "" };
|
||||
if (args[0] === "api") {
|
||||
// Newest first, and the checkout is sitting on the oldest attempt.
|
||||
return {
|
||||
|
||||
@@ -1,7 +1,3 @@
|
||||
import {
|
||||
pullRequestContainsCommit,
|
||||
createPullRequestCommitReader,
|
||||
} from "./pull-request-contains-commit.js";
|
||||
import { z } from "zod";
|
||||
import {
|
||||
isGitHubHost,
|
||||
@@ -637,22 +633,6 @@ query PullRequestTimeline($owner: String!, $name: String!, $number: Int!) {
|
||||
}
|
||||
}`;
|
||||
|
||||
const PullRequestCommitPageSchema = z.object({
|
||||
nodes: z.array(z.object({ commit: z.object({ oid: z.string() }) })),
|
||||
pageInfo: z
|
||||
.object({ hasPreviousPage: z.boolean(), startCursor: z.string().nullable() })
|
||||
.refine(
|
||||
(page) => !page.hasPreviousPage || !!page.startCursor,
|
||||
"A previous commit page requires a cursor",
|
||||
),
|
||||
});
|
||||
|
||||
type PullRequestMembership =
|
||||
| { kind: "unknown" }
|
||||
| { kind: "partial"; commitOids: string[]; cursor: string }
|
||||
| { kind: "complete"; commitOids: string[] }
|
||||
| { kind: "failed"; error: unknown };
|
||||
|
||||
const BatchPollPrNodeSchema = z.object({
|
||||
number: z.number(),
|
||||
url: z.string().catch(""),
|
||||
@@ -1145,7 +1125,6 @@ interface GitHubBatchDistribution {
|
||||
}
|
||||
|
||||
interface ResolvedPullRequestCandidate {
|
||||
membership: PullRequestMembership;
|
||||
status: CurrentPullRequestStatus;
|
||||
headSha?: string;
|
||||
headRepositoryOwner?: string;
|
||||
@@ -1194,9 +1173,6 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G
|
||||
// Rollup nodes for merged/closed PRs keyed by repo#number@headOid: their
|
||||
// checks can no longer change, so each is fetched at most once per daemon run.
|
||||
const frozenPullRequestChecksCache = new Map<string, unknown[]>();
|
||||
const readCommits = createPullRequestCommitReader();
|
||||
const terminalCommitPages = new Map<string, PullRequestMembership>();
|
||||
const batchMembership = new WeakMap<BatchPollPrNode, PullRequestMembership>();
|
||||
const pollRepositoryRedirects = new Map<
|
||||
string,
|
||||
{ owner: string; name: string; headRepositoryOwner: string }
|
||||
@@ -1685,32 +1661,15 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G
|
||||
return;
|
||||
}
|
||||
|
||||
const repositories = new Map<GitHubBatchPollEntry, BatchPollRepository>();
|
||||
for (const [index, entry] of addressedEntries.entries()) {
|
||||
const parsed = BatchPollRepositorySchema.safeParse(response.aliases[batchAlias(index)]);
|
||||
if (parsed.success) repositories.set(entry, parsed.data);
|
||||
}
|
||||
const failedCommitEntries = await loadBatchCommitPages(addressedEntries, repositories);
|
||||
const distribution = distributeGitHubPollBatch({
|
||||
entries: addressedEntries,
|
||||
repositories,
|
||||
aliases: response.aliases,
|
||||
args,
|
||||
startedAt,
|
||||
failedCommitEntries,
|
||||
});
|
||||
if ((pollPausedUntilByHost.get(firstEntry.host) ?? 0) > deps.now()) {
|
||||
const error = new Error(
|
||||
"GitHub GraphQL polling is paused; pull request checks could not be refreshed",
|
||||
);
|
||||
for (const item of distribution.pendingChecks) {
|
||||
updatePollTargetAfterError(item.entry.target, error);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (distribution.pendingChecks.length > 0) {
|
||||
await loadBatchPullRequestChecks(distribution.pendingChecks, startedAt);
|
||||
}
|
||||
if ((pollPausedUntilByHost.get(firstEntry.host) ?? 0) > deps.now()) return;
|
||||
await Promise.all(distribution.legacyFallback.map((target) => runGitHubPoll(target)));
|
||||
if (distribution.redirected.length > 0) {
|
||||
await runGitHubPollBatch(distribution.redirected, startedAt);
|
||||
@@ -1721,7 +1680,6 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G
|
||||
entries: GitHubBatchPollEntry[];
|
||||
firstEntry: GitHubBatchPollEntry;
|
||||
args: string[];
|
||||
onError?: (entries: GitHubBatchPollEntry[], error: unknown) => void;
|
||||
}): Promise<GitHubBatchQueryResponse | null> {
|
||||
try {
|
||||
const stdout = await run(input.args, { cwd: input.firstEntry.target.cwd });
|
||||
@@ -1730,7 +1688,7 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G
|
||||
const isPaused = await pauseGitHubPollsAfterRateLimit(input.firstEntry, error);
|
||||
const partial = extractGraphqlBatchAliasesFromError(error);
|
||||
if (isPaused || !partial) {
|
||||
(input.onError ?? reportGitHubBatchError)(input.entries, error);
|
||||
reportGitHubBatchError(input.entries, error);
|
||||
return null;
|
||||
}
|
||||
const stdout = error instanceof GitHubCommandError ? (error.stdout ?? "") : "";
|
||||
@@ -1744,145 +1702,21 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G
|
||||
}
|
||||
}
|
||||
|
||||
function collectBatchCommitPages(
|
||||
entries: GitHubBatchPollEntry[],
|
||||
repositories: Map<GitHubBatchPollEntry, BatchPollRepository>,
|
||||
): Array<{ entry: GitHubBatchPollEntry; node: BatchPollPrNode }> {
|
||||
const candidates: Array<{ entry: GitHubBatchPollEntry; node: BatchPollPrNode }> = [];
|
||||
for (const entry of entries) {
|
||||
const repository = repositories.get(entry);
|
||||
if (!repository || (repository.isFork && repository.parent)) continue;
|
||||
const nodes = batchPollNodesForWorkspace(entry, repository);
|
||||
if (nodes.some((node) => node.state === "OPEN")) continue;
|
||||
for (const node of nodes) {
|
||||
batchMembership.set(
|
||||
node,
|
||||
terminalCommitPages.get(batchCommitKey(entry, node)) ?? { kind: "unknown" },
|
||||
);
|
||||
if (entry.target.headSha) candidates.push({ entry, node });
|
||||
}
|
||||
}
|
||||
return candidates;
|
||||
}
|
||||
|
||||
function batchCommitKey(entry: GitHubBatchPollEntry, node: BatchPollPrNode): string {
|
||||
return `${entry.host}/${entry.owner}/${entry.name}#${node.number}@${node.headRefOid}`;
|
||||
}
|
||||
|
||||
async function loadBatchCommitPages(
|
||||
entries: GitHubBatchPollEntry[],
|
||||
repositories: Map<GitHubBatchPollEntry, BatchPollRepository>,
|
||||
): Promise<Set<GitHubBatchPollEntry>> {
|
||||
const pending = collectBatchCommitPages(entries, repositories);
|
||||
while (pending.length) {
|
||||
const blocked = new Set<GitHubBatchPollEntry>();
|
||||
const needing = unresolvedBatchCommitPages(pending).filter(({ entry, node }) => {
|
||||
if (batchMembership.get(node)?.kind === "failed") blocked.add(entry);
|
||||
return !blocked.has(entry);
|
||||
});
|
||||
if (!needing.length) break;
|
||||
const fields = needing.map(({ entry, node }, index) => {
|
||||
const membership = batchMembership.get(node);
|
||||
const cursor = membership?.kind === "partial" ? membership.cursor : null;
|
||||
return `${batchAlias(index)}: repository(owner: ${graphqlString(entry.owner)}, name: ${graphqlString(entry.name)}) { pullRequest(number: ${node.number}) { commits(last:100${cursor ? `, before:${graphqlString(cursor)}` : ""}) { nodes { commit { oid } } pageInfo { hasPreviousPage startCursor } } } }`;
|
||||
});
|
||||
const args = [
|
||||
"api",
|
||||
"graphql",
|
||||
"-f",
|
||||
`query=query PaseoBatchCommitPages { rateLimit { limit remaining resetAt } ${fields.join("\n")} }`,
|
||||
];
|
||||
const needingEntries = [...new Set(needing.map(({ entry }) => entry))];
|
||||
const response = await loadGitHubPollBatchResponse({
|
||||
entries: needingEntries,
|
||||
firstEntry: needingEntries[0]!,
|
||||
args,
|
||||
onError: (affected, error) => {
|
||||
for (const { entry, node } of needing)
|
||||
if (affected.includes(entry)) batchMembership.set(node, { kind: "failed", error });
|
||||
},
|
||||
});
|
||||
if (!response) break;
|
||||
const rateLimit = parseGraphqlBatchRateLimit(response.stdout);
|
||||
if (rateLimit && pauseGitHubPollsAtReserve(entries[0]!.host, rateLimit)) {
|
||||
const error = new GitHubGraphqlPollPausedError(rateLimit);
|
||||
for (const { node } of needing) batchMembership.set(node, { kind: "failed", error });
|
||||
break;
|
||||
}
|
||||
for (const [index, { entry, node }] of needing.entries()) {
|
||||
const parsed = z
|
||||
.object({
|
||||
pullRequest: z.object({ commits: PullRequestCommitPageSchema }),
|
||||
})
|
||||
.safeParse(response.aliases[batchAlias(index)]);
|
||||
if (!parsed.success) {
|
||||
batchMembership.set(node, { kind: "failed", error: parsed.error });
|
||||
continue;
|
||||
}
|
||||
const page = parsed.data.pullRequest.commits;
|
||||
const previous = batchMembership.get(node);
|
||||
const commitOids = [
|
||||
...(previous?.kind === "partial" ? previous.commitOids : []),
|
||||
...page.nodes.map(({ commit }) => commit.oid),
|
||||
];
|
||||
const membership: PullRequestMembership =
|
||||
page.pageInfo.hasPreviousPage && page.pageInfo.startCursor
|
||||
? { kind: "partial", commitOids, cursor: page.pageInfo.startCursor }
|
||||
: { kind: "complete", commitOids };
|
||||
batchMembership.set(node, membership);
|
||||
const key = batchCommitKey(entry, node);
|
||||
terminalCommitPages.delete(key);
|
||||
terminalCommitPages.set(key, membership);
|
||||
if (terminalCommitPages.size > 512)
|
||||
terminalCommitPages.delete(terminalCommitPages.keys().next().value!);
|
||||
}
|
||||
}
|
||||
return reportUnresolvedCommitReads(pending);
|
||||
}
|
||||
|
||||
function unresolvedBatchCommitPages(
|
||||
candidates: Array<{ entry: GitHubBatchPollEntry; node: BatchPollPrNode }>,
|
||||
): Array<{ entry: GitHubBatchPollEntry; node: BatchPollPrNode }> {
|
||||
const byEntry = new Map<GitHubBatchPollEntry, BatchPollPrNode[]>();
|
||||
for (const { entry, node } of candidates) {
|
||||
const nodes = byEntry.get(entry) ?? [];
|
||||
nodes.push(node);
|
||||
byEntry.set(entry, nodes);
|
||||
}
|
||||
return [...byEntry].flatMap(([entry, nodes]) =>
|
||||
inspectBatchPollCandidates(entry, nodes).pending.map((node) => ({ entry, node })),
|
||||
);
|
||||
}
|
||||
|
||||
function reportUnresolvedCommitReads(
|
||||
candidates: Array<{ entry: GitHubBatchPollEntry; node: BatchPollPrNode }>,
|
||||
): Set<GitHubBatchPollEntry> {
|
||||
const failed = new Set<GitHubBatchPollEntry>();
|
||||
for (const { entry, node } of unresolvedBatchCommitPages(candidates)) {
|
||||
const membership = batchMembership.get(node);
|
||||
if (membership?.kind !== "failed" || failed.has(entry)) continue;
|
||||
failed.add(entry);
|
||||
updatePollTargetAfterError(entry.target, membership.error);
|
||||
}
|
||||
return failed;
|
||||
}
|
||||
|
||||
function distributeGitHubPollBatch(input: {
|
||||
entries: GitHubBatchPollEntry[];
|
||||
repositories: Map<GitHubBatchPollEntry, BatchPollRepository>;
|
||||
aliases: Record<string, unknown>;
|
||||
args: string[];
|
||||
startedAt: number;
|
||||
failedCommitEntries: ReadonlySet<GitHubBatchPollEntry>;
|
||||
}): GitHubBatchDistribution {
|
||||
const distribution: GitHubBatchDistribution = {
|
||||
pendingChecks: [],
|
||||
legacyFallback: [],
|
||||
redirected: [],
|
||||
};
|
||||
for (const entry of input.entries) {
|
||||
if (input.failedCommitEntries.has(entry)) continue;
|
||||
const repository = input.repositories.get(entry);
|
||||
if (!repository) {
|
||||
for (const [index, entry] of input.entries.entries()) {
|
||||
const aliasValue = input.aliases[batchAlias(index)];
|
||||
const repository = aliasValue ? BatchPollRepositorySchema.safeParse(aliasValue) : null;
|
||||
if (!repository?.success) {
|
||||
updatePollTargetAfterError(
|
||||
entry.target,
|
||||
new GitHubCommandError({
|
||||
@@ -1894,29 +1728,32 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G
|
||||
);
|
||||
continue;
|
||||
}
|
||||
if (repository.isFork && repository.parent) {
|
||||
const forkOwner = repository.owner?.login ?? entry.owner;
|
||||
if (repository.data.isFork && repository.data.parent) {
|
||||
const forkOwner = repository.data.owner?.login ?? entry.owner;
|
||||
pollRepositoryRedirects.set(batchRepositoryRedirectKey(entry), {
|
||||
owner: repository.parent.owner.login,
|
||||
name: repository.parent.name,
|
||||
owner: repository.data.parent.owner.login,
|
||||
name: repository.data.parent.name,
|
||||
headRepositoryOwner: forkOwner,
|
||||
});
|
||||
distribution.redirected.push(entry);
|
||||
continue;
|
||||
}
|
||||
const node = selectBatchPollNode(entry, repository);
|
||||
const node = selectBatchPollNode(entry, repository.data);
|
||||
if (!node) {
|
||||
// Legacy fallback covers the two ways "no match" can be wrong: a fork
|
||||
// whose PR lives in the parent repository, and a full candidate page —
|
||||
// ten newer same-named fork PRs can crowd the checkout's own PR out of
|
||||
// the first:N window, so absence is only conclusive on a partial page.
|
||||
if (repository.isFork || repository.pullRequests.nodes.length >= BATCH_PR_CANDIDATE_LIMIT) {
|
||||
if (
|
||||
repository.data.isFork ||
|
||||
repository.data.pullRequests.nodes.length >= BATCH_PR_CANDIDATE_LIMIT
|
||||
) {
|
||||
distribution.legacyFallback.push(entry.target);
|
||||
} else {
|
||||
finalizeBatchPollTarget({
|
||||
entry,
|
||||
node: null,
|
||||
repository: repository,
|
||||
repository: repository.data,
|
||||
rollup: null,
|
||||
startedAt: input.startedAt,
|
||||
});
|
||||
@@ -1933,7 +1770,7 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G
|
||||
finalizeBatchPollTarget({
|
||||
entry,
|
||||
node,
|
||||
repository: repository,
|
||||
repository: repository.data,
|
||||
rollup: cachedRollup,
|
||||
startedAt: input.startedAt,
|
||||
});
|
||||
@@ -1941,7 +1778,7 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G
|
||||
distribution.pendingChecks.push({
|
||||
entry,
|
||||
node,
|
||||
repository: repository,
|
||||
repository: repository.data,
|
||||
cacheKey: frozenKey,
|
||||
});
|
||||
}
|
||||
@@ -1965,59 +1802,41 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G
|
||||
return `${entry.host}\n${entry.originOwner}/${entry.originName}`;
|
||||
}
|
||||
|
||||
function batchPollNodesForWorkspace(
|
||||
entry: GitHubBatchPollEntry,
|
||||
repository: BatchPollRepository,
|
||||
): BatchPollPrNode[] {
|
||||
// Branch names also match other forks; reject those before loading commit lists.
|
||||
const owner = entry.target.headRepositoryOwner ?? entry.headRepositoryOwner;
|
||||
const selfOwner = (repository.owner?.login ?? entry.owner).toLowerCase();
|
||||
return repository.pullRequests.nodes.filter(
|
||||
(node) =>
|
||||
node.headRefName === entry.target.headRef &&
|
||||
(owner
|
||||
? node.headRepositoryOwner?.login === owner
|
||||
: node.headRepositoryOwner?.login?.toLowerCase() === selfOwner),
|
||||
);
|
||||
}
|
||||
|
||||
function selectBatchPollNode(
|
||||
entry: GitHubBatchPollEntry,
|
||||
repository: BatchPollRepository,
|
||||
): BatchPollPrNode | null {
|
||||
const resolution = inspectBatchPollCandidates(
|
||||
entry,
|
||||
batchPollNodesForWorkspace(entry, repository),
|
||||
);
|
||||
return resolution.pending.length ? null : resolution.match;
|
||||
}
|
||||
|
||||
function inspectBatchPollCandidates(
|
||||
entry: GitHubBatchPollEntry,
|
||||
nodes: BatchPollPrNode[],
|
||||
): { match: BatchPollPrNode | null; pending: BatchPollPrNode[] } {
|
||||
// Prefer the canonical owner from the response: the origin slug can carry
|
||||
// stale casing or a pre-transfer owner that repository() redirects from.
|
||||
const selfOwner = (repository.owner?.login ?? entry.owner).toLowerCase();
|
||||
const headRepositoryOwner = entry.target.headRepositoryOwner ?? entry.headRepositoryOwner;
|
||||
const nodeByCandidate = new Map<ResolvedPullRequestCandidate, BatchPollPrNode>();
|
||||
const candidates: ResolvedPullRequestCandidate[] = [];
|
||||
for (const node of nodes) {
|
||||
for (const node of repository.pullRequests.nodes) {
|
||||
const candidate = toCurrentPullRequestCandidate(
|
||||
toBatchCurrentPullRequestItem(node, undefined),
|
||||
entry.target.headRef,
|
||||
);
|
||||
if (!candidate) continue;
|
||||
candidate.membership = batchMembership.get(node) ?? { kind: "unknown" };
|
||||
if (!candidate) {
|
||||
continue;
|
||||
}
|
||||
// pullRequests(headRefName:) also matches forks whose branch shares the
|
||||
// name. Without a fork-owner hint the workspace branch lives in this
|
||||
// repository, so only self-owned heads are real candidates (mirrors
|
||||
// `gh pr view` resolving the current branch's own PR).
|
||||
if (!headRepositoryOwner && candidate.headRepositoryOwner?.toLowerCase() !== selfOwner) {
|
||||
continue;
|
||||
}
|
||||
nodeByCandidate.set(candidate, node);
|
||||
candidates.push(candidate);
|
||||
}
|
||||
const resolution = inspectPullRequestCandidates({
|
||||
const match = pickPullRequestCandidate({
|
||||
candidates,
|
||||
headRef: entry.target.headRef,
|
||||
headSha: entry.target.headSha,
|
||||
headRepositoryOwner: entry.target.headRepositoryOwner ?? entry.headRepositoryOwner,
|
||||
headRepositoryOwner,
|
||||
});
|
||||
return {
|
||||
match: resolution.match ? nodeByCandidate.get(resolution.match)! : null,
|
||||
pending: resolution.pending.map((candidate) => nodeByCandidate.get(candidate)!),
|
||||
};
|
||||
return match ? (nodeByCandidate.get(match) ?? null) : null;
|
||||
}
|
||||
|
||||
async function loadBatchPullRequestChecks(
|
||||
@@ -2142,14 +1961,7 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G
|
||||
toBatchCurrentPullRequestItem(node, input.rollup ?? undefined),
|
||||
entry.target.headRef,
|
||||
);
|
||||
const membership = batchMembership.get(node);
|
||||
const commitOids =
|
||||
membership?.kind === "complete" || membership?.kind === "partial"
|
||||
? membership.commitOids
|
||||
: undefined;
|
||||
status = built
|
||||
? { ...built, commitOids, forgeSpecific: { forge: "github", ...facts } }
|
||||
: null;
|
||||
status = built ? { ...built, forgeSpecific: { forge: "github", ...facts } } : null;
|
||||
}
|
||||
const cacheKey = buildCacheKey({
|
||||
cwd: entry.target.cwd,
|
||||
@@ -2365,7 +2177,6 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G
|
||||
readOptions: input,
|
||||
load: async () => {
|
||||
const status = await resolveCurrentPullRequestView({
|
||||
readCommits,
|
||||
cwd: input.cwd,
|
||||
headRef: input.headRef,
|
||||
headSha: input.headSha,
|
||||
@@ -3178,13 +2989,20 @@ async function resolveCurrentPullRequestView(options: {
|
||||
headRef: string;
|
||||
headSha?: string;
|
||||
headRepositoryOwner?: string;
|
||||
readCommits: ReturnType<typeof createPullRequestCommitReader>;
|
||||
run: (args: string[], options: GitHubCommandRunnerOptions) => Promise<string>;
|
||||
}): Promise<CurrentPullRequestStatus | null> {
|
||||
const viewCandidate = await tryCurrentPullRequestView(options);
|
||||
const viewCandidates = viewCandidate ? [viewCandidate] : [];
|
||||
const open = pickPullRequestCandidate({ ...options, candidates: viewCandidates });
|
||||
if (open?.status.state === "open") return open.status;
|
||||
const viewMatch = viewCandidate
|
||||
? pickPullRequestCandidate({
|
||||
candidates: [viewCandidate],
|
||||
headRef: options.headRef,
|
||||
headSha: options.headSha,
|
||||
headRepositoryOwner: options.headRepositoryOwner,
|
||||
})
|
||||
: null;
|
||||
if (viewMatch?.status.state === "open") {
|
||||
return viewMatch.status;
|
||||
}
|
||||
|
||||
let headRepositoryOwner = options.headRepositoryOwner;
|
||||
|
||||
@@ -3194,17 +3012,13 @@ async function resolveCurrentPullRequestView(options: {
|
||||
const parentOwner = repo?.parent?.owner?.login;
|
||||
const parentName = repo?.parent?.name;
|
||||
if (!forkOwner) {
|
||||
const match = await loadAndPickPullRequestCandidate({
|
||||
...options,
|
||||
candidates: viewCandidates,
|
||||
});
|
||||
return match?.status ?? null;
|
||||
return viewMatch?.status ?? null;
|
||||
}
|
||||
if (parentOwner && parentName) {
|
||||
return resolveForkPullRequestView({
|
||||
...options,
|
||||
forkOwner,
|
||||
viewCandidate,
|
||||
viewMatch,
|
||||
repo: `${parentOwner}/${parentName}`,
|
||||
});
|
||||
}
|
||||
@@ -3214,14 +3028,10 @@ async function resolveCurrentPullRequestView(options: {
|
||||
const candidates = await listCurrentPullRequestCandidates({
|
||||
cwd: options.cwd,
|
||||
headRef: options.headRef,
|
||||
headRepositoryOwner,
|
||||
run: options.run,
|
||||
});
|
||||
const match = await loadAndPickPullRequestCandidate({
|
||||
readCommits: options.readCommits,
|
||||
cwd: options.cwd,
|
||||
run: options.run,
|
||||
candidates: [...candidates, ...viewCandidates],
|
||||
const match = pickPullRequestCandidate({
|
||||
candidates: viewMatch ? [...candidates, viewMatch] : candidates,
|
||||
headRef: options.headRef,
|
||||
headSha: options.headSha,
|
||||
headRepositoryOwner,
|
||||
@@ -3242,9 +3052,8 @@ async function resolveForkPullRequestView(options: {
|
||||
headRef: string;
|
||||
headSha?: string;
|
||||
forkOwner: string;
|
||||
viewCandidate: ResolvedPullRequestCandidate | null;
|
||||
viewMatch: ResolvedPullRequestCandidate | null;
|
||||
repo: string;
|
||||
readCommits: ReturnType<typeof createPullRequestCommitReader>;
|
||||
run: (args: string[], options: GitHubCommandRunnerOptions) => Promise<string>;
|
||||
}): Promise<CurrentPullRequestStatus | null> {
|
||||
const numbers = await listForkPullRequestNumbers(options);
|
||||
@@ -3258,20 +3067,16 @@ async function resolveForkPullRequestView(options: {
|
||||
}),
|
||||
),
|
||||
);
|
||||
const match = await loadAndPickPullRequestCandidate({
|
||||
readCommits: options.readCommits,
|
||||
cwd: options.cwd,
|
||||
run: options.run,
|
||||
const match = pickPullRequestCandidate({
|
||||
candidates: [
|
||||
...candidates.filter(
|
||||
(candidate): candidate is ResolvedPullRequestCandidate =>
|
||||
candidate !== null && candidate.headRepositoryOwner === options.forkOwner,
|
||||
),
|
||||
...(options.viewCandidate ? [options.viewCandidate] : []),
|
||||
...(options.viewMatch ? [options.viewMatch] : []),
|
||||
],
|
||||
headRef: options.headRef,
|
||||
headSha: options.headSha,
|
||||
headRepositoryOwner: options.forkOwner,
|
||||
});
|
||||
return match?.status ?? null;
|
||||
}
|
||||
@@ -3365,62 +3170,6 @@ async function loadPullRequestGithubFacts(options: {
|
||||
}
|
||||
}
|
||||
|
||||
async function loadAndPickPullRequestCandidate(
|
||||
options: Parameters<typeof pickPullRequestCandidate>[0] & {
|
||||
cwd: string;
|
||||
readCommits: ReturnType<typeof createPullRequestCommitReader>;
|
||||
run: (args: string[], options: GitHubCommandRunnerOptions) => Promise<string>;
|
||||
},
|
||||
): Promise<ResolvedPullRequestCandidate | null> {
|
||||
for (;;) {
|
||||
const resolution = inspectPullRequestCandidates(options);
|
||||
const next = resolution.pending[0];
|
||||
if (!next) return resolution.match;
|
||||
await completeCandidateCommits(next, options);
|
||||
}
|
||||
}
|
||||
|
||||
async function completeCandidateCommits(
|
||||
candidate: ResolvedPullRequestCandidate,
|
||||
options: {
|
||||
cwd: string;
|
||||
headRef: string;
|
||||
headRepositoryOwner?: string;
|
||||
readCommits: ReturnType<typeof createPullRequestCommitReader>;
|
||||
run: (args: string[], options: GitHubCommandRunnerOptions) => Promise<string>;
|
||||
},
|
||||
): Promise<void> {
|
||||
const status = candidate.status;
|
||||
if (!isCandidateForHeadRef(candidate, options.headRef)) return;
|
||||
if (options.headRepositoryOwner && candidate.headRepositoryOwner !== options.headRepositoryOwner)
|
||||
return;
|
||||
if (status.state === "open" || candidate.membership.kind === "complete") return;
|
||||
const commitOids = await options.readCommits(`${status.url}@${status.headSha}`, async () => {
|
||||
const commits: string[] = [];
|
||||
let cursor: string | null = null;
|
||||
for (;;) {
|
||||
const query = `query { repository(owner:${graphqlString(status.repoOwner!)},name:${graphqlString(status.repoName!)}) { pullRequest(number:${status.number}) { commits(last:100${cursor ? `,before:${graphqlString(cursor)}` : ""}) { nodes { commit { oid } } pageInfo { hasPreviousPage startCursor } } } } }`;
|
||||
const stdout = await options.run(["api", "graphql", "-f", `query=${query}`], {
|
||||
cwd: options.cwd,
|
||||
});
|
||||
const page = z
|
||||
.object({
|
||||
data: z.object({
|
||||
repository: z.object({
|
||||
pullRequest: z.object({ commits: PullRequestCommitPageSchema }),
|
||||
}),
|
||||
}),
|
||||
})
|
||||
.parse(JSON.parse(stdout)).data.repository.pullRequest.commits;
|
||||
commits.push(...page.nodes.map(({ commit }) => commit.oid));
|
||||
if (!page.pageInfo?.hasPreviousPage) return commits;
|
||||
cursor = page.pageInfo.startCursor;
|
||||
}
|
||||
});
|
||||
candidate.membership = { kind: "complete", commitOids };
|
||||
status.commitOids = commitOids;
|
||||
}
|
||||
|
||||
async function tryCurrentPullRequestView(options: {
|
||||
cwd: string;
|
||||
headRef: string;
|
||||
@@ -3434,11 +3183,10 @@ async function tryCurrentPullRequestView(options: {
|
||||
run: options.run,
|
||||
args,
|
||||
});
|
||||
const candidate = parseCurrentPullRequestCandidate(stdout, options.headRef, {
|
||||
return parseCurrentPullRequestCandidate(stdout, options.headRef, {
|
||||
args: [...args, "--json", CURRENT_PR_STATUS_FIELDS],
|
||||
cwd: options.cwd,
|
||||
});
|
||||
return candidate;
|
||||
} catch (error) {
|
||||
if (isNoPullRequestFoundError(error)) {
|
||||
return null;
|
||||
@@ -3450,7 +3198,6 @@ async function tryCurrentPullRequestView(options: {
|
||||
async function listCurrentPullRequestCandidates(options: {
|
||||
cwd: string;
|
||||
headRef: string;
|
||||
headRepositoryOwner?: string;
|
||||
run: (args: string[], options: GitHubCommandRunnerOptions) => Promise<string>;
|
||||
}): Promise<ResolvedPullRequestCandidate[]> {
|
||||
const args = ["pr", "list", "--state", "all", "--head", options.headRef, "--limit", "10"];
|
||||
@@ -3460,11 +3207,10 @@ async function listCurrentPullRequestCandidates(options: {
|
||||
run: options.run,
|
||||
args,
|
||||
});
|
||||
const candidates = parseCurrentPullRequestCandidateList(stdout, options.headRef, {
|
||||
return parseCurrentPullRequestCandidateList(stdout, options.headRef, {
|
||||
args: [...args, "--json", CURRENT_PR_STATUS_FIELDS],
|
||||
cwd: options.cwd,
|
||||
});
|
||||
return candidates;
|
||||
} catch (error) {
|
||||
if (isNoPullRequestFoundError(error)) {
|
||||
return [];
|
||||
@@ -3682,7 +3428,6 @@ function toCurrentPullRequestCandidate(
|
||||
const headSha = item.headRefOid;
|
||||
return {
|
||||
status,
|
||||
membership: { kind: "unknown" },
|
||||
updatedAt: item.updatedAt,
|
||||
...(headSha ? { headSha } : {}),
|
||||
...(headRepositoryOwner ? { headRepositoryOwner } : {}),
|
||||
@@ -3703,38 +3448,6 @@ function pickPullRequestCandidate(options: {
|
||||
headSha?: string;
|
||||
headRepositoryOwner?: string;
|
||||
}): ResolvedPullRequestCandidate | null {
|
||||
const result = inspectPullRequestCandidates(options);
|
||||
return result.pending.length ? null : result.match;
|
||||
}
|
||||
|
||||
function inspectPullRequestCandidates(options: Parameters<typeof pickPullRequestCandidate>[0]): {
|
||||
match: ResolvedPullRequestCandidate | null;
|
||||
pending: ResolvedPullRequestCandidate[];
|
||||
} {
|
||||
const matching = matchingPullRequestCandidates(options);
|
||||
const open = matching.find((candidate) => candidate.status.state === "open");
|
||||
if (open) return { match: open, pending: [] };
|
||||
const pending: ResolvedPullRequestCandidate[] = [];
|
||||
if (!options.headSha) return { match: null, pending };
|
||||
for (const candidate of matching) {
|
||||
if (
|
||||
pullRequestContainsCommit({
|
||||
workspaceCommit: options.headSha,
|
||||
pullRequestCommits:
|
||||
candidate.membership.kind === "complete" || candidate.membership.kind === "partial"
|
||||
? candidate.membership.commitOids
|
||||
: undefined,
|
||||
})
|
||||
)
|
||||
return { match: candidate, pending };
|
||||
if (candidate.membership.kind !== "complete") pending.push(candidate);
|
||||
}
|
||||
return { match: null, pending };
|
||||
}
|
||||
|
||||
function matchingPullRequestCandidates(
|
||||
options: Parameters<typeof pickPullRequestCandidate>[0],
|
||||
): ResolvedPullRequestCandidate[] {
|
||||
const matching = options.candidates.filter((candidate) => {
|
||||
if (!isCandidateForHeadRef(candidate, options.headRef)) {
|
||||
return false;
|
||||
@@ -3747,7 +3460,7 @@ function matchingPullRequestCandidates(
|
||||
matching.sort((left, right) =>
|
||||
comparePullRequestCandidatePreference(left, right, options.headSha),
|
||||
);
|
||||
return matching;
|
||||
return matching[0] ?? null;
|
||||
}
|
||||
|
||||
function comparePullRequestCandidatePreference(
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
import { createPullRequestHistory } from "../test-utils/pull-request-history.js";
|
||||
import { onTestFinished } from "vitest";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import type { PullRequestCommandStatus } from "./forge-service.js";
|
||||
@@ -377,7 +375,6 @@ describe("createGitLabService", () => {
|
||||
const { service, calls } = makeService((args) => {
|
||||
if (args[1] === "list") return ok(JSON.stringify([newestStale, exactOlder]));
|
||||
if (args[1] === "view" && args[2] === "270") return ok(JSON.stringify(exactOlder));
|
||||
if (args[1]?.includes("/commits?")) return ok(JSON.stringify([{ id: checkoutSha }]));
|
||||
if (args[0] === "api") return ok("{}");
|
||||
throw new Error(`unexpected call: ${args.join(" ")}`);
|
||||
});
|
||||
@@ -389,93 +386,25 @@ describe("createGitLabService", () => {
|
||||
});
|
||||
|
||||
expect(status?.number).toBe(270);
|
||||
expect(calls[2]).toEqual(["mr", "view", "270", "-F", "json"]);
|
||||
});
|
||||
|
||||
it("checks fork MR membership on a reused base branch and caches successful lists", async () => {
|
||||
const requests = Array.from({ length: 100 }, (_, index) => ({
|
||||
...OPEN_MR,
|
||||
iid: index + 1,
|
||||
source_branch: "main",
|
||||
state: "closed",
|
||||
source_project_id: 202,
|
||||
target_project_id: 101,
|
||||
sha: `fork-head-${index}`,
|
||||
web_url: `https://gitlab.example.com/example-group/example-project/-/merge_requests/${index + 1}`,
|
||||
}));
|
||||
let commitReads = 0;
|
||||
const { service } = makeService((args) => {
|
||||
if (args[1] === "list") return ok(JSON.stringify(requests));
|
||||
if (args[1]?.includes("/commits?")) {
|
||||
commitReads++;
|
||||
return ok(JSON.stringify([{ id: "fork-own-commit" }]));
|
||||
}
|
||||
if (args[1] === "view") return ok(JSON.stringify(requests[0]));
|
||||
return ok("{}");
|
||||
});
|
||||
const input = { cwd: "/repo", headRef: "main", headSha: "inherited-base" };
|
||||
await expect(service.getCurrentPullRequestStatus(input)).resolves.toBeNull();
|
||||
expect(commitReads).toBe(100);
|
||||
await expect(
|
||||
service.getCurrentPullRequestStatus({ ...input, force: true }),
|
||||
).resolves.toBeNull();
|
||||
expect(commitReads).toBe(100);
|
||||
await expect(
|
||||
service.getCurrentPullRequestStatus({ ...input, headSha: "fork-own-commit", force: true }),
|
||||
).resolves.toMatchObject({ number: 1, state: "closed" });
|
||||
expect(commitReads).toBe(100);
|
||||
});
|
||||
|
||||
it("rejects an unknown newer MR instead of choosing an older match and retries", async () => {
|
||||
const older = { ...OPEN_MR, iid: 270, state: "merged", sha: "older-head" };
|
||||
const newer = { ...older, iid: 271, state: "closed", sha: "newer-head" };
|
||||
let failedReads = 0;
|
||||
const { service } = makeService((args) => {
|
||||
if (args[1] === "list") return ok(JSON.stringify([newer, older]));
|
||||
if (args[1]?.includes("/271/commits?")) {
|
||||
failedReads++;
|
||||
if (failedReads < 3) throw new Error("HTTP 502");
|
||||
return ok(JSON.stringify([{ id: "workspace-commit" }]));
|
||||
}
|
||||
if (args[1]?.includes("/270/commits?"))
|
||||
return ok(JSON.stringify([{ id: "workspace-commit" }]));
|
||||
if (args[1] === "view") return ok(JSON.stringify(newer));
|
||||
return ok("{}");
|
||||
});
|
||||
const input = { cwd: "/repo", headRef: OPEN_MR.source_branch, headSha: "workspace-commit" };
|
||||
await expect(service.getCurrentPullRequestStatus(input)).rejects.toThrow(
|
||||
"GitLab CLI command failed",
|
||||
);
|
||||
await expect(
|
||||
service.getCurrentPullRequestStatus({ ...input, force: true, reason: "retry" }),
|
||||
).rejects.toThrow("GitLab CLI command failed");
|
||||
expect(failedReads).toBe(2);
|
||||
await expect(
|
||||
service.getCurrentPullRequestStatus({ ...input, force: true, reason: "recovered" }),
|
||||
).resolves.toMatchObject({ number: 271 });
|
||||
expect(calls[1]).toEqual(["mr", "view", "270", "-F", "json"]);
|
||||
});
|
||||
|
||||
it("keeps a merged MR when its remote head advances beyond the checkout", async () => {
|
||||
const history = createPullRequestHistory();
|
||||
onTestFinished(history.dispose);
|
||||
const { cwd, workspaceCommit, pullRequestCommit } = history;
|
||||
const stale = {
|
||||
...OPEN_MR,
|
||||
state: "merged",
|
||||
source_branch: "dev",
|
||||
sha: pullRequestCommit,
|
||||
sha: "1111111111111111111111111111111111111111",
|
||||
};
|
||||
const { service, calls } = makeService((args) => {
|
||||
if (args[1]?.includes("/commits?"))
|
||||
return ok(JSON.stringify([{ id: workspaceCommit }, { id: pullRequestCommit }]));
|
||||
return ok(JSON.stringify(args[1] === "list" ? [stale] : stale));
|
||||
});
|
||||
const { service, calls } = makeService((args) =>
|
||||
ok(JSON.stringify(args[1] === "list" ? [stale] : stale)),
|
||||
);
|
||||
|
||||
await expect(
|
||||
service.getCurrentPullRequestStatus({
|
||||
cwd,
|
||||
cwd: "/repo",
|
||||
headRef: "dev",
|
||||
headSha: workspaceCommit,
|
||||
headSha: "2222222222222222222222222222222222222222",
|
||||
}),
|
||||
).resolves.toMatchObject({ state: "merged" });
|
||||
expect(calls[0]).toEqual(currentMrListArgs("dev"));
|
||||
|
||||
@@ -1,7 +1,3 @@
|
||||
import {
|
||||
pullRequestContainsCommit,
|
||||
createPullRequestCommitReader,
|
||||
} from "./pull-request-contains-commit.js";
|
||||
import { z } from "zod";
|
||||
import { parseGitRemoteLocation } from "@getpaseo/protocol/git-remote";
|
||||
import { findExecutable } from "../executable-resolution/executable-resolution.js";
|
||||
@@ -157,7 +153,6 @@ const GitLabMergeRequestSchema = z
|
||||
source_branch: z.string(),
|
||||
target_branch: z.string(),
|
||||
sha: z.string().optional(),
|
||||
commitOids: z.array(z.string()).optional(),
|
||||
source_project_id: z.number().nullable().optional(),
|
||||
target_project_id: z.number().nullable().optional(),
|
||||
draft: z.boolean().optional(),
|
||||
@@ -744,7 +739,6 @@ function toCurrentPullRequestStatus(
|
||||
baseRefName: mr.target_branch,
|
||||
headRefName: mr.source_branch,
|
||||
...(mr.sha ? { headSha: mr.sha } : {}),
|
||||
commitOids: mr.commitOids,
|
||||
isMerged: mr.state === "merged" || mr.merged_at != null,
|
||||
isDraft: mr.draft ?? mr.work_in_progress ?? false,
|
||||
mergeable: mapMergeable(mr),
|
||||
@@ -925,7 +919,6 @@ function gitLabNumberQuery(query: string | undefined): string | null {
|
||||
}
|
||||
|
||||
export function createGitLabService(options: CreateGitLabServiceOptions = {}): ForgeService {
|
||||
const readRequestCommits = createPullRequestCommitReader();
|
||||
const runner = options.runner ?? runGlabCommand;
|
||||
const resolveGlab = createCachedCliPathResolver(options.resolveGlabPath ?? resolveGlabPath);
|
||||
const resolveRemoteUrl = options.resolveRemoteUrl ?? defaultResolveRemoteUrl;
|
||||
@@ -999,32 +992,15 @@ export function createGitLabService(options: CreateGitLabServiceOptions = {}): F
|
||||
): Promise<GitLabMergeRequest | null> {
|
||||
const mergeRequests = await listMergeRequestsBySourceBranch(cwd, headRef);
|
||||
const candidates = mergeRequests.filter((mr) => mr.source_branch === headRef);
|
||||
const open = candidates.find((candidate) => mapMergeRequestState(candidate.state) === "open");
|
||||
if (open) return viewMergeRequest(cwd, String(open.iid));
|
||||
candidates.sort((left, right) => Number(right.sha === headSha) - Number(left.sha === headSha));
|
||||
for (const mr of candidates) {
|
||||
const project = mr.target_project_id ?? extractProjectPath(mr.references?.full);
|
||||
if (project === undefined) continue;
|
||||
const commitOids = await readRequestCommits(`${mr.web_url}@${mr.sha}`, async () => {
|
||||
const result: string[] = [];
|
||||
for (let page = 1; ; page++) {
|
||||
const commits = await runJson(
|
||||
[
|
||||
"api",
|
||||
`projects/${encodeURIComponent(project)}/merge_requests/${mr.iid}/commits?per_page=100&page=${page}`,
|
||||
],
|
||||
{ cwd },
|
||||
z.array(z.object({ id: z.string() })),
|
||||
);
|
||||
result.push(...commits.map((commit) => commit.id));
|
||||
if (commits.length < 100) return result;
|
||||
}
|
||||
});
|
||||
if (pullRequestContainsCommit({ workspaceCommit: headSha, pullRequestCommits: commitOids })) {
|
||||
return { ...(await viewMergeRequest(cwd, String(mr.iid))), commitOids };
|
||||
}
|
||||
}
|
||||
return null;
|
||||
const match =
|
||||
candidates.find((mr) => mapMergeRequestState(mr.state) === "open") ??
|
||||
candidates.find(
|
||||
(mr) =>
|
||||
mapMergeRequestState(mr.state) !== "open" && headSha !== undefined && mr.sha === headSha,
|
||||
) ??
|
||||
candidates[0] ??
|
||||
null;
|
||||
return match ? viewMergeRequest(cwd, String(match.iid)) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,23 +0,0 @@
|
||||
/** Only commits introduced by the request establish workspace ownership. */
|
||||
export function pullRequestContainsCommit(input: {
|
||||
workspaceCommit?: string;
|
||||
pullRequestCommits?: readonly string[];
|
||||
}): boolean {
|
||||
return !!input.workspaceCommit && !!input.pullRequestCommits?.includes(input.workspaceCommit);
|
||||
}
|
||||
|
||||
/** Terminal commit lists are immutable for a request head. Failed reads remain retryable. */
|
||||
export function createPullRequestCommitReader() {
|
||||
const cache = new Map<string, Promise<string[]>>();
|
||||
return (key: string, load: () => Promise<string[]>): Promise<string[]> => {
|
||||
const existing = cache.get(key);
|
||||
if (existing) return existing;
|
||||
const commits = load().catch((error: unknown) => {
|
||||
cache.delete(key);
|
||||
throw error;
|
||||
});
|
||||
cache.set(key, commits);
|
||||
if (cache.size > 1024) cache.delete(cache.keys().next().value!);
|
||||
return commits;
|
||||
};
|
||||
}
|
||||
@@ -355,22 +355,13 @@ it.each(["detach", "closeTerminals"] as const)(
|
||||
...nodeTerminalCommand("setInterval(() => {}, 1000)"),
|
||||
});
|
||||
const [record] = await workerRecords(paseoHome);
|
||||
const programPid = record!.terminals[0]!.pid;
|
||||
try {
|
||||
process.kill(record!.pid, "SIGKILL");
|
||||
await manager[operation]();
|
||||
await expect(
|
||||
manager.createTerminal({ workspaceId: "ws-stop-recovery", cwd: paseoHome }),
|
||||
).rejects.toBeInstanceOf(NoTerminalWorkerAvailableError);
|
||||
await manager.closeTerminals();
|
||||
expect(await workerRecords(paseoHome)).toEqual([]);
|
||||
} finally {
|
||||
// A hard-crashed Windows worker can leave its terminal program alive.
|
||||
// The test owns that program even after the manager retires its record.
|
||||
if (isProcessAlive(programPid)) process.kill(programPid, "SIGKILL");
|
||||
await waitForCondition(() => !isProcessAlive(programPid), 5000);
|
||||
await waitForCondition(() => !isProcessAlive(record!.pid), 5000);
|
||||
}
|
||||
process.kill(record!.pid, "SIGKILL");
|
||||
await manager[operation]();
|
||||
await expect(
|
||||
manager.createTerminal({ workspaceId: "ws-stop-recovery", cwd: paseoHome }),
|
||||
).rejects.toBeInstanceOf(NoTerminalWorkerAvailableError);
|
||||
await manager.closeTerminals();
|
||||
expect(await workerRecords(paseoHome)).toEqual([]);
|
||||
},
|
||||
30000,
|
||||
);
|
||||
|
||||
@@ -1,44 +0,0 @@
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { mkdirSync, mkdtempSync, rmSync } from "node:fs";
|
||||
import { resolve, join } from "node:path";
|
||||
|
||||
export function createPullRequestHistory() {
|
||||
const root = resolve(import.meta.dirname, "../../../../.artifacts");
|
||||
mkdirSync(root, { recursive: true });
|
||||
const directory = mkdtempSync(join(root, "pr-history-"));
|
||||
const remote = join(directory, "remote");
|
||||
const cwd = join(directory, "checkout");
|
||||
const git = (path: string, args: string[]) =>
|
||||
execFileSync("git", args, {
|
||||
cwd: path,
|
||||
encoding: "utf8",
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
}).trim();
|
||||
git(directory, ["init", remote]);
|
||||
const commit = (message: string) =>
|
||||
git(remote, [
|
||||
"-c",
|
||||
"user.name=Test",
|
||||
"-c",
|
||||
"user.email=test@example.com",
|
||||
"-c",
|
||||
"commit.gpgsign=false",
|
||||
"commit",
|
||||
"--allow-empty",
|
||||
"-m",
|
||||
message,
|
||||
]);
|
||||
commit("workspace");
|
||||
const workspaceCommit = git(remote, ["rev-parse", "HEAD"]);
|
||||
git(directory, ["clone", remote, cwd]);
|
||||
commit("remote branch update");
|
||||
const pullRequestCommit = git(remote, ["rev-parse", "HEAD"]);
|
||||
return {
|
||||
cwd,
|
||||
remote,
|
||||
workspaceCommit,
|
||||
pullRequestCommit,
|
||||
git: (args: string[]) => git(cwd, args),
|
||||
dispose: () => rmSync(directory, { recursive: true, force: true }),
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user