mirror of
https://github.com/getpaseo/paseo.git
synced 2026-11-18 06:15:02 +00:00
Compare commits
20
Commits
@@ -121,6 +121,14 @@ from `packages/app/android`:
|
||||
|
||||
These check terminal arrow ownership, held-key repeats and modifiers, and ordinary text-field editing.
|
||||
|
||||
Run the display density regression tests the same way:
|
||||
|
||||
```bash
|
||||
./gradlew :paseo-display-metrics:connectedDebugAndroidTest --no-daemon --max-workers=2 -Dorg.gradle.parallel=false
|
||||
```
|
||||
|
||||
These check that React Native sizes text at the window's density when the window is on another display, such as Samsung DeX.
|
||||
|
||||
### Diagnostic logs without ADB
|
||||
|
||||
In a dogfood build, open Android's Files app → Downloads → **Paseo diagnostics** and share all
|
||||
|
||||
@@ -117,7 +117,10 @@ There is no renderer prep/restore handshake or lifetime background-throttling ov
|
||||
Screenshot capture temporarily enables frame production inside the shared serialized queue,
|
||||
restores the previous throttling policy on success or failure, and retains a 5-second capture budget.
|
||||
The browser tool takes one viewport frame through Electron's frame subscription and releases the
|
||||
subscription on completion or cancellation. A resized resident guest can produce fresh pixels
|
||||
subscription on completion or cancellation. Guest pages have a transparent base background, so a page
|
||||
that has painted nothing yet (a dev server hiding `body` until its JS boots) produces frames where
|
||||
every pixel is transparent. Both screenshot paths skip those frames and return `screenshot_no_frame`
|
||||
when the capture budget expires without a painted one. A resized resident guest can produce fresh pixels
|
||||
while `capturePage()` leaves its surface-copy request pending; waiting for animation frames or
|
||||
retrying the copy does not repair that state. Full-page screenshots retain the CDP path with layout
|
||||
metrics and screenshot clip.
|
||||
|
||||
@@ -99,8 +99,10 @@ Register the adapter in `defaultForgeRegistry` with:
|
||||
|
||||
Current change-request lookup matches the branch and repository for both open and
|
||||
terminal requests. Prefer an open request, then a terminal request at the local
|
||||
HEAD, then the most recently updated terminal request. A reused branch can show
|
||||
its previous request until a new one opens. Auto-archive separately requires an
|
||||
HEAD, then the most recently updated terminal request. When the forge identifies
|
||||
the checkout's branch as the origin repository's default branch, only open
|
||||
requests are eligible. A reused feature branch can show its previous request
|
||||
until a new one opens. Auto-archive separately requires an
|
||||
observed open-to-merged transition and a fresh exact match between checkout HEAD
|
||||
and the PR head, along with the existing workspace safety checks.
|
||||
|
||||
|
||||
+11
-3
@@ -49,9 +49,17 @@ Large unbounded timeline responses can exceed relay frame limits, so catch-up us
|
||||
|
||||
Page limits are projected-item targets. A tool call lifecycle is one projected item even if it spans many source sequence numbers, and assistant/reasoning chunks are merged before counting. The response carries `seqStart`, `seqEnd`, `sourceSeqRanges`, and `collapsed` so clients can advance sequence cursors without rendering delta rows.
|
||||
|
||||
When live delivery detects a sequence gap, the app fetches `direction: "after"`. If the daemon
|
||||
responds with `hasNewer: true`, the app immediately fetches the next page from `endCursor`. Gap
|
||||
recovery is complete only when `hasNewer: false`.
|
||||
When live delivery detects a sequence gap, the app fetches `direction: "after"` its end cursor. If
|
||||
the daemon responds with `hasNewer: true`, the app immediately fetches the next page from
|
||||
`endCursor`. Gap recovery is complete only when `hasNewer: false`.
|
||||
|
||||
A chat that was empty when it last caught up has no end cursor to compare a live row against. Such a
|
||||
row starts coverage only if it is the epoch's first row, seq 1. A later row means the chat missed the
|
||||
rows before it, such as a prompt sent while the app was offline, so the app drops it and recovers
|
||||
after seq 0. Coverage started at that later row would make the resume page look already applied, and
|
||||
the chat and its replica cache would keep only the end of the reply. A recovery that waits behind a
|
||||
running catch-up starts after whatever that catch-up applied, because the app applies a forward page
|
||||
row by row and an older cursor repeats rows.
|
||||
|
||||
Initialization timeouts guard lack of catch-up progress, not the full multi-page sync. A successful page that queues the next `after` page refreshes the watchdog.
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@ const withAndroidProfileable = require("./plugins/with-android-profileable");
|
||||
const withFdroidAutolinking = require("./plugins/with-fdroid-autolinking");
|
||||
const withPasteInput = require("./plugins/with-paste-input");
|
||||
const withAndroidScroll = require("./modules/paseo-scroll/app.plugin");
|
||||
const withAndroidDisplayMetrics = require("./modules/paseo-display-metrics/app.plugin");
|
||||
const { getNativeReleaseVersion } = require("./native-release-version");
|
||||
const appVariant = process.env.APP_VARIANT ?? "production";
|
||||
const isFdroidBuild = process.env.PASEO_FDROID_BUILD === "1";
|
||||
@@ -146,6 +147,7 @@ export default {
|
||||
"expo-router",
|
||||
withPasteInput,
|
||||
withAndroidScroll,
|
||||
withAndroidDisplayMetrics,
|
||||
[withAndroidAsyncStorageSize, 64],
|
||||
...buildProfile.cameraPlugins,
|
||||
withAndroidOptionalCamera,
|
||||
|
||||
@@ -527,7 +527,17 @@ async function expectHiddenStreamingSubmissionOrderAfterWorkspaceEviction(
|
||||
expect(gate.getClientRequestCount("agent.timeline.set_subscription.request")).toBe(
|
||||
subscriptionRequests,
|
||||
);
|
||||
const requestsBeforeRelease = rememberTimelineRequestCounts(gate, target.agentId);
|
||||
gate.releaseHeldAgentStreamEvent("turn_started");
|
||||
// The chat never saw the hidden prompt's live row, so the reply's first row is a gap.
|
||||
// The chat recovers the missing rows once, while its workspace is still evicted.
|
||||
await expect
|
||||
.poll(() => gate.getTimelineRequestCount("after", target.agentId))
|
||||
.toBe(requestsBeforeRelease.after + 1);
|
||||
await gate.waitForServerMessage(
|
||||
"fetch_agent_timeline_response",
|
||||
gate.getClientRequestCount("fetch_agent_timeline_request"),
|
||||
);
|
||||
const requestsBeforeReturn = rememberTimelineRequestCounts(gate, target.agentId);
|
||||
await waitForWorkspaceInSidebar(page, {
|
||||
serverId: getServerId(),
|
||||
|
||||
@@ -14,6 +14,8 @@ import {
|
||||
answerFreshnessCheck,
|
||||
commitTimelineTurnsWhileDisconnected,
|
||||
disconnectViewedTimeline,
|
||||
expectEmptyChatSynced,
|
||||
expectPromptAndWholeReply,
|
||||
expectResumeAnsweredWithoutFetch,
|
||||
expectResumeOverflowFallsBackToOneTail,
|
||||
hideTabAndReturn,
|
||||
@@ -22,7 +24,11 @@ import {
|
||||
restoreUnchangedViewedTimeline,
|
||||
restoreViewedTimelineHoldingCatchUp,
|
||||
restoreViewedTimelineWithHeldResponse,
|
||||
restoreViewedTimelineWithLiveRowsFirst,
|
||||
reopenWithFreshnessCheckUnanswered,
|
||||
seedStreamingReplyAgent,
|
||||
sendPromptWhileDisconnected,
|
||||
stopStreamingReply,
|
||||
waitForResumeAnswer,
|
||||
reopenAppWatchingForUpdatingToast,
|
||||
watchForUpdatingToast,
|
||||
@@ -147,4 +153,27 @@ test.describe("Agent timeline resume", () => {
|
||||
await agent.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("an empty chat that reconnects mid-reply keeps the prompt and the whole reply", async ({
|
||||
page,
|
||||
}) => {
|
||||
test.setTimeout(120_000);
|
||||
const gate = await installDaemonWebSocketGate(page);
|
||||
const agent = await seedStreamingReplyAgent();
|
||||
try {
|
||||
await openAgentTimeline(page, agent);
|
||||
await expectEmptyChatSynced(page, gate);
|
||||
await disconnectViewedTimeline(page, gate);
|
||||
await sendPromptWhileDisconnected(agent);
|
||||
await restoreViewedTimelineWithLiveRowsFirst(gate);
|
||||
const reply = await stopStreamingReply(agent);
|
||||
await expectPromptAndWholeReply(page, agent, reply);
|
||||
|
||||
await page.reload();
|
||||
await expectPromptAndWholeReply(page, agent, reply);
|
||||
} finally {
|
||||
gate.restore();
|
||||
await agent.cleanup();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -362,6 +362,16 @@ test.describe("Plugin sidebar items", () => {
|
||||
});
|
||||
});
|
||||
|
||||
test("a plugin screen reads workspaces through the state hooks", async ({ page }) => {
|
||||
await page.setViewportSize(WIDE);
|
||||
await gotoWorkspace(page, workspaceId);
|
||||
await expect(headerRow(page, SHOWCASE_PLUGIN_ID, "deploys")).toBeVisible({ timeout: 30_000 });
|
||||
await runCommand(page, "Open plugin workspaces");
|
||||
await expect(screenTitle(page)).toHaveText("Workspaces");
|
||||
await expect(page.getByText(`Workspace ${workspaceId}`, { exact: true })).toBeVisible();
|
||||
await expect(page.getByText("Plugin failed", { exact: false })).toHaveCount(0);
|
||||
});
|
||||
|
||||
test("a header row's shortcut hint presses the row", async ({ page }) => {
|
||||
await page.setViewportSize(WIDE);
|
||||
await gotoWorkspace(page, workspaceId);
|
||||
|
||||
@@ -361,6 +361,10 @@ test.describe("Worktree restore", () => {
|
||||
cwd: backingWorktree.workspaceDirectory,
|
||||
stdio: "pipe",
|
||||
});
|
||||
const originalHead = execFileSync("git", ["rev-parse", "HEAD"], {
|
||||
cwd: backingWorktree.workspaceDirectory,
|
||||
encoding: "utf8",
|
||||
}).trim();
|
||||
const created = await worktreeClient.createWorkspace({
|
||||
source: { kind: "directory", path: backingWorktree.workspaceDirectory },
|
||||
title: "Sample workspace",
|
||||
@@ -389,10 +393,7 @@ test.describe("Worktree restore", () => {
|
||||
await page.getByTestId(`agent-row-${getServerId()}-${agent.id}`).click();
|
||||
await expect(page.getByText("Workspace archived", { exact: true })).toBeVisible();
|
||||
await expect(
|
||||
page.getByText(
|
||||
"Restore Sample workspace to return to its agents. A new branch will start from the saved base or the repository default.",
|
||||
{ exact: true },
|
||||
),
|
||||
page.getByText("Restore Sample workspace to return to its agents.", { exact: true }),
|
||||
).toBeVisible();
|
||||
await captureBranchlessRestoreStep(page, "01-restore-workspace.png");
|
||||
|
||||
@@ -409,17 +410,13 @@ test.describe("Worktree restore", () => {
|
||||
cwd: backingWorktree.workspaceDirectory,
|
||||
encoding: "utf8",
|
||||
}).trim();
|
||||
const defaultHead = execFileSync("git", ["rev-parse", "main"], {
|
||||
cwd: tempRepo.path,
|
||||
encoding: "utf8",
|
||||
}).trim();
|
||||
expect(restoredHead).toBe(defaultHead);
|
||||
expect(restoredHead).toBe(originalHead);
|
||||
expect(
|
||||
execFileSync("git", ["branch", "--show-current"], {
|
||||
cwd: backingWorktree.workspaceDirectory,
|
||||
encoding: "utf8",
|
||||
}).trim(),
|
||||
).toMatch(/^restored\//);
|
||||
).toBe("");
|
||||
});
|
||||
|
||||
test("restore failure stays visible and permits a successful retry", async ({ page }) => {
|
||||
|
||||
@@ -97,18 +97,15 @@ export class ImportSessionFlow {
|
||||
await target.scrollIntoViewIfNeeded();
|
||||
await expect(target).toBeInViewport();
|
||||
}
|
||||
/**
|
||||
* Scrolls the virtualized list, the only one that leaves rows unmounted. A row handle is no way
|
||||
* in: the list unmounts rows as it scrolls, and a detached row has no scroller above it.
|
||||
*/
|
||||
private async scrollList(forward: boolean) {
|
||||
await this.page
|
||||
.locator('[data-testid^="import-session-session-"]')
|
||||
.first()
|
||||
.evaluate((row, advance) => {
|
||||
let element = row.parentElement;
|
||||
while (element && !["auto", "scroll"].includes(getComputedStyle(element).overflowY))
|
||||
element = element.parentElement;
|
||||
if (!element) throw new Error("Import list has no scroll owner");
|
||||
element.scrollTop = advance ? element.scrollTop + element.clientHeight * 0.8 : 0;
|
||||
element.dispatchEvent(new Event("scroll"));
|
||||
}, forward);
|
||||
await this.page.getByTestId("import-session-list").evaluate((list, advance) => {
|
||||
list.scrollTop = advance ? list.scrollTop + list.clientHeight * 0.8 : 0;
|
||||
list.dispatchEvent(new Event("scroll"));
|
||||
}, forward);
|
||||
}
|
||||
async search(query: string) {
|
||||
await this.page.getByTestId("import-session-search").fill(query);
|
||||
@@ -120,11 +117,18 @@ export class ImportSessionFlow {
|
||||
await this.page.getByTestId("import-session-search").fill("");
|
||||
await expect(this.page.getByTestId("import-session-load-more")).toBeVisible();
|
||||
}
|
||||
/** Load more keeps the reader down the list instead of sending them back to the top. */
|
||||
async loadMore() {
|
||||
await this.page.getByTestId("import-session-load-more").click();
|
||||
const loadMore = this.page.getByTestId("import-session-load-more");
|
||||
const topRow = this.page.getByTestId((await this.rowIds())[0]!);
|
||||
await expect(topRow).toBeInViewport();
|
||||
await loadMore.click();
|
||||
// The next page is the last and short, so the button leaves once it lands.
|
||||
await expect(loadMore).toHaveCount(0);
|
||||
await expect(this.page.getByText("Loading sessions...", { exact: true })).toHaveCount(0);
|
||||
await expect(topRow).not.toBeInViewport();
|
||||
await this.revealSession("fixture-root-20");
|
||||
await expect(this.page.getByText("Root session 20", { exact: true })).toBeInViewport();
|
||||
await expect(this.page.getByTestId("import-session-load-more")).toHaveCount(0);
|
||||
}
|
||||
async retryProvider(provider: string, label: string) {
|
||||
await this.expectProviderError(label);
|
||||
|
||||
@@ -198,6 +198,14 @@ async function expectDetails(page: Page) {
|
||||
await expect(page.getByText("All systems operational", { exact: true })).toBeInViewport();
|
||||
}
|
||||
|
||||
// The details render before the daemon answers their event subscription, and reopened
|
||||
// details show the cached summary at once, so wait for the subscription id to arrive.
|
||||
async function readContentObservation(page: Page): Promise<string> {
|
||||
const observation = page.getByLabel("Content observation", { exact: true });
|
||||
await expect(observation).not.toHaveText("");
|
||||
return (await observation.textContent())!;
|
||||
}
|
||||
|
||||
function workspaceMenuRow(page: Page, title: string): Locator {
|
||||
return compactWorkspaceMenu(page).getByRole("menuitem", { name: title, exact: true });
|
||||
}
|
||||
@@ -354,14 +362,12 @@ export async function withButtonShowcase(
|
||||
test.step("closing and crashing content release its owner while sibling buttons and app remain live", async () => {
|
||||
await press(page, "Header status");
|
||||
await expectDetails(page);
|
||||
const observation = page.getByLabel("Content observation", { exact: true });
|
||||
await expect(observation).not.toHaveText("");
|
||||
const first = (await observation.textContent())!;
|
||||
const first = await readContentObservation(page);
|
||||
await press(page, "Close deployment details");
|
||||
await expect.poll(() => released.has(first)).toBe(true);
|
||||
await press(page, "Composer status");
|
||||
await expectDetails(page);
|
||||
const second = (await observation.textContent())!;
|
||||
const second = await readContentObservation(page);
|
||||
expect(second).not.toBe(first);
|
||||
await workspace.client.renameProject(workspace.projectId, "Observer control");
|
||||
await expect(page.getByText("Observed updates: 1", { exact: true })).toBeVisible();
|
||||
@@ -373,7 +379,7 @@ export async function withButtonShowcase(
|
||||
await page.keyboard.press("Escape");
|
||||
await press(page, "Header status");
|
||||
await expectDetails(page);
|
||||
const recovered = (await observation.textContent())!;
|
||||
const recovered = await readContentObservation(page);
|
||||
expect([first, second]).not.toContain(recovered);
|
||||
await showcase.setTitle("Healthy app after button failure");
|
||||
await expect(page.getByTestId("workspace-header-title")).toHaveText(
|
||||
@@ -687,9 +693,7 @@ export async function withButtonShowcase(
|
||||
page,
|
||||
page.getByRole("button", { name: "Close deployment details", exact: true }),
|
||||
);
|
||||
const observation = page.getByLabel("Content observation", { exact: true });
|
||||
await expect(observation).not.toHaveText("");
|
||||
const owner = (await observation.textContent())!;
|
||||
const owner = await readContentObservation(page);
|
||||
await showcase.disable();
|
||||
await expect.poll(() => released.has(owner)).toBe(true);
|
||||
await expect(
|
||||
|
||||
@@ -15,8 +15,18 @@ export const COMPACT = { width: 390, height: 844 };
|
||||
/** A plugin written against the current API: a screen, header and footer items, a command. */
|
||||
const SHOWCASE_SOURCE = `import React from "react";
|
||||
import { Pressable, Text, View } from "react-native";
|
||||
import { useWorkspaces } from "@getpaseo/plugin/client";
|
||||
import { SidebarRow } from "@getpaseo/plugin/client/ui";
|
||||
|
||||
function WorkspacesScreen({ theme }) {
|
||||
const workspaces = useWorkspaces();
|
||||
return (
|
||||
<View style={{ flex: 1, padding: 24, gap: 8 }}>
|
||||
{workspaces.map((ref) => <Text key={ref.id} style={{ color: theme.colors.foreground }}>{"Workspace " + ref.id}</Text>)}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function DeploysScreen({ theme }) {
|
||||
return <View style={{ flex: 1, padding: 24 }}><Text style={{ color: theme.colors.foreground }}>Deploys screen body</Text></View>;
|
||||
}
|
||||
@@ -63,11 +73,13 @@ function Broken() {
|
||||
|
||||
export default function contribute(client) {
|
||||
client.addScreen({ id: "deploys", title: "Deploys", Component: DeploysScreen });
|
||||
client.addScreen({ id: "workspaces", title: "Workspaces", Component: WorkspacesScreen });
|
||||
client.addSidebarHeaderItem({ id: "deploys", title: "Deploys", Component: DeploysItem });
|
||||
client.addSidebarHeaderItem({ id: "broken", title: "Broken header", Component: Broken });
|
||||
client.addSidebarFooterItem({ id: "sync", title: "Sync", Component: SyncItem });
|
||||
client.addSidebarFooterItem({ id: "broken", title: "Broken footer", Component: Broken });
|
||||
client.addCommandCenterItem({ id: "open-deploys", title: "Open deploys", icon: "Rocket", context: "global", onSelect: (ctx) => ctx.openScreen({ screenId: "deploys" }) });
|
||||
client.addCommandCenterItem({ id: "open-workspaces", title: "Open plugin workspaces", icon: "List", context: "global", onSelect: (ctx) => ctx.openScreen({ screenId: "workspaces" }) });
|
||||
return () => {};
|
||||
}
|
||||
`;
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { expect, type Page } from "@playwright/test";
|
||||
import type { installDaemonWebSocketGate } from "./daemon-websocket-gate";
|
||||
import { seedMockAgentWorkspace, type MockAgentWorkspace } from "./mock-agent";
|
||||
import { readReplicaCache } from "./replica-cache-storage";
|
||||
import type { LongTimelineAgent } from "./timeline-pagination";
|
||||
import {
|
||||
@@ -241,3 +242,100 @@ export async function restoreUnchangedViewedTimeline(
|
||||
gate.restore();
|
||||
await expectReconnectingToastGone(page);
|
||||
}
|
||||
|
||||
export interface StreamingReplyAgent extends MockAgentWorkspace {
|
||||
prompt: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* A mock agent with no history whose reply streams one word every 100 ms. At 2,000 words the
|
||||
* reply outlasts the test's timeout, so it is still streaming however long the app takes to
|
||||
* reconnect. The test ends the turn with {@link stopStreamingReply}.
|
||||
*/
|
||||
export async function seedStreamingReplyAgent(): Promise<StreamingReplyAgent> {
|
||||
const reply = Array.from({ length: 2_000 }, (_unused, index) => `word${index}`).join(" ");
|
||||
const agent = await seedMockAgentWorkspace({
|
||||
repoPrefix: "reply-reconnect-",
|
||||
title: "Reply through reconnect",
|
||||
featureValues: {
|
||||
mockStreamingAssistantResponse: reply,
|
||||
mockStreamingAssistantIntervalMs: 100,
|
||||
},
|
||||
});
|
||||
return {
|
||||
...agent,
|
||||
prompt: "stream through a reconnect",
|
||||
cleanup: async () => {
|
||||
await agent.client.cancelAgent(agent.agentId).catch(() => undefined);
|
||||
await agent.cleanup();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
interface TimelineReader {
|
||||
fetchAgentTimeline(
|
||||
agentId: string,
|
||||
request: { direction: "tail"; limit: number },
|
||||
): Promise<{ entries: Array<{ item: { type: string; text?: string } }> }>;
|
||||
}
|
||||
|
||||
async function readDaemonReply(agent: StreamingReplyAgent): Promise<string> {
|
||||
const timeline = await (agent.client as unknown as TimelineReader).fetchAgentTimeline(
|
||||
agent.agentId,
|
||||
{ direction: "tail", limit: 0 },
|
||||
);
|
||||
return timeline.entries
|
||||
.map(({ item }) => (item.type === "assistant_message" ? (item.text ?? "") : ""))
|
||||
.join("");
|
||||
}
|
||||
|
||||
/** Waits for the empty chat's first catch-up, so the chat is synced with no range. */
|
||||
export async function expectEmptyChatSynced(page: Page, gate: DaemonWebSocketGate): Promise<void> {
|
||||
await gate.waitForServerMessage(TIMELINE_RESPONSE);
|
||||
await expect(page.getByTestId("agent-chat-scroll").filter({ visible: true })).toHaveCount(1, {
|
||||
timeout: 30_000,
|
||||
});
|
||||
}
|
||||
|
||||
/** Another client sends the prompt, and the reply starts, while the chat is away. */
|
||||
export async function sendPromptWhileDisconnected(agent: StreamingReplyAgent): Promise<void> {
|
||||
await agent.client.sendAgentMessage(agent.agentId, agent.prompt);
|
||||
await expect.poll(() => readDaemonReply(agent), { timeout: 30_000 }).toContain("word10");
|
||||
}
|
||||
|
||||
/** Reconnects with live reply chunks reaching the chat before the catch-up page that holds them. */
|
||||
export async function restoreViewedTimelineWithLiveRowsFirst(
|
||||
gate: DaemonWebSocketGate,
|
||||
): Promise<void> {
|
||||
gate.holdNextClientRequest(TIMELINE_REQUEST);
|
||||
const chunksBeforeReconnect = gate.getAgentStreamItemCount("assistant_message");
|
||||
gate.restore();
|
||||
await gate.waitForHeldClientRequest();
|
||||
await gate.waitForAgentStreamItem("assistant_message", chunksBeforeReconnect + 5);
|
||||
gate.releaseHeldClientRequest();
|
||||
}
|
||||
|
||||
/** Stops the turn and returns the reply as the daemon recorded it. */
|
||||
export async function stopStreamingReply(agent: StreamingReplyAgent): Promise<string> {
|
||||
await agent.client.cancelAgent(agent.agentId);
|
||||
await agent.client.waitForFinish(agent.agentId, 30_000);
|
||||
const reply = (await readDaemonReply(agent)).trim();
|
||||
expect(reply).toMatch(/^word0 word1 word2 .* word10 /);
|
||||
return reply;
|
||||
}
|
||||
|
||||
export async function expectPromptAndWholeReply(
|
||||
page: Page,
|
||||
agent: StreamingReplyAgent,
|
||||
reply: string,
|
||||
): Promise<void> {
|
||||
const chat = page.getByTestId("agent-chat-scroll").filter({ visible: true }).first();
|
||||
await expect(chat.getByText(agent.prompt, { exact: true })).toBeVisible({ timeout: 30_000 });
|
||||
await expect
|
||||
.poll(
|
||||
async () =>
|
||||
(await chat.getByTestId("assistant-message").allInnerTexts()).map((text) => text.trim()),
|
||||
{ timeout: 30_000 },
|
||||
)
|
||||
.toEqual([reply]);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
/android/.cxx/
|
||||
/android/build/
|
||||
@@ -0,0 +1,23 @@
|
||||
apply plugin: 'com.android.library'
|
||||
|
||||
group = 'sh.paseo.displaymetrics'
|
||||
version = '0.1.0'
|
||||
|
||||
def expoModulesCorePlugin = new File(project(":expo-modules-core").projectDir.absolutePath, "ExpoModulesCorePlugin.gradle")
|
||||
apply from: expoModulesCorePlugin
|
||||
applyKotlinExpoModulesCorePlugin()
|
||||
useCoreDependencies()
|
||||
useDefaultAndroidSdkVersions()
|
||||
|
||||
android {
|
||||
namespace "sh.paseo.displaymetrics"
|
||||
defaultConfig {
|
||||
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
|
||||
}
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation "com.facebook.react:react-android"
|
||||
androidTestImplementation 'androidx.test:runner:1.6.2'
|
||||
androidTestImplementation 'androidx.test.ext:junit:1.2.1'
|
||||
}
|
||||
+86
@@ -0,0 +1,86 @@
|
||||
package sh.paseo.displaymetrics
|
||||
|
||||
import android.util.DisplayMetrics
|
||||
import android.util.TypedValue
|
||||
import androidx.test.ext.junit.runners.AndroidJUnit4
|
||||
import androidx.test.platform.app.InstrumentationRegistry
|
||||
import com.facebook.react.uimanager.DisplayMetricsHolder
|
||||
import com.facebook.react.uimanager.PixelUtil
|
||||
import org.junit.After
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertSame
|
||||
import org.junit.Assert.assertThrows
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
|
||||
@RunWith(AndroidJUnit4::class)
|
||||
class PaseoDisplayMetricsTest {
|
||||
private lateinit var display: DisplayMetrics
|
||||
|
||||
@Before
|
||||
fun readDisplayLikeReactNative() {
|
||||
DisplayMetricsHolder.initDisplayMetrics(InstrumentationRegistry.getInstrumentation().targetContext)
|
||||
display = DisplayMetricsHolder.getScreenDisplayMetrics()
|
||||
}
|
||||
|
||||
@After
|
||||
fun forgetDisplay() {
|
||||
DisplayMetricsHolder.setScreenDisplayMetrics(null)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun reservesRoomForTextAtTheWindowDensity() {
|
||||
// A DeX window at two thirds of the phone's density (240 dpi on a 360 dpi phone). React Native
|
||||
// reads the font scale from the window but the density from the phone's display.
|
||||
val window = windowAt(display.densityDpi * 2 / 3)
|
||||
DisplayMetricsHolder.setScreenDisplayMetrics(
|
||||
DisplayMetrics().apply {
|
||||
setTo(display)
|
||||
scaledDensity = window.scaledDensity
|
||||
},
|
||||
)
|
||||
assertTrue(reservedTextPx(window) < drawnTextPx())
|
||||
|
||||
PaseoDisplayMetrics.syncWithWindow(window)
|
||||
|
||||
assertEquals(drawnTextPx(), reservedTextPx(window), 0.01f)
|
||||
assertEquals(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 16f, window), drawnTextPx(), 0.01f)
|
||||
val synced = DisplayMetricsHolder.getScreenDisplayMetrics()
|
||||
assertEquals(window.densityDpi, synced.densityDpi)
|
||||
assertEquals(display.widthPixels, synced.widthPixels)
|
||||
assertEquals(display.heightPixels, synced.heightPixels)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun leavesTheBuiltInDisplayAlone() {
|
||||
PaseoDisplayMetrics.syncWithWindow(windowAt(display.densityDpi))
|
||||
|
||||
assertSame(display, DisplayMetricsHolder.getScreenDisplayMetrics())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun waitsForReactNativeToReadTheDisplay() {
|
||||
DisplayMetricsHolder.setScreenDisplayMetrics(null)
|
||||
|
||||
PaseoDisplayMetrics.syncWithWindow(windowAt(display.densityDpi / 2))
|
||||
|
||||
assertThrows(IllegalStateException::class.java) { DisplayMetricsHolder.getScreenDisplayMetrics() }
|
||||
}
|
||||
|
||||
private fun windowAt(densityDpi: Int): DisplayMetrics =
|
||||
DisplayMetrics().apply {
|
||||
setTo(display)
|
||||
this.densityDpi = densityDpi
|
||||
density = densityDpi.toFloat() / DisplayMetrics.DENSITY_DEFAULT
|
||||
scaledDensity = density * display.scaledDensity / display.density
|
||||
}
|
||||
|
||||
/** A 16sp font as React Native draws it, in pixels. */
|
||||
private fun drawnTextPx(): Float = PixelUtil.toPixelFromSP(16f)
|
||||
|
||||
/** The box React Native lays out for that font, once the window renders it in pixels. */
|
||||
private fun reservedTextPx(window: DisplayMetrics): Float =
|
||||
PixelUtil.toDIPFromPixel(drawnTextPx()) * window.density
|
||||
}
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
package sh.paseo.displaymetrics
|
||||
|
||||
import android.app.Activity
|
||||
import android.util.DisplayMetrics
|
||||
import com.facebook.react.uimanager.DisplayMetricsHolder
|
||||
|
||||
/**
|
||||
* React Native 0.86 converts between px and dp, and so sizes text, with the density of the
|
||||
* device's built-in display, because `DisplayMetricsHolder` reads `Display.getRealMetrics()`.
|
||||
* Fabric lays out at the window's density. On a display with another density, such as a Samsung
|
||||
* DeX monitor, text boxes come out too small and clip their text.
|
||||
*
|
||||
* Backports react/react-native#59087 (`useWindowDensityForDisplayMetricsAndroid`): keep the
|
||||
* window's density and take only the size from the display. Remove once the app runs React Native
|
||||
* 0.89 or later with that flag on.
|
||||
*/
|
||||
object PaseoDisplayMetrics {
|
||||
/** Call right after React Native reads the display, which it does again on each configuration change. */
|
||||
@JvmStatic
|
||||
fun syncWithWindow(activity: Activity) {
|
||||
syncWithWindow(activity.resources.displayMetrics)
|
||||
}
|
||||
|
||||
@JvmStatic
|
||||
fun syncWithWindow(window: DisplayMetrics) {
|
||||
val screen =
|
||||
try {
|
||||
DisplayMetricsHolder.getScreenDisplayMetrics()
|
||||
} catch (_: IllegalStateException) {
|
||||
// React Native hasn't read the display yet, so there is nothing to correct.
|
||||
return
|
||||
}
|
||||
if (screen.densityDpi == window.densityDpi) return
|
||||
|
||||
DisplayMetricsHolder.setScreenDisplayMetrics(
|
||||
DisplayMetrics().apply {
|
||||
setTo(screen)
|
||||
density = window.density
|
||||
densityDpi = window.densityDpi
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
const { withMainActivity } = require("expo/config-plugins");
|
||||
|
||||
const ACTIVITY_CLASS = "class MainActivity : ReactActivity() {";
|
||||
const SYNC = "sh.paseo.displaymetrics.PaseoDisplayMetrics.syncWithWindow(this)";
|
||||
// React Native re-reads the built-in display's density when it creates the root view and on every
|
||||
// configuration change, so the window's density has to be restored right after each `super` call.
|
||||
const OVERRIDES = `
|
||||
override fun onContentChanged() {
|
||||
super.onContentChanged()
|
||||
${SYNC}
|
||||
}
|
||||
|
||||
override fun onConfigurationChanged(newConfig: android.content.res.Configuration) {
|
||||
super.onConfigurationChanged(newConfig)
|
||||
${SYNC}
|
||||
}
|
||||
`;
|
||||
|
||||
function configureDisplayMetricsActivity(contents) {
|
||||
if (contents.includes(SYNC)) return contents;
|
||||
if (
|
||||
!contents.includes(ACTIVITY_CLASS) ||
|
||||
/override fun on(ContentChanged|ConfigurationChanged)\(/.test(contents)
|
||||
) {
|
||||
throw new Error("Could not keep React Native text at the window's density in MainActivity");
|
||||
}
|
||||
return contents.replace(ACTIVITY_CLASS, `${ACTIVITY_CLASS}${OVERRIDES}`);
|
||||
}
|
||||
|
||||
module.exports = (config) =>
|
||||
withMainActivity(config, (mod) => {
|
||||
mod.modResults.contents = configureDisplayMetricsActivity(mod.modResults.contents);
|
||||
return mod;
|
||||
});
|
||||
module.exports.configureDisplayMetricsActivity = configureDisplayMetricsActivity;
|
||||
@@ -0,0 +1,29 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
const { configureDisplayMetricsActivity } = require("./app.plugin");
|
||||
|
||||
const SYNC = "sh.paseo.displaymetrics.PaseoDisplayMetrics.syncWithWindow(this)";
|
||||
|
||||
describe("Android display metrics", () => {
|
||||
it("restores the window's density after React Native reads the display", () => {
|
||||
const source = "class MainActivity : ReactActivity() {\n}";
|
||||
const result = configureDisplayMetricsActivity(source);
|
||||
expect(result).toContain(`super.onContentChanged()\n ${SYNC}`);
|
||||
expect(result).toContain(`super.onConfigurationChanged(newConfig)\n ${SYNC}`);
|
||||
expect(configureDisplayMetricsActivity(result)).toBe(result);
|
||||
});
|
||||
|
||||
it("fails prebuild when the template no longer has a place for the overrides", () => {
|
||||
expect(() => configureDisplayMetricsActivity("changed template")).toThrow(
|
||||
"Could not keep React Native text at the window's density",
|
||||
);
|
||||
});
|
||||
|
||||
it("fails prebuild rather than replace another plugin's configuration handler", () => {
|
||||
const source =
|
||||
"class MainActivity : ReactActivity() {\n override fun onConfigurationChanged(newConfig: Configuration) {}\n}";
|
||||
expect(() => configureDisplayMetricsActivity(source)).toThrow(
|
||||
"Could not keep React Native text at the window's density",
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"platforms": ["android"],
|
||||
"android": {
|
||||
"modules": []
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"name": "paseo-display-metrics",
|
||||
"version": "0.1.0",
|
||||
"private": true
|
||||
}
|
||||
@@ -17,6 +17,11 @@ export function nextPageLimit(limit: number): number {
|
||||
return PAGE_LIMITS.find((candidate) => candidate > limit) ?? limit;
|
||||
}
|
||||
|
||||
/** The page Load more grew this limit from, or null for the first page. */
|
||||
export function previousPageLimit(limit: number): number | null {
|
||||
return PAGE_LIMITS.findLast((candidate) => candidate < limit) ?? null;
|
||||
}
|
||||
|
||||
export function requiresImportSessionsHostUpgrade(input: {
|
||||
supportsSnapshot: boolean;
|
||||
workspaceId?: string | null;
|
||||
|
||||
@@ -1172,6 +1172,44 @@ describe("ImportSessionSheet", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps the loaded list in place while Load more fetches the next page", async () => {
|
||||
let releaseNextPage: () => void = () => undefined;
|
||||
const nextPage = new Promise<void>((resolve) => {
|
||||
releaseNextPage = resolve;
|
||||
});
|
||||
const fetchRecentProviderSessions = vi.fn(async (options: { limit?: number } | undefined) => {
|
||||
if (options?.limit !== 15) await nextPage;
|
||||
return {
|
||||
requestId: "recent-provider-sessions",
|
||||
entries: createPageOfEntries(options?.limit === 15 ? 15 : 20),
|
||||
};
|
||||
});
|
||||
|
||||
renderSheet(createRecentSessionsClient(fetchRecentProviderSessions, vi.fn()), {
|
||||
cwd: null,
|
||||
snapshot: { supportsSnapshot: true, entries: [createSnapshotEntry("claude")] },
|
||||
});
|
||||
|
||||
fireEvent.click(await screen.findByTestId("import-session-load-more"));
|
||||
// The list the user scrolled to Load more is the one they keep: replacing it would drop
|
||||
// them back at the top, behind a loading state, until the larger page lands.
|
||||
const list = screen.getByTestId("import-session-list");
|
||||
await waitFor(() => {
|
||||
expect(fetchRecentProviderSessions).toHaveBeenCalledWith({
|
||||
providers: ["claude"],
|
||||
limit: 45,
|
||||
});
|
||||
});
|
||||
expect(screen.getByTestId("import-session-list")).toBe(list);
|
||||
expect(screen.queryByText("Loading sessions...")).toBeNull();
|
||||
|
||||
releaseNextPage();
|
||||
await waitFor(() => {
|
||||
expect(screen.queryByTestId("import-session-load-more")).toBeNull();
|
||||
});
|
||||
expect(screen.getByTestId("import-session-list")).toBe(list);
|
||||
});
|
||||
|
||||
it("stops the refresh spinner and retries only the failed provider", async () => {
|
||||
const fetchRecentProviderSessions = vi.fn(
|
||||
async (options: { providers?: string[] } | undefined) => {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import React, { type ReactNode, useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { Pressable, type PressableStateCallbackType, Text, View } from "react-native";
|
||||
import { keepPreviousData, useMutation, useQueries, useQueryClient } from "@tanstack/react-query";
|
||||
import { useMutation, useQueries, useQueryClient, type QueryClient } from "@tanstack/react-query";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import type {
|
||||
DaemonClient,
|
||||
@@ -40,6 +40,7 @@ import {
|
||||
resolveDirectoryLabel,
|
||||
nextPageLimit,
|
||||
PER_PROVIDER_LIMIT,
|
||||
previousPageLimit,
|
||||
type ProviderErrorRow,
|
||||
resolveImportTarget,
|
||||
resolveProvidersToFetch,
|
||||
@@ -100,11 +101,12 @@ interface SessionsQueryConfig {
|
||||
// Query's default retry would keep the header spinner turning and pile up
|
||||
// in-flight daemon requests behind a dead provider (#2512).
|
||||
retry: false;
|
||||
placeholderData: typeof keepPreviousData;
|
||||
placeholderData: () => RecentSessionsResponse | undefined;
|
||||
queryFn: () => Promise<RecentSessionsResponse>;
|
||||
}
|
||||
|
||||
function buildSessionsQueriesConfig(args: {
|
||||
queryClient: QueryClient;
|
||||
providersToFetch: AgentProvider[] | null;
|
||||
visible: boolean;
|
||||
client: RecentProviderSessionsClient | null;
|
||||
@@ -113,14 +115,24 @@ function buildSessionsQueriesConfig(args: {
|
||||
limit: number;
|
||||
hostDisconnectedMessage?: string;
|
||||
}): SessionsQueryConfig[] {
|
||||
const { providersToFetch, visible, client, cwd, query, limit, hostDisconnectedMessage } = args;
|
||||
const { queryClient, providersToFetch, visible, client, cwd, query, limit } = args;
|
||||
const { hostDisconnectedMessage } = args;
|
||||
if (providersToFetch === null) return [];
|
||||
const enabled = visible && Boolean(client);
|
||||
const previousLimit = previousPageLimit(limit);
|
||||
return providersToFetch.map((provider) => ({
|
||||
queryKey: buildSessionsQueryKey({ cwd, query, limit, provider }),
|
||||
enabled,
|
||||
retry: false as const,
|
||||
placeholderData: keepPreviousData,
|
||||
// While Load more fetches the next page, keep showing the page it grew from. React Query's
|
||||
// keepPreviousData cannot do this here: useQueries gives a changed key a new observer, which
|
||||
// has no previous data, so the rows would vanish and the list would remount at the top.
|
||||
placeholderData: () =>
|
||||
previousLimit === null
|
||||
? undefined
|
||||
: queryClient.getQueryData<RecentSessionsResponse>(
|
||||
buildSessionsQueryKey({ cwd, query, limit: previousLimit, provider }),
|
||||
),
|
||||
queryFn: async () => {
|
||||
if (!client) {
|
||||
throw new Error(hostDisconnectedMessage ?? i18n.t("workspace.terminal.hostDisconnected"));
|
||||
@@ -522,6 +534,7 @@ export function ImportSessionSheet({
|
||||
const queriesConfig = useMemo(
|
||||
() =>
|
||||
buildSessionsQueriesConfig({
|
||||
queryClient,
|
||||
providersToFetch,
|
||||
visible,
|
||||
client,
|
||||
@@ -530,7 +543,7 @@ export function ImportSessionSheet({
|
||||
limit: pageLimit,
|
||||
hostDisconnectedMessage: t("workspace.terminal.hostDisconnected"),
|
||||
}),
|
||||
[providersToFetch, visible, client, scopeCwd, query, pageLimit, t],
|
||||
[queryClient, providersToFetch, visible, client, scopeCwd, query, pageLimit, t],
|
||||
);
|
||||
|
||||
const queries = useQueries({ queries: queriesConfig });
|
||||
|
||||
@@ -1,7 +1,4 @@
|
||||
import { PluginClientStateProvider } from "@getpaseo/plugin/client/host";
|
||||
import type { PluginFilePanelProps } from "@getpaseo/plugin/client";
|
||||
import { useMemo } from "react";
|
||||
import { createPluginClientStateSource } from "@/plugins/client-state/source";
|
||||
import { PluginInstallationProvider } from "@/plugins/installation-provider";
|
||||
import { SurfaceErrorBoundary } from "@/plugins/surface-error-boundary";
|
||||
import type { PluginFilePanel } from "./panels";
|
||||
@@ -11,17 +8,11 @@ export function PluginFilePanelHost({
|
||||
...props
|
||||
}: PluginFilePanelProps & { panel: PluginFilePanel }) {
|
||||
const { plugin, contribution } = panel;
|
||||
const stateSource = useMemo(
|
||||
() => createPluginClientStateSource(plugin.serverId),
|
||||
[plugin.serverId],
|
||||
);
|
||||
const Component = contribution.Component;
|
||||
return (
|
||||
<SurfaceErrorBoundary installation={plugin} Surface={Component} key={panel.id}>
|
||||
<PluginInstallationProvider plugin={plugin}>
|
||||
<PluginClientStateProvider source={stateSource}>
|
||||
<Component {...props} />
|
||||
</PluginClientStateProvider>
|
||||
<Component {...props} />
|
||||
</PluginInstallationProvider>
|
||||
</SurfaceErrorBoundary>
|
||||
);
|
||||
|
||||
@@ -6,6 +6,7 @@ import { createMacDockBadgeCountSelector } from "@/utils/desktop-badge-state";
|
||||
import { createFaviconStatusSelector, type FaviconStatus } from "@/utils/favicon-status";
|
||||
import { isNative } from "@/constants/platform";
|
||||
import { useSessionStore } from "@/stores/session-store";
|
||||
import { useSidebarViewStore } from "@/stores/sidebar-view-store";
|
||||
import { useHosts } from "@/runtime/host-runtime";
|
||||
|
||||
type ColorScheme = "dark" | "light";
|
||||
@@ -85,8 +86,16 @@ export function useFaviconStatus() {
|
||||
// The favicon reads the whole fleet, so it has to keep every host's directory loading even
|
||||
// though it no longer subscribes to the agent maps.
|
||||
useAllDirectoryDemand({ serverIds, enabled: !isNative });
|
||||
const selectFaviconStatus = useMemo(createFaviconStatusSelector, []);
|
||||
const selectMacDockBadgeCount = useMemo(createMacDockBadgeCountSelector, []);
|
||||
// Background workspaces count exactly when the sidebar shows them.
|
||||
const showBackground = useSidebarViewStore((state) => state.showBackground);
|
||||
const selectFaviconStatus = useMemo(
|
||||
() => createFaviconStatusSelector({ showBackground }),
|
||||
[showBackground],
|
||||
);
|
||||
const selectMacDockBadgeCount = useMemo(
|
||||
() => createMacDockBadgeCountSelector({ showBackground }),
|
||||
[showBackground],
|
||||
);
|
||||
const status = useSessionStore(selectFaviconStatus);
|
||||
const dockBadgeCount = useSessionStore(selectMacDockBadgeCount);
|
||||
const [colorScheme, setColorScheme] = useState<ColorScheme>(getSystemColorScheme);
|
||||
|
||||
@@ -484,8 +484,7 @@ export const ar: TranslationResources = {
|
||||
archivedTitle: "مساحة العمل مؤرشفة",
|
||||
restoreDescription:
|
||||
"استعد {{workspaceName}} للعودة إلى وكلائها. ستستخدم شجرة العمل الفرع {{branch}}.",
|
||||
restoreWithoutBranchDescription:
|
||||
"استعد {{workspaceName}} للعودة إلى وكلائها. سيبدأ فرع جديد من الفرع الأساسي المحفوظ أو الفرع الافتراضي للمستودع.",
|
||||
restoreWithoutBranchDescription: "استعد {{workspaceName}} للعودة إلى وكلائها.",
|
||||
unarchiveDescription: "{{workspaceName}} مؤرشفة. ألغِ أرشفتها لفتحها مجددًا.",
|
||||
restoreAction: "استعادة",
|
||||
unarchiveAction: "إلغاء الأرشفة",
|
||||
|
||||
@@ -483,8 +483,7 @@ export const en = {
|
||||
archivedTitle: "Workspace archived",
|
||||
restoreDescription:
|
||||
"Restore {{workspaceName}} to return to its agents. Its worktree will use branch {{branch}}.",
|
||||
restoreWithoutBranchDescription:
|
||||
"Restore {{workspaceName}} to return to its agents. A new branch will start from the saved base or the repository default.",
|
||||
restoreWithoutBranchDescription: "Restore {{workspaceName}} to return to its agents.",
|
||||
unarchiveDescription: "{{workspaceName}} is archived. Unarchive it to open it again.",
|
||||
restoreAction: "Restore",
|
||||
unarchiveAction: "Unarchive",
|
||||
|
||||
@@ -489,8 +489,7 @@ export const es: TranslationResources = {
|
||||
archivedTitle: "Espacio de trabajo archivado",
|
||||
restoreDescription:
|
||||
"Restaura {{workspaceName}} para volver a sus agentes. Su worktree usará la rama {{branch}}.",
|
||||
restoreWithoutBranchDescription:
|
||||
"Restaura {{workspaceName}} para volver a sus agentes. Se creará una rama nueva desde la base guardada o la rama predeterminada del repositorio.",
|
||||
restoreWithoutBranchDescription: "Restaura {{workspaceName}} para volver a sus agentes.",
|
||||
unarchiveDescription:
|
||||
"{{workspaceName}} está archivado. Desarchívalo para volver a abrirlo.",
|
||||
restoreAction: "Restaurar",
|
||||
|
||||
@@ -489,8 +489,7 @@ export const fr: TranslationResources = {
|
||||
archivedTitle: "Espace de travail archivé",
|
||||
restoreDescription:
|
||||
"Restaurez {{workspaceName}} pour retrouver ses agents. Son worktree utilisera la branche {{branch}}.",
|
||||
restoreWithoutBranchDescription:
|
||||
"Restaurez {{workspaceName}} pour retrouver ses agents. Une nouvelle branche partira de la base enregistrée ou de la branche par défaut du dépôt.",
|
||||
restoreWithoutBranchDescription: "Restaurez {{workspaceName}} pour retrouver ses agents.",
|
||||
unarchiveDescription: "{{workspaceName}} est archivé. Désarchivez-le pour le rouvrir.",
|
||||
restoreAction: "Restaurer",
|
||||
unarchiveAction: "Désarchiver",
|
||||
|
||||
@@ -489,8 +489,7 @@ export const ja: TranslationResources = {
|
||||
archivedTitle: "ワークスペースはアーカイブ済みです",
|
||||
restoreDescription:
|
||||
"{{workspaceName}} を復元してエージェントに戻ります。worktree ではブランチ {{branch}} を使用します。",
|
||||
restoreWithoutBranchDescription:
|
||||
"{{workspaceName}} を復元してエージェントに戻ります。保存されたベース、またはリポジトリのデフォルトブランチから新しいブランチを作成します。",
|
||||
restoreWithoutBranchDescription: "{{workspaceName}} を復元してエージェントに戻ります。",
|
||||
unarchiveDescription:
|
||||
"{{workspaceName}} はアーカイブされています。再度開くにはアーカイブを解除してください。",
|
||||
restoreAction: "復元",
|
||||
|
||||
@@ -485,8 +485,7 @@ export const ko: TranslationResources = {
|
||||
archivedTitle: "워크스페이스가 보관되었습니다",
|
||||
restoreDescription:
|
||||
"{{workspaceName}}를 복원하여 에이전트로 돌아갑니다. 워크트리는 {{branch}} 브랜치를 사용합니다.",
|
||||
restoreWithoutBranchDescription:
|
||||
"{{workspaceName}}를 복원하여 에이전트로 돌아갑니다. 저장된 기반 브랜치 또는 저장소 기본 브랜치에서 새 브랜치를 만듭니다.",
|
||||
restoreWithoutBranchDescription: "{{workspaceName}}를 복원하여 에이전트로 돌아갑니다.",
|
||||
unarchiveDescription: "{{workspaceName}}가 보관되었습니다. 다시 열려면 보관을 취소하세요.",
|
||||
restoreAction: "복원",
|
||||
unarchiveAction: "보관 취소",
|
||||
|
||||
@@ -488,8 +488,7 @@ export const ptBR: TranslationResources = {
|
||||
archivedTitle: "Workspace arquivado",
|
||||
restoreDescription:
|
||||
"Restaure {{workspaceName}} para voltar aos seus agentes. A worktree usará a branch {{branch}}.",
|
||||
restoreWithoutBranchDescription:
|
||||
"Restaure {{workspaceName}} para voltar aos seus agentes. Uma nova branch partirá da base salva ou da branch padrão do repositório.",
|
||||
restoreWithoutBranchDescription: "Restaure {{workspaceName}} para voltar aos seus agentes.",
|
||||
unarchiveDescription:
|
||||
"{{workspaceName}} está arquivado. Desarquive-o para abri-lo novamente.",
|
||||
restoreAction: "Restaurar",
|
||||
|
||||
@@ -489,7 +489,7 @@ export const ru: TranslationResources = {
|
||||
restoreDescription:
|
||||
"Восстановите «{{workspaceName}}», чтобы вернуться к его агентам. Worktree будет использовать ветку {{branch}}.",
|
||||
restoreWithoutBranchDescription:
|
||||
"Восстановите «{{workspaceName}}», чтобы вернуться к его агентам. Новая ветка будет создана от сохранённой базовой или ветки репозитория по умолчанию.",
|
||||
"Восстановите «{{workspaceName}}», чтобы вернуться к его агентам.",
|
||||
unarchiveDescription:
|
||||
"Рабочее пространство «{{workspaceName}}» находится в архиве. Разархивируйте его, чтобы снова открыть.",
|
||||
restoreAction: "Восстановить",
|
||||
|
||||
@@ -484,8 +484,7 @@ export const zhCN: TranslationResources = {
|
||||
archivedTitle: "Workspace 已归档",
|
||||
restoreDescription:
|
||||
"恢复 {{workspaceName}} 以返回其中的代理。worktree 将使用分支 {{branch}}。",
|
||||
restoreWithoutBranchDescription:
|
||||
"恢复 {{workspaceName}} 以返回其中的代理。新分支将从保存的基准分支或仓库默认分支创建。",
|
||||
restoreWithoutBranchDescription: "恢复 {{workspaceName}} 以返回其中的代理。",
|
||||
unarchiveDescription: "{{workspaceName}} 已归档。取消归档以重新打开。",
|
||||
restoreAction: "恢复",
|
||||
unarchiveAction: "取消归档",
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { PluginTranslationRuntime } from "@getpaseo/plugin/client/host";
|
||||
import { usePaseo, useRpc } from "@getpaseo/plugin/client";
|
||||
import { usePaseo, useRpc, useWorkspace, useWorkspaces } from "@getpaseo/plugin/client";
|
||||
import { defineRpc } from "@getpaseo/plugin";
|
||||
import { createPaseoApi, type PaseoApi } from "@getpaseo/client";
|
||||
import { DaemonClient } from "@getpaseo/client/internal/daemon-client";
|
||||
@@ -8,7 +8,11 @@ import React from "react";
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
import { expect, it } from "vitest";
|
||||
import { z } from "zod";
|
||||
import type { PluginWorkspaceSnapshot } from "@getpaseo/plugin";
|
||||
import type { PluginClientStateSource } from "@getpaseo/plugin/client/host";
|
||||
import type { ToastApi } from "@/components/toast-host";
|
||||
import { PluginInstallationProvider } from "./installation-provider";
|
||||
import { PluginEnvironmentProvider } from "./popover";
|
||||
import type { InstalledPlugin } from "./types";
|
||||
|
||||
const status = defineRpc({
|
||||
@@ -89,3 +93,53 @@ it("gives every surface the installation's client and RPCs on its first frame",
|
||||
plugin.lifetime.abort();
|
||||
await plugin.paseo.dispose();
|
||||
});
|
||||
|
||||
it("lets every surface read state through the plugin state hooks", async () => {
|
||||
const plugin = installation([]);
|
||||
function Surface() {
|
||||
return <span>{useWorkspaces().length} workspaces</span>;
|
||||
}
|
||||
|
||||
const markup = renderToStaticMarkup(
|
||||
<PluginInstallationProvider plugin={plugin}>
|
||||
<Surface />
|
||||
</PluginInstallationProvider>,
|
||||
);
|
||||
|
||||
expect(markup).toBe("<span>0 workspaces</span>");
|
||||
plugin.lifetime.abort();
|
||||
await plugin.paseo.dispose();
|
||||
});
|
||||
|
||||
function pluginEnvironment(plugin: InstalledPlugin, state: PluginClientStateSource) {
|
||||
return { installation: plugin, state, toast: {} as ToastApi };
|
||||
}
|
||||
|
||||
it("lets a surface read the state source its host passes", async () => {
|
||||
const plugin = installation([]);
|
||||
// A sidebar view spans every connected host, so its source is not the installation's host.
|
||||
const workspace = { id: "ws-on-another-host" } as PluginWorkspaceSnapshot;
|
||||
const state: PluginClientStateSource = {
|
||||
subscribe: () => () => undefined,
|
||||
getWorkspace: () => workspace,
|
||||
getAgent: () => null,
|
||||
getProject: () => null,
|
||||
getTerminal: () => null,
|
||||
getSnapshot: () => ({ workspaces: [], agents: [], projects: [], terminals: [] }),
|
||||
};
|
||||
function Surface() {
|
||||
return <span>{useWorkspace("ws-on-another-host")?.id}</span>;
|
||||
}
|
||||
|
||||
const environment = pluginEnvironment(plugin, state);
|
||||
|
||||
const markup = renderToStaticMarkup(
|
||||
<PluginEnvironmentProvider environment={environment}>
|
||||
<Surface />
|
||||
</PluginEnvironmentProvider>,
|
||||
);
|
||||
|
||||
expect(markup).toBe("<span>ws-on-another-host</span>");
|
||||
plugin.lifetime.abort();
|
||||
await plugin.paseo.dispose();
|
||||
});
|
||||
|
||||
@@ -2,29 +2,42 @@ import { getPluginClientApi } from "./client-state/api";
|
||||
import { QueryClientProvider } from "@tanstack/react-query";
|
||||
import {
|
||||
PaseoApiProvider,
|
||||
PluginClientStateProvider,
|
||||
PluginComposersProvider,
|
||||
PluginRpcProvider,
|
||||
PluginTranslationProvider,
|
||||
type PluginClientStateSource,
|
||||
} from "@getpaseo/plugin/client/host";
|
||||
import React, { type ReactNode } from "react";
|
||||
import React, { useMemo, type ReactNode } from "react";
|
||||
import { createPluginClientStateSource } from "./client-state/source";
|
||||
import { pluginComposersSource } from "./composer-items/source";
|
||||
import type { InstalledPlugin } from "./types";
|
||||
|
||||
/** Every plugin surface renders under its installation: one query cache, one Paseo client, RPCs. */
|
||||
/**
|
||||
* Every plugin surface renders under its installation: one query cache, one Paseo client, RPCs,
|
||||
* and the state the plugin state hooks read. That state is scoped to the installation's host
|
||||
* unless the surface passes its own, as a sidebar view does to span every connected host.
|
||||
*/
|
||||
export function PluginInstallationProvider({
|
||||
plugin,
|
||||
state: surfaceState,
|
||||
children,
|
||||
}: {
|
||||
plugin: InstalledPlugin;
|
||||
state?: PluginClientStateSource;
|
||||
children: ReactNode;
|
||||
}) {
|
||||
const state = useMemo(
|
||||
() => surfaceState ?? createPluginClientStateSource(plugin.serverId),
|
||||
[plugin.serverId, surfaceState],
|
||||
);
|
||||
return (
|
||||
<QueryClientProvider client={plugin.queryClient}>
|
||||
<PaseoApiProvider paseo={getPluginClientApi(plugin).paseo}>
|
||||
<PluginRpcProvider invoke={plugin.invoke} subscribe={plugin.subscribe}>
|
||||
<PluginTranslationProvider runtime={plugin.i18n}>
|
||||
<PluginComposersProvider source={pluginComposersSource(plugin)}>
|
||||
{children}
|
||||
<PluginClientStateProvider source={state}>{children}</PluginClientStateProvider>
|
||||
</PluginComposersProvider>
|
||||
</PluginTranslationProvider>
|
||||
</PluginRpcProvider>
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { PluginClientStateProvider } from "@getpaseo/plugin/client/host";
|
||||
import type { ReactNode } from "react";
|
||||
import { View } from "react-native";
|
||||
import { StyleSheet } from "react-native-unistyles";
|
||||
@@ -30,8 +29,8 @@ export function PluginEnvironmentProvider({
|
||||
}: PluginEnvironmentProviderProps) {
|
||||
return (
|
||||
<ToastApiProvider api={environment.toast}>
|
||||
<PluginInstallationProvider plugin={environment.installation}>
|
||||
<PluginClientStateProvider source={environment.state}>{children}</PluginClientStateProvider>
|
||||
<PluginInstallationProvider plugin={environment.installation} state={environment.state}>
|
||||
{children}
|
||||
</PluginInstallationProvider>
|
||||
</ToastApiProvider>
|
||||
);
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { PluginClientStateProvider } from "@getpaseo/plugin/client/host";
|
||||
import type { PluginTimelineItemProps } from "@getpaseo/plugin/client";
|
||||
import type { PluginTheme } from "@getpaseo/plugin";
|
||||
import React, { type ComponentType, useMemo } from "react";
|
||||
@@ -8,7 +7,6 @@ import { useIsCompactFormFactor } from "@/constants/layout";
|
||||
import { useHostRuntimeClient, useHosts } from "@/runtime/host-runtime";
|
||||
import type { Theme } from "@/styles/theme";
|
||||
import type { PluginTimelineStreamItem } from "@/types/stream";
|
||||
import { createPluginClientStateSource } from "../client-state/source";
|
||||
import { useInstalledPlugin } from "../registry";
|
||||
import { PluginInstallationProvider } from "../installation-provider";
|
||||
import { SurfaceErrorBoundary } from "../surface-error-boundary";
|
||||
@@ -59,7 +57,6 @@ function PluginTimelineItemBody({
|
||||
const hostLabel = hosts.find((host) => host.serverId === serverId)?.label ?? serverId;
|
||||
const host = useMemo(() => ({ id: serverId, label: hostLabel }), [hostLabel, serverId]);
|
||||
const layout = useMemo(() => ({ compact, platform: resolvePluginPlatform() }), [compact]);
|
||||
const stateSource = useMemo(() => createPluginClientStateSource(serverId), [serverId]);
|
||||
|
||||
if (!plugin || !renderer || !parsed || !client) {
|
||||
return <TimelineItemUnavailable />;
|
||||
@@ -82,9 +79,7 @@ function PluginTimelineItemBody({
|
||||
return (
|
||||
<SurfaceErrorBoundary installation={plugin} resetKey={item.data} Surface={Component}>
|
||||
<PluginInstallationProvider plugin={plugin}>
|
||||
<PluginClientStateProvider source={stateSource}>
|
||||
<Component {...props} />
|
||||
</PluginClientStateProvider>
|
||||
<Component {...props} />
|
||||
</PluginInstallationProvider>
|
||||
</SurfaceErrorBoundary>
|
||||
);
|
||||
|
||||
@@ -5,7 +5,6 @@ import type {
|
||||
PluginTab,
|
||||
} from "@getpaseo/plugin/client";
|
||||
import type { PluginTheme } from "@getpaseo/plugin";
|
||||
import { PluginClientStateProvider } from "@getpaseo/plugin/client/host";
|
||||
import { CircleAlert } from "lucide-react-native";
|
||||
import { useMemo, useState } from "react";
|
||||
import { Text, View } from "react-native";
|
||||
@@ -20,7 +19,6 @@ import { useWorkspaceExists } from "@/stores/session-store-hooks";
|
||||
import type { Theme } from "@/styles/theme";
|
||||
import { normalizeWorkspaceOpaqueId } from "@/utils/workspace-identity";
|
||||
import { usePluginHostNavigation } from "../host-navigation";
|
||||
import { createPluginClientStateSource } from "../client-state/source";
|
||||
import { toPluginTheme } from "../theme";
|
||||
import { pluginIconComponent } from "../icons";
|
||||
import { useInstalledPlugin } from "../registry";
|
||||
@@ -67,7 +65,6 @@ function PluginPanelBody({ theme }: { theme: PluginTheme }) {
|
||||
const hostLabel = hosts.find((host) => host.serverId === serverId)?.label ?? serverId;
|
||||
const host = useMemo(() => ({ id: serverId, label: hostLabel }), [hostLabel, serverId]);
|
||||
const layout = useMemo(() => ({ compact, platform: resolvePluginPlatform() }), [compact]);
|
||||
const stateSource = useMemo(() => createPluginClientStateSource(serverId), [serverId]);
|
||||
const navigation = usePluginHostNavigation(serverId);
|
||||
|
||||
if (!plugin || !contribution || !workspaceExists) {
|
||||
@@ -123,9 +120,7 @@ function PluginPanelBody({ theme }: { theme: PluginTheme }) {
|
||||
Surface={Surface}
|
||||
key={`${serverId}/${target.pluginId}/${target.panelId}/${target.context}`}
|
||||
>
|
||||
<PluginInstallationProvider plugin={plugin}>
|
||||
<PluginClientStateProvider source={stateSource}>{panel}</PluginClientStateProvider>
|
||||
</PluginInstallationProvider>
|
||||
<PluginInstallationProvider plugin={plugin}>{panel}</PluginInstallationProvider>
|
||||
</SurfaceErrorBoundary>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -2739,6 +2739,52 @@ describe("HostRuntimeStore", () => {
|
||||
session.clearSession(host.serverId);
|
||||
});
|
||||
|
||||
it("loads the directory for a consumer that sees a restored host before the registry finishes loading", async () => {
|
||||
const host = makeHost({
|
||||
connections: [{ id: "direct:lan:6767", type: "directTcp", endpoint: "lan:6767" }],
|
||||
});
|
||||
const fakeClient = new FakeDaemonClient();
|
||||
fakeClient.setConnectionState({ status: "connected" });
|
||||
const store = new HostRuntimeStore({
|
||||
storage: createMemoryHostRuntimeStorage({
|
||||
[REGISTRY_KEY]: JSON.stringify([host]),
|
||||
"@paseo:e2e": "1",
|
||||
}),
|
||||
deps: {
|
||||
createClient: () => fakeClient as unknown as DaemonClient,
|
||||
connectToDaemon: async ({ host: hostProfile }) => ({
|
||||
client: fakeClient as unknown as DaemonClient,
|
||||
serverId: hostProfile.serverId,
|
||||
hostname: hostProfile.label ?? null,
|
||||
}),
|
||||
getClientId: async () => "cid_test_runtime",
|
||||
},
|
||||
});
|
||||
|
||||
// A component renders on every tick while the registry loads, and acquires directory
|
||||
// demand for each host it reads, as the sidebar does on its first render.
|
||||
const registry = { loading: true };
|
||||
const boot = store.boot().finally(() => {
|
||||
registry.loading = false;
|
||||
});
|
||||
let releaseDemand: (() => void) | null = null;
|
||||
while (registry.loading && !releaseDemand) {
|
||||
if (store.getHosts().some((candidate) => candidate.serverId === host.serverId)) {
|
||||
releaseDemand = store.acquireDirectoryDemand(host.serverId);
|
||||
}
|
||||
await Promise.resolve();
|
||||
}
|
||||
await boot;
|
||||
expect(releaseDemand).not.toBeNull();
|
||||
|
||||
await waitForHostOnline(store, host.serverId);
|
||||
await vi.waitFor(() => expect(fakeClient.fetchAgentsCalls).toHaveLength(1));
|
||||
|
||||
releaseDemand?.();
|
||||
store.syncHosts([]);
|
||||
useSessionStore.getState().clearSession(host.serverId);
|
||||
});
|
||||
|
||||
it("keeps readable hosts when the registry holds entries this build can't read", async () => {
|
||||
const { store, storage } = await bootWithRegistry(JSON.stringify(storedWithUnreadableEntries));
|
||||
|
||||
@@ -2863,7 +2909,8 @@ describe("HostRuntimeStore", () => {
|
||||
await registryLoaded;
|
||||
|
||||
expect(store.isHostRegistryLoaded()).toBe(true);
|
||||
expect(hostListNotifications).toBe(2);
|
||||
// Publishing the restored hosts, the registry turning ready, and the registry loading.
|
||||
expect(hostListNotifications).toBe(3);
|
||||
} finally {
|
||||
if (previousOverride === undefined) {
|
||||
delete process.env.EXPO_PUBLIC_LOCAL_DAEMON;
|
||||
|
||||
@@ -1816,11 +1816,9 @@ export class HostRuntimeStore {
|
||||
shouldPersistHosts = true;
|
||||
}
|
||||
}
|
||||
this.hosts = profiles;
|
||||
this.replicaCache.setHosts(profiles.map((profile) => profile.serverId));
|
||||
projectIconCache.setHosts(profiles.map((profile) => profile.serverId));
|
||||
await projectIconCache.restore();
|
||||
this.syncHosts(profiles);
|
||||
this.setHostsAndSync(profiles);
|
||||
for (const profile of profiles) {
|
||||
void this.directorySyncByServer
|
||||
.get(profile.serverId)
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
type SqliteValue,
|
||||
} from "@/runtime/replica-cache/row-store-sqlite";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import type { AgentTimelineItem } from "@getpaseo/protocol/agent-types";
|
||||
import type { AgentStreamEventPayload } from "@getpaseo/protocol/messages";
|
||||
import type { CachedTimeline } from "@/runtime/replica-cache";
|
||||
import {
|
||||
@@ -17,6 +18,8 @@ import {
|
||||
} from "@/stores/session-store";
|
||||
import { useCreateFlowStore, type PendingCreateAttempt } from "@/stores/create-flow-store";
|
||||
import type { StreamItem } from "@/types/stream";
|
||||
import type { AgentStreamReducerEvent } from "./session-stream-reducers";
|
||||
import type { ProjectedTimelineForwardFetchPlan } from "./timeline-sync-plan";
|
||||
import { reduceTurnLiveness, type TurnLivenessTransition } from "./turn-liveness";
|
||||
import {
|
||||
createTimelineReplica,
|
||||
@@ -1379,6 +1382,318 @@ describe("create handoff lifetime", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("a chat that was empty when it went offline", () => {
|
||||
const EPOCH = "epoch-1";
|
||||
const PROMPT = "stream through a reconnect";
|
||||
const THOUGHT = "Thinking before the reply.";
|
||||
const TURN_ID = "turn-1";
|
||||
const TIMESTAMP = "2026-10-31T10:00:00.000Z";
|
||||
|
||||
/** The daemon's timeline: one row per flushed chunk, read back as projected pages. */
|
||||
class DaemonTimeline {
|
||||
private readonly rows: Array<{ seq: number; item: AgentTimelineItem }> = [];
|
||||
|
||||
record(timelineItem: AgentTimelineItem): AgentStreamReducerEvent {
|
||||
const seq = this.rows.length + 1;
|
||||
this.rows.push({ seq, item: timelineItem });
|
||||
return {
|
||||
event: { type: "timeline", provider: "mock", turnId: TURN_ID, item: timelineItem },
|
||||
seq,
|
||||
epoch: EPOCH,
|
||||
timestamp: new Date(TIMESTAMP),
|
||||
};
|
||||
}
|
||||
|
||||
page(request: ProjectedTimelineForwardFetchPlan): TimelineResponsePayload {
|
||||
const maxSeq = this.rows.at(-1)?.seq ?? 0;
|
||||
const after = request.direction === "after" ? request.cursor.seq : 0;
|
||||
const entries = this.projected().filter((entry) => entry.seqEnd > after);
|
||||
const first = entries[0];
|
||||
const startSeq = request.direction === "after" ? after + 1 : first?.seqStart;
|
||||
return {
|
||||
requestId: `${request.direction}-${after}`,
|
||||
agentId: AGENT_ID,
|
||||
agent: null,
|
||||
direction: request.direction,
|
||||
projection: "projected",
|
||||
reset: false,
|
||||
epoch: EPOCH,
|
||||
window: { minSeq: this.rows[0]?.seq ?? 0, maxSeq, nextSeq: maxSeq + 1 },
|
||||
startCursor: first && startSeq !== undefined ? { epoch: EPOCH, seq: startSeq } : null,
|
||||
endCursor: first ? { epoch: EPOCH, seq: maxSeq } : null,
|
||||
entries,
|
||||
error: null,
|
||||
hasNewer: false,
|
||||
hasOlder: after > 0,
|
||||
staleCursor: false,
|
||||
gap: false,
|
||||
};
|
||||
}
|
||||
|
||||
/** Contiguous reply and thought chunks read back as one row, like the daemon's projection. */
|
||||
private projected(): TimelineResponsePayload["entries"] {
|
||||
const entries: TimelineResponsePayload["entries"] = [];
|
||||
for (const { seq, item: row } of this.rows) {
|
||||
const previous = entries.at(-1);
|
||||
const continues =
|
||||
previous !== undefined &&
|
||||
((row.type === "assistant_message" &&
|
||||
previous.item.type === "assistant_message" &&
|
||||
previous.item.messageId === row.messageId) ||
|
||||
(row.type === "reasoning" && previous.item.type === "reasoning"));
|
||||
if (
|
||||
continues &&
|
||||
(previous.item.type === "assistant_message" || previous.item.type === "reasoning") &&
|
||||
(row.type === "assistant_message" || row.type === "reasoning")
|
||||
) {
|
||||
previous.item = { ...previous.item, text: `${previous.item.text}${row.text}` };
|
||||
previous.seqEnd = seq;
|
||||
previous.sourceSeqRanges = [{ startSeq: previous.seqStart, endSeq: seq }];
|
||||
previous.collapsed = [
|
||||
row.type === "assistant_message" ? "assistant_merge" : "reasoning_merge",
|
||||
];
|
||||
continue;
|
||||
}
|
||||
entries.push({
|
||||
provider: "mock",
|
||||
item: row,
|
||||
timestamp: TIMESTAMP,
|
||||
seqStart: seq,
|
||||
seqEnd: seq,
|
||||
sourceSeqRanges: [{ startSeq: seq, endSeq: seq }],
|
||||
collapsed: [],
|
||||
turnId: TURN_ID,
|
||||
});
|
||||
}
|
||||
return entries;
|
||||
}
|
||||
}
|
||||
|
||||
interface PendingFetch {
|
||||
request: ProjectedTimelineForwardFetchPlan;
|
||||
/** Delivers a page the way the host runtime does: queued live chunks first, then the page. */
|
||||
deliver(page: TimelineResponsePayload): void;
|
||||
}
|
||||
|
||||
function openChat(storage: TimelineReplicaStorage) {
|
||||
const fetches: PendingFetch[] = [];
|
||||
const errors: unknown[] = [];
|
||||
const fetch = (request: ProjectedTimelineForwardFetchPlan) =>
|
||||
new Promise<{ hasNewer: boolean; endCursor: { epoch: string; seq: number } | null }>(
|
||||
(resolve) => {
|
||||
fetches.push({
|
||||
request,
|
||||
deliver: (page) => {
|
||||
owner.flushStreamAgent(AGENT_ID);
|
||||
owner.applyTimelineResponse(page);
|
||||
resolve({ hasNewer: page.hasNewer, endCursor: page.endCursor });
|
||||
},
|
||||
});
|
||||
},
|
||||
);
|
||||
const replica = createTimelineReplica({
|
||||
serverId: SERVER_ID,
|
||||
storage,
|
||||
prepareAgent: async () => undefined,
|
||||
});
|
||||
const owner = createViewedTimelineOwner({
|
||||
serverId: SERVER_ID,
|
||||
replica,
|
||||
replaceDemandedAgentIds: () => undefined,
|
||||
drainQueuedAgentMessage: () => undefined,
|
||||
applyTurnLiveness: () => undefined,
|
||||
ports: {
|
||||
canCheckFreshness: () => true,
|
||||
observe: () => ({ ready: Promise.resolve(), release: async () => undefined }),
|
||||
readCursor: (agentId) => {
|
||||
const timeline = selectAgentTimelineState(
|
||||
useSessionStore.getState().sessions[SERVER_ID],
|
||||
agentId,
|
||||
);
|
||||
return timeline.status === "synced" && timeline.range
|
||||
? { epoch: timeline.range.epoch, endSeq: timeline.range.endSeq }
|
||||
: undefined;
|
||||
},
|
||||
fetchPage: (_agentId, request) => fetch(request),
|
||||
fetchLatestTail: () =>
|
||||
fetch({ direction: "tail", limit: 40, projection: "projected", wholeTurns: true }),
|
||||
reportError: (error) => errors.push(error),
|
||||
},
|
||||
});
|
||||
owner.setConnected(true);
|
||||
owner.replaceVisibleAgentIds("test", [AGENT_ID]);
|
||||
return {
|
||||
owner,
|
||||
async nextFetch(): Promise<PendingFetch> {
|
||||
await expect.poll(() => fetches.length).toBeGreaterThan(0);
|
||||
return fetches.shift()!;
|
||||
},
|
||||
live(event: AgentStreamReducerEvent): void {
|
||||
owner.applyStreamEvent(AGENT_ID, event);
|
||||
owner.flushStreamAgent(AGENT_ID);
|
||||
},
|
||||
/** Answers every catch-up the chat still asks for until it reports itself current. */
|
||||
async settle(daemon: DaemonTimeline): Promise<void> {
|
||||
for (let turn = 0; turn < 20; turn += 1) {
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
expect(errors).toEqual([]);
|
||||
const next = fetches.shift();
|
||||
if (next) next.deliver(daemon.page(next.request));
|
||||
else if (owner.getAgentTimelineStatus(AGENT_ID) === "ready") return;
|
||||
}
|
||||
throw new Error("The chat never caught up");
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function rows(): Array<{ kind: StreamItem["kind"]; text: string }> {
|
||||
const session = useSessionStore.getState().sessions[SERVER_ID];
|
||||
return [
|
||||
...(session?.agentStreamTail.get(AGENT_ID) ?? []),
|
||||
...(session?.agentStreamHead.get(AGENT_ID) ?? []),
|
||||
].map((entry) => ({
|
||||
kind: entry.kind,
|
||||
text: "text" in entry && typeof entry.text === "string" ? entry.text : "",
|
||||
}));
|
||||
}
|
||||
|
||||
const reply = (words: number) =>
|
||||
Array.from({ length: words }, (_unused, index) => `word${index}`).join(" ");
|
||||
const chunk = (index: number) => `${index === 0 ? "" : " "}word${index}`;
|
||||
const replyChunk = (index: number): AgentTimelineItem => ({
|
||||
type: "assistant_message",
|
||||
text: chunk(index),
|
||||
messageId: "reply-1",
|
||||
});
|
||||
|
||||
/**
|
||||
* Opens the chat while its timeline is empty, then drops the connection while the prompt,
|
||||
* an optional thought and the first three reply chunks are recorded.
|
||||
*/
|
||||
async function goOfflineWhileTheReplyStarts(input: {
|
||||
reasoning: boolean;
|
||||
storage: TimelineReplicaStorage;
|
||||
}) {
|
||||
useSessionStore.getState().initializeSession(SERVER_ID, null);
|
||||
const daemon = new DaemonTimeline();
|
||||
const chat = openChat(input.storage);
|
||||
const opened = await chat.nextFetch();
|
||||
opened.deliver(daemon.page(opened.request));
|
||||
expect(
|
||||
selectAgentTimelineState(useSessionStore.getState().sessions[SERVER_ID], AGENT_ID),
|
||||
).toEqual({ status: "synced", items: [], range: null, older: "none", newer: "none" });
|
||||
|
||||
chat.owner.setConnected(false);
|
||||
daemon.record({ type: "user_message", text: PROMPT, messageId: "prompt-1" });
|
||||
if (input.reasoning) daemon.record({ type: "reasoning", text: THOUGHT });
|
||||
for (const index of [0, 1, 2]) daemon.record(replyChunk(index));
|
||||
chat.owner.setConnected(true);
|
||||
const catchUp = await chat.nextFetch();
|
||||
return { daemon, chat, catchUp };
|
||||
}
|
||||
|
||||
function expectedRows(reasoning: boolean, words: number) {
|
||||
return [
|
||||
{ kind: "user_message", text: PROMPT },
|
||||
...(reasoning ? [{ kind: "thought", text: THOUGHT }] : []),
|
||||
{ kind: "assistant_message", text: reply(words) },
|
||||
];
|
||||
}
|
||||
|
||||
/** A saved range that starts after the prompt claims history the chat never received. */
|
||||
function expectCoverageFromTheFirstRow(commits: CachedTimeline[]): void {
|
||||
expect(commits.map((commit) => commit.range?.startSeq ?? 1)).toEqual(commits.map(() => 1));
|
||||
}
|
||||
|
||||
it.each([true, false])(
|
||||
"keeps the prompt and the whole reply when live chunks arrive before a page that holds them (reasoning=%s)",
|
||||
async (reasoning) => {
|
||||
const commits: CachedTimeline[] = [];
|
||||
const { daemon, chat, catchUp } = await goOfflineWhileTheReplyStarts({
|
||||
reasoning,
|
||||
storage: {
|
||||
readTimeline: async () => undefined,
|
||||
commitTimeline: (_serverId, _agentId, timeline) => commits.push(timeline),
|
||||
},
|
||||
});
|
||||
try {
|
||||
chat.live(daemon.record(replyChunk(3)));
|
||||
chat.live(daemon.record(replyChunk(4)));
|
||||
catchUp.deliver(daemon.page(catchUp.request));
|
||||
chat.live(daemon.record(replyChunk(5)));
|
||||
await chat.settle(daemon);
|
||||
|
||||
expect(rows()).toEqual(expectedRows(reasoning, 6));
|
||||
expectCoverageFromTheFirstRow(commits);
|
||||
} finally {
|
||||
chat.owner.dispose();
|
||||
}
|
||||
|
||||
// The saved chat paints the same rows after a reload.
|
||||
const saved = commits.at(-1);
|
||||
useSessionStore.getState().clearSession(SERVER_ID);
|
||||
useSessionStore.getState().initializeSession(SERVER_ID, null);
|
||||
const reopened = createOwner({
|
||||
readTimeline: async () => saved,
|
||||
commitTimeline: () => undefined,
|
||||
});
|
||||
try {
|
||||
reopened.replaceVisibleAgentIds("test", [AGENT_ID]);
|
||||
await expect.poll(rows).toEqual(expectedRows(reasoning, 6));
|
||||
} finally {
|
||||
reopened.dispose();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it("keeps the prompt when the page already holds a chunk the chat has not seen live", async () => {
|
||||
const commits: CachedTimeline[] = [];
|
||||
const { daemon, chat, catchUp } = await goOfflineWhileTheReplyStarts({
|
||||
reasoning: true,
|
||||
storage: {
|
||||
readTimeline: async () => undefined,
|
||||
commitTimeline: (_serverId, _agentId, timeline) => commits.push(timeline),
|
||||
},
|
||||
});
|
||||
try {
|
||||
chat.live(daemon.record(replyChunk(3)));
|
||||
const notYetLive = daemon.record(replyChunk(4));
|
||||
catchUp.deliver(daemon.page(catchUp.request));
|
||||
chat.live(notYetLive);
|
||||
chat.live(daemon.record(replyChunk(5)));
|
||||
await chat.settle(daemon);
|
||||
|
||||
expect(rows()).toEqual(expectedRows(true, 6));
|
||||
expectCoverageFromTheFirstRow(commits);
|
||||
} finally {
|
||||
chat.owner.dispose();
|
||||
}
|
||||
});
|
||||
|
||||
it("finishes the reply when its last chunks arrive while an older page is in flight", async () => {
|
||||
const commits: CachedTimeline[] = [];
|
||||
const { daemon, chat, catchUp } = await goOfflineWhileTheReplyStarts({
|
||||
reasoning: true,
|
||||
storage: {
|
||||
readTimeline: async () => undefined,
|
||||
commitTimeline: (_serverId, _agentId, timeline) => commits.push(timeline),
|
||||
},
|
||||
});
|
||||
try {
|
||||
const olderPage = daemon.page(catchUp.request);
|
||||
chat.live(daemon.record(replyChunk(3)));
|
||||
chat.live(daemon.record(replyChunk(4)));
|
||||
catchUp.deliver(olderPage);
|
||||
await chat.settle(daemon);
|
||||
|
||||
expect(rows()).toEqual(expectedRows(true, 5));
|
||||
expectCoverageFromTheFirstRow(commits);
|
||||
} finally {
|
||||
chat.owner.dispose();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
function createSqliteCache() {
|
||||
const database = new DatabaseSync(":memory:");
|
||||
let beforeRead = async () => {};
|
||||
|
||||
@@ -53,6 +53,7 @@ it.each([false, true])(
|
||||
(hasAuthoritativeBaseline) => {
|
||||
let head: StreamItem[] = [];
|
||||
let tail: StreamItem[] = [];
|
||||
let cursor: TimelineCursor | undefined;
|
||||
for (const [index, turnId] of ["turn-1", "turn-2"].entries()) {
|
||||
const result = processAgentStreamEvent({
|
||||
event: {
|
||||
@@ -65,12 +66,13 @@ it.each([false, true])(
|
||||
epoch: "epoch-1",
|
||||
currentTail: tail,
|
||||
currentHead: head,
|
||||
currentCursor: undefined,
|
||||
currentCursor: cursor,
|
||||
timestamp: new Date(1000),
|
||||
hasAuthoritativeBaseline,
|
||||
});
|
||||
head = result.head;
|
||||
tail = result.tail;
|
||||
cursor = result.cursor ?? cursor;
|
||||
}
|
||||
expect([...tail, ...head]).toMatchObject([
|
||||
{ kind: "thought", text: "turn-1", turnId: "turn-1" },
|
||||
@@ -2848,7 +2850,7 @@ describe("processTimelineResponse", () => {
|
||||
],
|
||||
currentTail: [],
|
||||
currentHead: [],
|
||||
currentCursor: undefined,
|
||||
currentCursor: { epoch: "epoch-1", startSeq: 60, endSeq: 79 },
|
||||
});
|
||||
expect(getAssistantTexts([...live.tail, ...live.head])).toEqual([
|
||||
"First paragraph.\n\nSecond paragraph.",
|
||||
@@ -3677,6 +3679,7 @@ describe("processAgentStreamEvent", () => {
|
||||
event: makeAssistantTimelineEvent("[System Error] failed"),
|
||||
epoch: "timeline-1",
|
||||
seq: 42,
|
||||
currentCursor: { epoch: "timeline-1", startSeq: 1, endSeq: 41 },
|
||||
});
|
||||
|
||||
expect(result.head).toEqual([
|
||||
@@ -3897,6 +3900,24 @@ describe("processAgentStreamEvent", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("catches up from the first row when a chat that was empty receives a later row", () => {
|
||||
const result = processAgentStreamEvent({
|
||||
...baseStreamInput,
|
||||
event: makeTimelineEvent("word3"),
|
||||
seq: 6,
|
||||
epoch: "epoch-1",
|
||||
currentCursor: undefined,
|
||||
});
|
||||
|
||||
expect(result).toMatchObject({
|
||||
head: [],
|
||||
changedHead: false,
|
||||
cursor: null,
|
||||
cursorChanged: false,
|
||||
sideEffects: [{ type: "catch_up", cursor: { epoch: "epoch-1", endSeq: 0 } }],
|
||||
});
|
||||
});
|
||||
|
||||
it("renders a live row over painted items without creating an authoritative cursor", () => {
|
||||
const result = processAgentStreamEvent({
|
||||
...baseStreamInput,
|
||||
@@ -4087,7 +4108,7 @@ describe("processAgentStreamEvents", () => {
|
||||
],
|
||||
currentTail: [],
|
||||
currentHead: [],
|
||||
currentCursor: undefined,
|
||||
currentCursor: { epoch: "epoch-1", startSeq: 1, endSeq: 237 },
|
||||
});
|
||||
|
||||
expect(result.changedTail).toBe(false);
|
||||
@@ -4261,6 +4282,7 @@ describe("processAgentStreamEvents", () => {
|
||||
currentTail: [],
|
||||
currentHead: [],
|
||||
currentCursor: undefined,
|
||||
hasAuthoritativeBaseline: false,
|
||||
timestamp: new Date("2026-05-02T10:00:00.186Z"),
|
||||
});
|
||||
|
||||
@@ -4462,7 +4484,7 @@ describe("createAgentStreamReducerQueue", () => {
|
||||
const scheduler = createManualScheduler();
|
||||
let currentTail: StreamItem[] = [];
|
||||
let currentHead: StreamItem[] = [];
|
||||
let currentCursor: TimelineCursor | undefined;
|
||||
let currentCursor: TimelineCursor | undefined = { epoch: "epoch-1", startSeq: 1, endSeq: 1 };
|
||||
|
||||
const queue = createAgentStreamReducerQueue({
|
||||
getSnapshot: () => ({
|
||||
@@ -4505,7 +4527,7 @@ describe("createAgentStreamReducerQueue", () => {
|
||||
expect(getAssistantTexts(currentHead)).toEqual(["This is a paragraph continues."]);
|
||||
expect(currentCursor).toEqual({
|
||||
epoch: "epoch-1",
|
||||
startSeq: 2,
|
||||
startSeq: 1,
|
||||
endSeq: 4,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -289,7 +289,10 @@ function classifySessionTimelineSeq({
|
||||
seq: number;
|
||||
}): SessionTimelineSeqDecision {
|
||||
if (!cursor) {
|
||||
return "init";
|
||||
// A synced chat without coverage was empty when it last caught up. Only an epoch's
|
||||
// first row can start coverage; a later row means rows before it were missed, for
|
||||
// example while offline, and a cursor started there would hide them from catch-up.
|
||||
return seq === 1 ? "init" : "gap";
|
||||
}
|
||||
if (cursor.epoch !== epoch) {
|
||||
return "drop_epoch";
|
||||
@@ -1543,14 +1546,14 @@ function processTimelineSequencingGate(input: {
|
||||
return {
|
||||
...base,
|
||||
shouldApplyStreamEvent: false,
|
||||
sideEffects: currentCursor
|
||||
? [
|
||||
{
|
||||
type: "catch_up",
|
||||
cursor: { epoch: currentCursor.epoch, endSeq: currentCursor.endSeq },
|
||||
},
|
||||
]
|
||||
: [],
|
||||
sideEffects: [
|
||||
{
|
||||
type: "catch_up",
|
||||
cursor: currentCursor
|
||||
? { epoch: currentCursor.epoch, endSeq: currentCursor.endSeq }
|
||||
: { epoch, endSeq: 0 },
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
if (decision === "drop_epoch" && seq === 1) {
|
||||
|
||||
@@ -64,6 +64,21 @@ export function planTimelineResumeFetch(
|
||||
: planTimelineTailFetch();
|
||||
}
|
||||
|
||||
/**
|
||||
* A catch-up that waited behind another starts after the rows applied meanwhile. A forward
|
||||
* page is applied row by row, so asking again for rows the chat already holds repeats them.
|
||||
*/
|
||||
export function planTimelineCatchUpPastApplied(
|
||||
request: ProjectedTimelineForwardFetchPlan,
|
||||
applied: { epoch: string; endSeq: number } | undefined,
|
||||
): ProjectedTimelineForwardFetchPlan {
|
||||
if (request.direction !== "after" || !applied) return request;
|
||||
if (applied.epoch !== request.cursor.epoch || applied.endSeq <= request.cursor.seq) {
|
||||
return request;
|
||||
}
|
||||
return planTimelineCatchUpAfter({ epoch: applied.epoch, seq: applied.endSeq });
|
||||
}
|
||||
|
||||
export function planTimelineOlderFetch(cursor: TimelineSyncCursor) {
|
||||
return {
|
||||
direction: "before",
|
||||
|
||||
@@ -441,6 +441,96 @@ test("a gap absorbed by a running tail is recovered after the tail completes", a
|
||||
await vi.waitFor(() => expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("ready"));
|
||||
});
|
||||
|
||||
test("a gap parked behind a running tail resumes after the rows that tail applied", async () => {
|
||||
const world = new TimelineWorld();
|
||||
world.sync.setConnected(true);
|
||||
world.sync.replaceVisibleAgentIds("workspace", ["agent-a"]);
|
||||
(await world.nextMembership()).succeed();
|
||||
const tail = await world.nextFetch("agent-a");
|
||||
|
||||
world.sync.recoverGap("agent-a", { epoch: "epoch-agent-a", endSeq: 0 });
|
||||
world.cursors.set("agent-a", { epoch: "epoch-agent-a", endSeq: 7 });
|
||||
tail.respond({ hasNewer: false, seq: 7 });
|
||||
|
||||
const recovery = await world.nextFetch("agent-a");
|
||||
expect(recovery.request).toEqual({
|
||||
direction: "after",
|
||||
cursor: { epoch: "epoch-agent-a", seq: 7 },
|
||||
limit: 40,
|
||||
projection: "projected",
|
||||
wholeTurns: true,
|
||||
});
|
||||
recovery.respond({ hasNewer: false, seq: 7 });
|
||||
await vi.waitFor(() => expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("ready"));
|
||||
world.sync.dispose();
|
||||
});
|
||||
|
||||
test("a chat without coverage that recovers a gap loads the latest tail when history overflows a page", async () => {
|
||||
const world = new TimelineWorld();
|
||||
world.sync.setConnected(true);
|
||||
world.sync.replaceVisibleAgentIds("workspace", ["agent-a"]);
|
||||
(await world.nextMembership()).succeed();
|
||||
const tail = await world.nextFetch("agent-a");
|
||||
|
||||
world.sync.recoverGap("agent-a", { epoch: "epoch-agent-a", endSeq: 0 });
|
||||
tail.respond({ hasNewer: false, seq: 0 });
|
||||
|
||||
const recovery = await world.nextFetch("agent-a");
|
||||
expect(recovery.request).toEqual({
|
||||
direction: "after",
|
||||
cursor: { epoch: "epoch-agent-a", seq: 0 },
|
||||
limit: 40,
|
||||
projection: "projected",
|
||||
wholeTurns: true,
|
||||
});
|
||||
recovery.respond({ hasNewer: true, seq: 40 });
|
||||
|
||||
const fallback = await world.nextFetch("agent-a");
|
||||
expect(fallback.request).toEqual({
|
||||
direction: "tail",
|
||||
limit: 40,
|
||||
projection: "projected",
|
||||
wholeTurns: true,
|
||||
});
|
||||
fallback.respond({ hasNewer: false, seq: 90 });
|
||||
await vi.waitFor(() => expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("ready"));
|
||||
world.sync.dispose();
|
||||
});
|
||||
|
||||
test("a recovery's follow-up page starts after rows another fetch applied meanwhile", async () => {
|
||||
const world = new TimelineWorld();
|
||||
world.sync.setConnected(true);
|
||||
world.sync.replaceVisibleAgentIds("workspace", ["agent-a"]);
|
||||
(await world.nextMembership()).succeed();
|
||||
(await world.nextFetch("agent-a")).respond({ hasNewer: false, seq: 0 });
|
||||
await vi.waitFor(() => expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("ready"));
|
||||
|
||||
world.sync.recoverGap("agent-a", { epoch: "epoch-agent-a", endSeq: 0 });
|
||||
const firstPage = await world.nextFetch("agent-a");
|
||||
world.cursors.set("agent-a", { epoch: "epoch-agent-a", endSeq: 40 });
|
||||
firstPage.respond({ hasNewer: true, seq: 40 });
|
||||
const latestTail = await world.nextFetch("agent-a");
|
||||
expect(latestTail.request.direction).toBe("tail");
|
||||
|
||||
world.sync.recoverGap("agent-a", { epoch: "epoch-agent-a", endSeq: 40 });
|
||||
const recovery = await world.nextFetch("agent-a");
|
||||
world.cursors.set("agent-a", { epoch: "epoch-agent-a", endSeq: 300 });
|
||||
latestTail.respond({ hasNewer: false, seq: 300 });
|
||||
recovery.respond({ hasNewer: true, seq: 80 });
|
||||
|
||||
const followUp = await world.nextFetch("agent-a");
|
||||
expect(followUp.request).toEqual({
|
||||
direction: "after",
|
||||
cursor: { epoch: "epoch-agent-a", seq: 300 },
|
||||
limit: 40,
|
||||
projection: "projected",
|
||||
wholeTurns: true,
|
||||
});
|
||||
followUp.respond({ hasNewer: false, seq: 300 });
|
||||
await vi.waitFor(() => expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("ready"));
|
||||
world.sync.dispose();
|
||||
});
|
||||
|
||||
test("reports a chat current only once its parked follow-up page completes", async () => {
|
||||
const world = new TimelineWorld();
|
||||
world.sync.setConnected(true);
|
||||
@@ -885,7 +975,8 @@ test("gap recovery supersedes completed catch-up and pages through the current t
|
||||
const membership = await world.nextMembership();
|
||||
membership.succeed();
|
||||
const initial = await world.nextFetch("agent-a");
|
||||
initial.respond({ hasNewer: false });
|
||||
world.cursors.set("agent-a", { epoch: "epoch-agent-a", endSeq: 10 });
|
||||
initial.respond({ hasNewer: false, seq: 10 });
|
||||
await vi.waitFor(() => expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("ready"));
|
||||
|
||||
world.sync.recoverGap("agent-a", { epoch: "epoch-agent-a", endSeq: 10 });
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import {
|
||||
planTimelineCatchUpAfter,
|
||||
planTimelineCatchUpPastApplied,
|
||||
planTimelineResumeFetch,
|
||||
type ProjectedTimelineForwardFetchPlan,
|
||||
} from "./timeline-sync-plan";
|
||||
@@ -741,7 +742,10 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
|
||||
await fetchUntilCurrent(
|
||||
agentId,
|
||||
generation,
|
||||
planTimelineCatchUpAfter(page.endCursor),
|
||||
planTimelineCatchUpPastApplied(
|
||||
planTimelineCatchUpAfter(page.endCursor),
|
||||
ports.readCursor(agentId),
|
||||
),
|
||||
false,
|
||||
);
|
||||
return;
|
||||
@@ -819,7 +823,10 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
|
||||
ensureCacheLoaded(agentId);
|
||||
return;
|
||||
}
|
||||
const nextRequest = request ?? planTimelineResumeFetch(ports.readCursor(agentId));
|
||||
const applied = ports.readCursor(agentId);
|
||||
const nextRequest = request
|
||||
? planTimelineCatchUpPastApplied(request, applied)
|
||||
: planTimelineResumeFetch(applied);
|
||||
const current = catchUps.get(agentId);
|
||||
const decision = decideCatchUp({ current, request: nextRequest, supersede });
|
||||
if (decision === "keep-and-park") {
|
||||
@@ -833,11 +840,13 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
|
||||
catchUpGenerations.set(agentId, generation);
|
||||
catchUps.set(agentId, { generation, status: "running", request: nextRequest });
|
||||
pendingCatchUps.delete(agentId);
|
||||
// A gap recovery pages forward to keep the coverage it extends. Without coverage there is
|
||||
// nothing to keep, so an overflowing page falls back to the latest tail, as a resume does.
|
||||
void fetchUntilCurrent(
|
||||
agentId,
|
||||
generation,
|
||||
nextRequest,
|
||||
request === undefined && nextRequest.direction === "after",
|
||||
nextRequest.direction === "after" && (request === undefined || applied === undefined),
|
||||
);
|
||||
};
|
||||
|
||||
|
||||
@@ -73,6 +73,18 @@ describe("desktop-badge-state", () => {
|
||||
expect(selectMacDockBadgeCount(state)).toBe(3);
|
||||
});
|
||||
|
||||
it("leaves out background workspaces, which the sidebar hides", () => {
|
||||
const hidden = { ...workspace("a", "attention"), background: true };
|
||||
expect(selectMacDockBadgeCount(stateWith(hidden))).toBeUndefined();
|
||||
expect(selectMacDockBadgeCount(stateWith(hidden, workspace("b", "failed")))).toBe(1);
|
||||
});
|
||||
|
||||
it("counts background workspaces while Show background puts them in the sidebar", () => {
|
||||
const hidden = { ...workspace("a", "attention"), background: true };
|
||||
expect(selectMacDockBadgeCount(stateWith(hidden), { showBackground: true })).toBe(1);
|
||||
expect(createMacDockBadgeCountSelector({ showBackground: true })(stateWith(hidden))).toBe(1);
|
||||
});
|
||||
|
||||
it("recounts only when a workspace map is replaced", () => {
|
||||
const select = createMacDockBadgeCountSelector();
|
||||
const state = stateWith(workspace("a", "attention"));
|
||||
|
||||
@@ -19,11 +19,21 @@ export function isWorkspaceActionableForDesktopBadge(status: DesktopBadgeWorkspa
|
||||
* The macOS dock badge only needs a count, so count here instead of materialising every
|
||||
* workspace status and comparing the whole list on every store write.
|
||||
*/
|
||||
export function selectMacDockBadgeCount(state: WorkspaceStatusSource): number | undefined {
|
||||
export interface DockBadgeOptions {
|
||||
/** Count background workspaces too, as the sidebar shows them while Show background is on. */
|
||||
showBackground?: boolean;
|
||||
}
|
||||
|
||||
export function selectMacDockBadgeCount(
|
||||
state: WorkspaceStatusSource,
|
||||
options: DockBadgeOptions = {},
|
||||
): number | undefined {
|
||||
let actionableCount = 0;
|
||||
for (const session of Object.values(state.sessions)) {
|
||||
if (!session) continue;
|
||||
for (const workspace of session.workspaces.values()) {
|
||||
// A hidden background workspace would leave the badge pointing at nothing in the sidebar.
|
||||
if (workspace.background && !options.showBackground) continue;
|
||||
if (isWorkspaceActionableForDesktopBadge(workspace.status)) actionableCount += 1;
|
||||
}
|
||||
}
|
||||
@@ -31,11 +41,11 @@ export function selectMacDockBadgeCount(state: WorkspaceStatusSource): number |
|
||||
}
|
||||
|
||||
/** A session-store selector for the dock badge count that recounts only when a workspace map changes. */
|
||||
export function createMacDockBadgeCountSelector(): (
|
||||
state: WorkspaceStatusSource,
|
||||
) => number | undefined {
|
||||
export function createMacDockBadgeCountSelector(
|
||||
options: DockBadgeOptions = {},
|
||||
): (state: WorkspaceStatusSource) => number | undefined {
|
||||
return memoizeOnSessionMaps<WorkspaceStatusSession, WorkspaceStatusSource, number | undefined>(
|
||||
(session) => session.workspaces,
|
||||
selectMacDockBadgeCount,
|
||||
(session) => [session.workspaces],
|
||||
(state) => selectMacDockBadgeCount(state, options),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { Agent } from "@/stores/session-store";
|
||||
import type { Agent, WorkspaceDescriptor } from "@/stores/session-store";
|
||||
import { createFaviconStatusSelector, deriveFaviconStatus } from "./favicon-status";
|
||||
|
||||
function agent(input: Partial<Agent> & { id: string }): Agent {
|
||||
@@ -14,7 +14,21 @@ function agent(input: Partial<Agent> & { id: string }): Agent {
|
||||
}
|
||||
|
||||
function stateWith(...agents: Agent[]) {
|
||||
return { sessions: { srv: { agents: new Map(agents.map((entry) => [entry.id, entry])) } } };
|
||||
return stateWithWorkspaces([], ...agents);
|
||||
}
|
||||
|
||||
function stateWithWorkspaces(
|
||||
workspaces: Array<Pick<WorkspaceDescriptor, "id" | "background">>,
|
||||
...agents: Agent[]
|
||||
) {
|
||||
return {
|
||||
sessions: {
|
||||
srv: {
|
||||
agents: new Map(agents.map((entry) => [entry.id, entry])),
|
||||
workspaces: new Map(workspaces.map((entry) => [entry.id, entry])),
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe("deriveFaviconStatus", () => {
|
||||
@@ -50,6 +64,37 @@ describe("deriveFaviconStatus", () => {
|
||||
),
|
||||
).toBe("none");
|
||||
});
|
||||
|
||||
it("ignores agents in background workspaces, which the sidebar hides", () => {
|
||||
const hidden = { id: "ws-hidden", background: true };
|
||||
expect(
|
||||
deriveFaviconStatus(
|
||||
stateWithWorkspaces(
|
||||
[hidden],
|
||||
agent({ id: "a", workspaceId: "ws-hidden", requiresAttention: true }),
|
||||
agent({ id: "b", workspaceId: "ws-hidden", status: "running" }),
|
||||
),
|
||||
),
|
||||
).toBe("none");
|
||||
expect(
|
||||
deriveFaviconStatus(
|
||||
stateWithWorkspaces(
|
||||
[hidden, { id: "ws-shown", background: false }],
|
||||
agent({ id: "a", workspaceId: "ws-hidden", status: "running" }),
|
||||
agent({ id: "b", workspaceId: "ws-shown", requiresAttention: true }),
|
||||
),
|
||||
),
|
||||
).toBe("attention");
|
||||
});
|
||||
|
||||
it("counts agents in background workspaces while Show background puts them in the sidebar", () => {
|
||||
const state = stateWithWorkspaces(
|
||||
[{ id: "ws-hidden", background: true }],
|
||||
agent({ id: "a", workspaceId: "ws-hidden", requiresAttention: true }),
|
||||
);
|
||||
expect(deriveFaviconStatus(state, { showBackground: true })).toBe("attention");
|
||||
expect(createFaviconStatusSelector({ showBackground: true })(state)).toBe("attention");
|
||||
});
|
||||
});
|
||||
|
||||
describe("createFaviconStatusSelector", () => {
|
||||
@@ -63,6 +108,18 @@ describe("createFaviconStatusSelector", () => {
|
||||
expect(select({ sessions: { ...state.sessions } })).toBe("running");
|
||||
});
|
||||
|
||||
it("rescans when a workspace map is replaced", () => {
|
||||
const select = createFaviconStatusSelector();
|
||||
const state = stateWithWorkspaces(
|
||||
[],
|
||||
agent({ id: "a", workspaceId: "ws-hidden", requiresAttention: true }),
|
||||
);
|
||||
expect(select(state)).toBe("attention");
|
||||
// The agent synced before its workspace; only the workspace map changes.
|
||||
const workspaces = new Map([["ws-hidden", { id: "ws-hidden", background: true }]]);
|
||||
expect(select({ sessions: { srv: { ...state.sessions.srv, workspaces } } })).toBe("none");
|
||||
});
|
||||
|
||||
it("rescans when an agent map is replaced", () => {
|
||||
const select = createFaviconStatusSelector();
|
||||
expect(select(stateWith(agent({ id: "a", status: "running" })))).toBe("running");
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import type { Agent } from "@/stores/session-store";
|
||||
import type { Agent, WorkspaceDescriptor } from "@/stores/session-store";
|
||||
import { memoizeOnSessionMaps } from "./memoize-on-session-maps";
|
||||
|
||||
export type FaviconStatus = "none" | "running" | "attention";
|
||||
|
||||
interface FaviconAgentSession {
|
||||
agents: ReadonlyMap<string, Agent>;
|
||||
workspaces: ReadonlyMap<string, Pick<WorkspaceDescriptor, "background">>;
|
||||
}
|
||||
|
||||
interface FaviconAgentSource {
|
||||
@@ -16,13 +17,22 @@ interface FaviconAgentSource {
|
||||
* three states here instead of building the aggregated agent list: the list allocates a
|
||||
* projection per agent, deep-compares it and sorts every agent on the host on each update.
|
||||
*/
|
||||
export function deriveFaviconStatus(state: FaviconAgentSource): FaviconStatus {
|
||||
export interface FaviconStatusOptions {
|
||||
/** Count agents in background workspaces too, as the sidebar shows them while Show background is on. */
|
||||
showBackground?: boolean;
|
||||
}
|
||||
|
||||
export function deriveFaviconStatus(
|
||||
state: FaviconAgentSource,
|
||||
options: FaviconStatusOptions = {},
|
||||
): FaviconStatus {
|
||||
let hasAttention = false;
|
||||
let hasNeedsInput = false;
|
||||
for (const session of Object.values(state.sessions)) {
|
||||
if (!session) continue;
|
||||
for (const agent of session.agents.values()) {
|
||||
if (agent.background || agent.archivedAt) continue;
|
||||
if (!options.showBackground && isInBackgroundWorkspace(agent, session)) continue;
|
||||
if (agent.status === "running") return "running";
|
||||
if (agent.requiresAttention) hasAttention = true;
|
||||
if (agent.pendingPermissions.length > 0) hasNeedsInput = true;
|
||||
@@ -31,10 +41,16 @@ export function deriveFaviconStatus(state: FaviconAgentSource): FaviconStatus {
|
||||
return hasAttention || hasNeedsInput ? "attention" : "none";
|
||||
}
|
||||
|
||||
/** A session-store selector for the favicon status that rescans only when an agent map changes. */
|
||||
export function createFaviconStatusSelector(): (state: FaviconAgentSource) => FaviconStatus {
|
||||
function isInBackgroundWorkspace(agent: Agent, session: FaviconAgentSession): boolean {
|
||||
return agent.workspaceId ? session.workspaces.get(agent.workspaceId)?.background === true : false;
|
||||
}
|
||||
|
||||
/** A session-store selector for the favicon status that rescans only when an agent or workspace map changes. */
|
||||
export function createFaviconStatusSelector(
|
||||
options: FaviconStatusOptions = {},
|
||||
): (state: FaviconAgentSource) => FaviconStatus {
|
||||
return memoizeOnSessionMaps<FaviconAgentSession, FaviconAgentSource, FaviconStatus>(
|
||||
(session) => session.agents,
|
||||
deriveFaviconStatus,
|
||||
(session) => [session.agents, session.workspaces],
|
||||
(state) => deriveFaviconStatus(state, options),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -4,18 +4,18 @@ interface SessionsSource<TSession> {
|
||||
|
||||
/**
|
||||
* Wraps a whole-store selector so it reruns only when one of the per-session maps it reads has
|
||||
* changed. Session-store writes that leave those maps alone (timeline updates, drafts) then cost
|
||||
* changed. `pickMaps` returns every map the selector reads from one session. Session-store writes that leave those maps alone (timeline updates, drafts) then cost
|
||||
* a reference check per host instead of a walk over every entry.
|
||||
*/
|
||||
export function memoizeOnSessionMaps<TSession, TState extends SessionsSource<TSession>, TResult>(
|
||||
pickMap: (session: TSession) => unknown,
|
||||
pickMaps: (session: TSession) => readonly unknown[],
|
||||
derive: (state: TState) => TResult,
|
||||
): (state: TState) => TResult {
|
||||
let previousMaps: unknown[] | null = null;
|
||||
let previousResult: TResult;
|
||||
return (state) => {
|
||||
const maps = Object.values(state.sessions).map((session) =>
|
||||
session ? pickMap(session) : undefined,
|
||||
const maps = Object.values(state.sessions).flatMap((session) =>
|
||||
session ? pickMaps(session) : [undefined],
|
||||
);
|
||||
if (
|
||||
previousMaps &&
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import path from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { buildWorkspaceSource } from "./create.js";
|
||||
|
||||
@@ -8,6 +9,49 @@ describe("workspace create source", () => {
|
||||
).toEqual({ kind: "directory", path: "/tmp/project", projectId: "project-1" });
|
||||
});
|
||||
|
||||
it("resolves a relative path against the directory the command runs in", () => {
|
||||
const daemonTarget = { kind: "instance" as const, home: "/tmp/paseo-home" };
|
||||
expect(buildWorkspaceSource({ daemonTarget, isolation: "local", path: "." })).toEqual({
|
||||
kind: "directory",
|
||||
path: process.cwd(),
|
||||
});
|
||||
expect(
|
||||
buildWorkspaceSource({ daemonTarget, isolation: "worktree", path: "../sibling" }),
|
||||
).toEqual({
|
||||
kind: "worktree",
|
||||
cwd: path.resolve(process.cwd(), "../sibling"),
|
||||
action: "branch-off",
|
||||
});
|
||||
});
|
||||
|
||||
it("sends a relative path to an explicit daemon endpoint as written", () => {
|
||||
const daemonTarget = { kind: "endpoint" as const, host: "other-box:6767" };
|
||||
expect(buildWorkspaceSource({ daemonTarget, isolation: "local", path: "repo" })).toEqual({
|
||||
kind: "directory",
|
||||
path: "repo",
|
||||
});
|
||||
});
|
||||
|
||||
it("passes an absolute path from another operating system through unchanged", () => {
|
||||
expect(buildWorkspaceSource({ isolation: "local", path: "C:\\repos\\project" })).toEqual({
|
||||
kind: "directory",
|
||||
path: "C:\\repos\\project",
|
||||
});
|
||||
});
|
||||
|
||||
it("leaves a home-relative path for the daemon to expand", () => {
|
||||
const daemonTarget = { kind: "instance" as const, home: "/tmp/paseo-home" };
|
||||
expect(buildWorkspaceSource({ daemonTarget, isolation: "local", path: "~/repo" })).toEqual({
|
||||
kind: "directory",
|
||||
path: "~/repo",
|
||||
});
|
||||
expect(buildWorkspaceSource({ daemonTarget, isolation: "worktree", path: "~" })).toEqual({
|
||||
kind: "worktree",
|
||||
cwd: "~",
|
||||
action: "branch-off",
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps branch names separate from managed worktree slugs", () => {
|
||||
expect(
|
||||
buildWorkspaceSource({
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
import { isAbsolute as isPosixAbsolute } from "node:path/posix";
|
||||
import { isAbsolute as isWindowsAbsolute } from "node:path/win32";
|
||||
import { resolve } from "node:path";
|
||||
import type { Command } from "commander";
|
||||
import { connectToDaemon, getDaemonHost } from "../../utils/client.js";
|
||||
import { resolveCallerAgentId } from "../../utils/caller-agent.js";
|
||||
import type { DaemonTarget } from "../../utils/daemon-target.js";
|
||||
import type { CommandError, CommandOptions, SingleResult } from "../../output/index.js";
|
||||
import { toWorkspaceRow, workspaceSchema, type WorkspaceRow } from "./shared.js";
|
||||
|
||||
@@ -121,12 +125,26 @@ function buildWorktreeWorkspaceSource(options: WorkspaceCreateOptions, path: str
|
||||
}
|
||||
}
|
||||
|
||||
// A relative --path names a directory relative to where the command runs, so
|
||||
// it is made absolute here for a local daemon, which would otherwise resolve
|
||||
// it against its own working directory. For an explicit endpoint the path is
|
||||
// sent as written, the same rule as resolveRepositoryDirectory. An absolute
|
||||
// path can target a daemon on a different operating system, and the daemon
|
||||
// expands a leading ~ to its own home directory.
|
||||
function resolveCallerPath(input: string, daemonTarget: DaemonTarget): string {
|
||||
const isHomeRelative = input === "~" || input.startsWith("~/");
|
||||
if (isHomeRelative || isPosixAbsolute(input) || isWindowsAbsolute(input)) return input;
|
||||
return daemonTarget.kind === "instance" ? resolve(input) : input;
|
||||
}
|
||||
|
||||
export function buildWorkspaceSource(options: WorkspaceCreateOptions) {
|
||||
const callerPath =
|
||||
options.path === undefined ? undefined : resolveCallerPath(options.path, options.daemonTarget);
|
||||
if (options.isolation === "local") {
|
||||
return buildLocalWorkspaceSource(options, options.path ?? process.cwd());
|
||||
return buildLocalWorkspaceSource(options, callerPath ?? process.cwd());
|
||||
}
|
||||
if (options.isolation === "worktree") {
|
||||
const sourcePath = options.path ?? (options.project ? undefined : process.cwd());
|
||||
const sourcePath = callerPath ?? (options.project ? undefined : process.cwd());
|
||||
return buildWorktreeWorkspaceSource(options, sourcePath);
|
||||
}
|
||||
throw new Error(`Unsupported workspace isolation: ${String(options.isolation)}`);
|
||||
|
||||
@@ -5,18 +5,25 @@ import { fileURLToPath } from "node:url";
|
||||
import { _electron as electron, expect } from "playwright/test";
|
||||
|
||||
const root = await mkdtemp(path.join(tmpdir(), "paseo-window-startup-"));
|
||||
const modulePath = fileURLToPath(new URL("../dist/window/show-when-ready.js", import.meta.url));
|
||||
const showWhenReadyPath = fileURLToPath(
|
||||
new URL("../dist/window/show-when-ready.js", import.meta.url),
|
||||
);
|
||||
const rendererRecoveryPath = fileURLToPath(
|
||||
new URL("../dist/window/renderer-recovery.js", import.meta.url),
|
||||
);
|
||||
|
||||
async function launchWindowWithoutHiddenFrames() {
|
||||
async function launchDesktopWindow() {
|
||||
const main = path.join(root, "main.cjs");
|
||||
await writeFile(
|
||||
main,
|
||||
`const { app, BrowserWindow } = require("electron");
|
||||
const { showWindowWhenReady } = require(${JSON.stringify(modulePath)});
|
||||
const { showWindowWhenReady } = require(${JSON.stringify(showWhenReadyPath)});
|
||||
const { reloadWhenRendererExits } = require(${JSON.stringify(rendererRecoveryPath)});
|
||||
app.setPath("userData", ${JSON.stringify(path.join(root, "user-data"))});
|
||||
app.whenReady().then(async () => {
|
||||
const win = global.mainWindow = new BrowserWindow({ show: false, paintWhenInitiallyHidden: false });
|
||||
showWindowWhenReady(win, { showOnLoad: true });
|
||||
reloadWhenRendererExits(win);
|
||||
await win.loadURL("data:text/html,<h1>Desktop ready</h1>");
|
||||
global.visibleAfterLoad = win.isVisible();
|
||||
});`,
|
||||
@@ -37,11 +44,32 @@ async function expectLoadedDesktopIsShown(desktop) {
|
||||
await expect(page.getByRole("heading", { name: "Desktop ready" })).toBeVisible();
|
||||
}
|
||||
|
||||
function rendererPid(desktop) {
|
||||
return desktop.evaluate(() => global.mainWindow.webContents.getOSProcessId());
|
||||
}
|
||||
|
||||
async function expectDesktopReloadsAfterRendererIsTerminated(desktop) {
|
||||
const terminated = await rendererPid(desktop);
|
||||
process.kill(terminated, "SIGTERM");
|
||||
await expect.poll(() => rendererPid(desktop), { timeout: 15_000 }).not.toBe(terminated);
|
||||
await expect
|
||||
.poll(
|
||||
() =>
|
||||
desktop.evaluate(() =>
|
||||
global.mainWindow.webContents.executeJavaScript("document.body.textContent"),
|
||||
),
|
||||
{ timeout: 15_000 },
|
||||
)
|
||||
.toBe("Desktop ready");
|
||||
}
|
||||
|
||||
let desktop;
|
||||
try {
|
||||
desktop = await launchWindowWithoutHiddenFrames();
|
||||
desktop = await launchDesktopWindow();
|
||||
await expectLoadedDesktopIsShown(desktop);
|
||||
console.log("Loaded desktop is visible without hidden compositor frames");
|
||||
await expectDesktopReloadsAfterRendererIsTerminated(desktop);
|
||||
console.log("Desktop reloads its window after the renderer is terminated");
|
||||
} finally {
|
||||
await desktop?.close();
|
||||
await rm(root, { recursive: true, force: true });
|
||||
|
||||
@@ -4,6 +4,8 @@ import { adaptWebContents, HostSnapshotEngineRegistry } from "./ipc.js";
|
||||
import type { IsolatedKeyboardInputEvent } from "./trusted-input.js";
|
||||
|
||||
class FakeImage implements TabImage {
|
||||
public constructor(private readonly alpha = 255) {}
|
||||
|
||||
public toPNG(): Uint8Array {
|
||||
return new Uint8Array([137, 80, 78, 71]);
|
||||
}
|
||||
@@ -11,6 +13,10 @@ class FakeImage implements TabImage {
|
||||
public getSize(): { width: number; height: number } {
|
||||
return { width: 640, height: 480 };
|
||||
}
|
||||
|
||||
public toBitmap(): Uint8Array {
|
||||
return new Uint8Array([0, 0, 0, 0, 10, 20, 30, this.alpha]);
|
||||
}
|
||||
}
|
||||
|
||||
class FakeDebugger {
|
||||
@@ -268,6 +274,24 @@ describe("browser automation IPC adapter", () => {
|
||||
expect(contents.endedFrameSubscriptions).toBe(1);
|
||||
});
|
||||
|
||||
test("skips frames with no painted pixels and captures the first painted frame", async () => {
|
||||
const contents = new FakeWebContents(2004);
|
||||
const tab = adaptWebContents(contents);
|
||||
const controller = new AbortController();
|
||||
const capture = tab.captureFrame(controller.signal);
|
||||
const unpainted = new FakeImage(0);
|
||||
const painted = new FakeImage(255);
|
||||
|
||||
contents.frameListener?.(unpainted);
|
||||
expect(contents.frameListener).not.toBeNull();
|
||||
contents.frameListener?.(painted);
|
||||
|
||||
expect(await capture).toBe(painted);
|
||||
expect(contents.frameListener).toBeNull();
|
||||
controller.abort();
|
||||
expect(contents.endedFrameSubscriptions).toBe(1);
|
||||
});
|
||||
|
||||
test("cancels a pending frame subscription when the capture budget expires", async () => {
|
||||
const contents = new FakeWebContents(2001);
|
||||
const tab = adaptWebContents(contents);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { ipcMain } from "electron";
|
||||
import { ipcMain, nativeImage } from "electron";
|
||||
import { BrowserAutomationExecuteRequestSchema } from "@getpaseo/protocol/browser-automation/rpc-schemas";
|
||||
import type {
|
||||
BrowserAutomationConsoleLogEntry,
|
||||
@@ -15,7 +15,7 @@ import {
|
||||
promptShimInstallScript,
|
||||
promptShimRestoreScript,
|
||||
} from "./dialog-handling.js";
|
||||
import { BrowserTabClosedError, executeAutomationCommand } from "./service.js";
|
||||
import { BrowserTabClosedError, executeAutomationCommand, hasPaintedPixels } from "./service.js";
|
||||
import { BrowserSnapshotEngine } from "./snapshot-engine.js";
|
||||
import {
|
||||
listRegisteredPaseoBrowserIds,
|
||||
@@ -133,6 +133,7 @@ export function adaptWebContents(contents: BrowserAutomationWebContents): TabCon
|
||||
goForward: () => contents.goForward(),
|
||||
reload: () => contents.reload(),
|
||||
captureFrame: (signal) => captureViewportFrame(contents, signal),
|
||||
decodePng: (png) => nativeImage.createFromBuffer(Buffer.from(png)),
|
||||
invalidate: () => contents.invalidate(),
|
||||
withFrameProduction: async (capture) => {
|
||||
const previous = contents.getBackgroundThrottling();
|
||||
@@ -182,6 +183,9 @@ function captureViewportFrame(
|
||||
// A resized resident guest can paint while capturePage's surface-copy
|
||||
// request remains pending. Subscribe to its rendered frames instead.
|
||||
contents.beginFrameSubscription(false, (image) => {
|
||||
// Keep the subscription open until the page has painted; the capture
|
||||
// budget turns a page that never paints into screenshot_no_frame.
|
||||
if (!hasPaintedPixels(image)) return;
|
||||
stop();
|
||||
resolve(image);
|
||||
});
|
||||
|
||||
@@ -22,6 +22,7 @@ class FakeImage implements TabImage {
|
||||
public constructor(
|
||||
private readonly bytes = new Uint8Array([137, 80, 78, 71, 1, 2, 3]),
|
||||
private readonly size = { width: 640, height: 480 },
|
||||
private readonly alpha = 255,
|
||||
) {}
|
||||
|
||||
public toPNG(): Uint8Array {
|
||||
@@ -31,8 +32,14 @@ class FakeImage implements TabImage {
|
||||
public getSize(): { width: number; height: number } {
|
||||
return this.size;
|
||||
}
|
||||
|
||||
public toBitmap(): Uint8Array {
|
||||
return new Uint8Array([0, 0, 0, 0, 10, 20, 30, this.alpha]);
|
||||
}
|
||||
}
|
||||
|
||||
const UNPAINTED_FULL_PAGE_PNG = "unpaintedPng";
|
||||
|
||||
class FakeTab implements TabContents {
|
||||
public withFrameProduction<T>(capture: () => Promise<T>): Promise<T> {
|
||||
return capture();
|
||||
@@ -77,6 +84,7 @@ class FakeTab implements TabContents {
|
||||
public fullPageScreenshotThrows = false;
|
||||
public fullPageScreenshotErrorMessage = "UnknownVizError";
|
||||
public fullPageCaptureFailuresBeforeSuccess = 0;
|
||||
public fullPageUnpaintedCapturesBeforePainted = 0;
|
||||
public layoutMetrics = {
|
||||
cssLayoutViewport: { clientWidth: 390, clientHeight: 844 },
|
||||
cssContentSize: { width: 390, height: 1200 },
|
||||
@@ -191,6 +199,11 @@ class FakeTab implements TabContents {
|
||||
this.actions.push("invalidate");
|
||||
}
|
||||
|
||||
public decodePng(png: Uint8Array): TabImage {
|
||||
const unpainted = Buffer.from(png).equals(Buffer.from(UNPAINTED_FULL_PAGE_PNG, "base64"));
|
||||
return new FakeImage(png, { width: 390, height: 1200 }, unpainted ? 0 : 255);
|
||||
}
|
||||
|
||||
public getConsoleMessages(): BrowserAutomationConsoleLogEntry[] {
|
||||
return this.consoleMessages;
|
||||
}
|
||||
@@ -218,6 +231,10 @@ class FakeTab implements TabContents {
|
||||
if (this.fullPageScreenshotThrows) {
|
||||
throw new Error(this.fullPageScreenshotErrorMessage);
|
||||
}
|
||||
if (this.fullPageUnpaintedCapturesBeforePainted > 0) {
|
||||
this.fullPageUnpaintedCapturesBeforePainted -= 1;
|
||||
return { data: UNPAINTED_FULL_PAGE_PNG };
|
||||
}
|
||||
return { data: this.fullPageScreenshotData };
|
||||
}
|
||||
if (command === "Runtime.evaluate") {
|
||||
@@ -2035,6 +2052,56 @@ describe("executeAutomationCommand", () => {
|
||||
}
|
||||
});
|
||||
|
||||
test("screenshot with fullPage waits for a CDP image with painted pixels", async () => {
|
||||
vi.useFakeTimers();
|
||||
try {
|
||||
const browser = new BrowserAutomationHarness();
|
||||
browser.tab.fullPageUnpaintedCapturesBeforePainted = 1;
|
||||
|
||||
const resultPromise = browser.execute({
|
||||
command: "screenshot",
|
||||
args: { browserId: BROWSER_A, fullPage: true },
|
||||
});
|
||||
await vi.advanceTimersByTimeAsync(200);
|
||||
|
||||
await expect(resultPromise).resolves.toMatchObject({
|
||||
ok: true,
|
||||
result: { command: "screenshot", dataBase64: "fullPagePng" },
|
||||
});
|
||||
expect(
|
||||
browser.tab.debugCommands.filter((entry) => entry.command === "Page.captureScreenshot"),
|
||||
).toHaveLength(2);
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
test("screenshot with fullPage returns no-frame when the page never paints", async () => {
|
||||
vi.useFakeTimers();
|
||||
try {
|
||||
const browser = new BrowserAutomationHarness();
|
||||
browser.tab.fullPageUnpaintedCapturesBeforePainted = Number.POSITIVE_INFINITY;
|
||||
|
||||
const resultPromise = browser.execute({
|
||||
command: "screenshot",
|
||||
args: { browserId: BROWSER_A, fullPage: true },
|
||||
});
|
||||
await vi.advanceTimersByTimeAsync(5_000);
|
||||
|
||||
await expect(resultPromise).resolves.toEqual({
|
||||
requestId: "req-screenshot",
|
||||
ok: false,
|
||||
error: {
|
||||
code: "screenshot_no_frame",
|
||||
message: "The tab has not painted yet. Retry the screenshot.",
|
||||
retryable: true,
|
||||
},
|
||||
});
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
test("screenshot with fullPage surfaces ordinary CDP capture errors", async () => {
|
||||
const browser = new BrowserAutomationHarness();
|
||||
browser.tab.fullPageScreenshotThrows = true;
|
||||
|
||||
@@ -36,6 +36,7 @@ export interface TabContents {
|
||||
goForward(): void;
|
||||
reload(): void;
|
||||
captureFrame(signal: AbortSignal): Promise<TabImage>;
|
||||
decodePng(png: Uint8Array): TabImage;
|
||||
invalidate(): void;
|
||||
withFrameProduction<T>(capture: () => Promise<T>): Promise<T>;
|
||||
sendInputEvent(event: IsolatedKeyboardInputEvent): void;
|
||||
@@ -52,6 +53,22 @@ export interface TabContents {
|
||||
export interface TabImage {
|
||||
toPNG(): Uint8Array;
|
||||
getSize(): { width: number; height: number };
|
||||
// Raw 32-bit pixels. Alpha is the fourth byte of each pixel in BGRA and RGBA order alike.
|
||||
toBitmap(): Uint8Array;
|
||||
}
|
||||
|
||||
// Electron guest pages have a transparent base background, so a page that has
|
||||
// painted nothing yet (for example a dev server hiding body until its JS boots)
|
||||
// yields a frame where every pixel is transparent. That frame is not a
|
||||
// screenshot of the page.
|
||||
export function hasPaintedPixels(image: TabImage): boolean {
|
||||
const bitmap = image.toBitmap();
|
||||
for (let alpha = 3; alpha < bitmap.length; alpha += 4) {
|
||||
if (bitmap[alpha] !== 0) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
export interface BrowserRegistry {
|
||||
@@ -1348,11 +1365,18 @@ async function executeFullPageScreenshot(
|
||||
const metrics = await getCdpLayoutMetrics(target.contents);
|
||||
width = metrics.contentWidth;
|
||||
height = metrics.contentHeight;
|
||||
return (await sendDebugCommand("Page.captureScreenshot", {
|
||||
const result = (await sendDebugCommand("Page.captureScreenshot", {
|
||||
format: "png",
|
||||
captureBeyondViewport: true,
|
||||
clip: { x: 0, y: 0, width, height, scale: 1 },
|
||||
})) as CdpCaptureScreenshotResult;
|
||||
if (
|
||||
result.data &&
|
||||
!hasPaintedPixels(target.contents.decodePng(Buffer.from(result.data, "base64")))
|
||||
) {
|
||||
throw new Error("Page.captureScreenshot returned no painted frame");
|
||||
}
|
||||
return result;
|
||||
});
|
||||
} catch (error) {
|
||||
if (isScreenshotNoFrameError(error)) {
|
||||
|
||||
@@ -46,6 +46,7 @@ import {
|
||||
buildStandardContextMenuItems,
|
||||
} from "./window/window-manager.js";
|
||||
import { setupDarwinCompositorWatchdog } from "./window/compositor-watchdog/index.js";
|
||||
import { reloadWhenRendererExits } from "./window/renderer-recovery.js";
|
||||
import { showWindowWhenReady } from "./window/show-when-ready.js";
|
||||
import { resolveDesktopWindowChromeMode, windowChromeModeArgument } from "./window/chrome.js";
|
||||
import { registerDialogHandlers } from "./features/dialogs.js";
|
||||
@@ -734,6 +735,7 @@ async function createWindow(
|
||||
}
|
||||
|
||||
setupDarwinCompositorWatchdog(mainWindow);
|
||||
reloadWhenRendererExits(mainWindow);
|
||||
setupWindowResizeEvents(mainWindow);
|
||||
if (windowStateStore) {
|
||||
setupWindowStatePersistence(mainWindow, windowStateStore);
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
import { EventEmitter } from "node:events";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { reloadWhenRendererExits } from "./renderer-recovery.js";
|
||||
|
||||
class Contents extends EventEmitter {
|
||||
reloads = 0;
|
||||
url = "paseo://app/";
|
||||
getURL() {
|
||||
return this.url;
|
||||
}
|
||||
reload() {
|
||||
this.reloads += 1;
|
||||
}
|
||||
exit(reason: string) {
|
||||
this.emit("render-process-gone", {}, { reason, exitCode: reason === "clean-exit" ? 0 : 15 });
|
||||
}
|
||||
}
|
||||
|
||||
class Window {
|
||||
webContents = new Contents();
|
||||
destroyed = false;
|
||||
isDestroyed() {
|
||||
return this.destroyed;
|
||||
}
|
||||
}
|
||||
|
||||
function recoverableWindow() {
|
||||
const win = new Window();
|
||||
let time = 0;
|
||||
reloadWhenRendererExits(win, { now: () => time });
|
||||
return {
|
||||
win,
|
||||
advance(ms: number) {
|
||||
time += ms;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe("reloadWhenRendererExits", () => {
|
||||
it("reloads the window when its renderer is killed", () => {
|
||||
const { win } = recoverableWindow();
|
||||
win.webContents.exit("killed");
|
||||
expect(win.webContents.reloads).toBe(1);
|
||||
});
|
||||
|
||||
it("reloads after a renderer crash or out-of-memory exit", () => {
|
||||
const { win, advance } = recoverableWindow();
|
||||
win.webContents.exit("crashed");
|
||||
advance(120_000);
|
||||
win.webContents.exit("oom");
|
||||
expect(win.webContents.reloads).toBe(2);
|
||||
});
|
||||
|
||||
it("leaves a renderer that exited cleanly alone", () => {
|
||||
const { win } = recoverableWindow();
|
||||
win.webContents.exit("clean-exit");
|
||||
expect(win.webContents.reloads).toBe(0);
|
||||
});
|
||||
|
||||
it("leaves a renderer that exits before the first page commits to Chromium", () => {
|
||||
const { win } = recoverableWindow();
|
||||
win.webContents.url = "";
|
||||
win.webContents.exit("killed");
|
||||
expect(win.webContents.reloads).toBe(0);
|
||||
});
|
||||
|
||||
it("leaves a closed window closed", () => {
|
||||
const { win } = recoverableWindow();
|
||||
win.destroyed = true;
|
||||
win.webContents.exit("killed");
|
||||
expect(win.webContents.reloads).toBe(0);
|
||||
});
|
||||
|
||||
it("stops reloading a renderer that keeps exiting, and recovers again later", () => {
|
||||
const { win, advance } = recoverableWindow();
|
||||
for (let exit = 0; exit < 5; exit += 1) {
|
||||
win.webContents.exit("crashed");
|
||||
advance(1_000);
|
||||
}
|
||||
expect(win.webContents.reloads).toBe(3);
|
||||
|
||||
advance(60_000);
|
||||
win.webContents.exit("killed");
|
||||
expect(win.webContents.reloads).toBe(4);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,56 @@
|
||||
import log from "electron-log/main";
|
||||
|
||||
// A window whose renderer exits keeps its frame but shows nothing until it is
|
||||
// reloaded. Reload it, but stop when the renderer keeps exiting so a page that
|
||||
// crashes on load does not restart in a loop.
|
||||
const MAX_RELOADS_PER_WINDOW = 3;
|
||||
const RELOAD_WINDOW_MS = 60_000;
|
||||
|
||||
interface RendererExit {
|
||||
reason: string;
|
||||
exitCode: number;
|
||||
}
|
||||
|
||||
interface RecoverableWindow {
|
||||
isDestroyed(): boolean;
|
||||
webContents: {
|
||||
on(
|
||||
event: "render-process-gone",
|
||||
listener: (event: unknown, details: RendererExit) => void,
|
||||
): unknown;
|
||||
getURL(): string;
|
||||
reload(): void;
|
||||
};
|
||||
}
|
||||
|
||||
export function reloadWhenRendererExits(
|
||||
win: RecoverableWindow,
|
||||
options: { now?: () => number } = {},
|
||||
): void {
|
||||
const now = options.now ?? Date.now;
|
||||
let reloadTimes: number[] = [];
|
||||
|
||||
win.webContents.on("render-process-gone", (_event, details) => {
|
||||
if (details.reason === "clean-exit" || win.isDestroyed()) return;
|
||||
// Before the first page commits, Chromium finishes the navigation in a new
|
||||
// renderer by itself. Reloading then would abort the window's initial load.
|
||||
if (win.webContents.getURL() === "") return;
|
||||
|
||||
const time = now();
|
||||
reloadTimes = reloadTimes.filter((reloadTime) => time - reloadTime < RELOAD_WINDOW_MS);
|
||||
if (reloadTimes.length >= MAX_RELOADS_PER_WINDOW) {
|
||||
log.error(
|
||||
`[renderer-recovery] Renderer exited (${details.reason}, code ${details.exitCode}); ` +
|
||||
`not reloading after ${reloadTimes.length} reloads in the last minute`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
reloadTimes.push(time);
|
||||
log.warn(
|
||||
`[renderer-recovery] Renderer exited (${details.reason}, code ${details.exitCode}); ` +
|
||||
`reloading the window (reload ${reloadTimes.length} in the last minute)`,
|
||||
);
|
||||
win.webContents.reload();
|
||||
});
|
||||
}
|
||||
@@ -47,6 +47,9 @@ export const PaseoWorktreeConfigRawSchema = z
|
||||
.object({
|
||||
setup: PaseoLifecycleCommandRawSchema.optional(),
|
||||
teardown: PaseoLifecycleCommandRawSchema.optional(),
|
||||
// Checked by WorktreeConfigSchema, where an invalid value falls back to the default, so it
|
||||
// never stops paseo.json from being edited or sent to the app.
|
||||
teardownTimeoutMs: z.unknown().optional(),
|
||||
terminals: z.unknown().optional(),
|
||||
servicePorts: PaseoServicePortAllocationSchema.optional(),
|
||||
})
|
||||
@@ -79,9 +82,20 @@ export const PaseoConfigRawSchema = z
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
// Node timers can't wait longer than this; a longer delay fires at once.
|
||||
const MAX_TIMER_DELAY_MS = 2_147_483_647;
|
||||
|
||||
export const WorktreeConfigSchema = PaseoWorktreeConfigRawSchema.extend({
|
||||
setup: z.unknown().optional().transform(normalizeLifecycleCommands),
|
||||
teardown: z.unknown().optional().transform(normalizeLifecycleCommands),
|
||||
// Its own catch, so an invalid limit doesn't drop the commands with the rest of the worktree.
|
||||
teardownTimeoutMs: z
|
||||
.number()
|
||||
.int()
|
||||
.positive()
|
||||
.max(MAX_TIMER_DELAY_MS)
|
||||
.optional()
|
||||
.catch(undefined),
|
||||
})
|
||||
.passthrough()
|
||||
.catch({ setup: [], teardown: [] });
|
||||
|
||||
@@ -3473,6 +3473,101 @@ test("cancelAgentRun succeeds when the provider queues completion before rejecti
|
||||
}
|
||||
});
|
||||
|
||||
test.each([
|
||||
{ binding: "foreground", agentId: "00000000-0000-4000-8000-000000000307" },
|
||||
{ binding: "autonomous", agentId: "00000000-0000-4000-8000-000000000308" },
|
||||
] as const)(
|
||||
"cancelAgentRun settles a $binding run bound to an already finalized turn",
|
||||
async ({ binding, agentId }) => {
|
||||
const fixture = await createControlledInterruptFixture({
|
||||
name: `interrupt-finalized-${binding}`,
|
||||
agentId,
|
||||
turnId: "finalized-turn",
|
||||
interrupt: async () => {},
|
||||
});
|
||||
|
||||
try {
|
||||
await fixture.startForegroundRun();
|
||||
await expect(fixture.manager.cancelAgentRun(fixture.agentId)).resolves.toEqual({
|
||||
status: "settled",
|
||||
});
|
||||
|
||||
if (binding === "foreground") {
|
||||
await fixture.startForegroundRun();
|
||||
} else {
|
||||
const running = waitForAgentLifecycle(fixture.manager, fixture.agentId, "running");
|
||||
fixture.session.pushEvent({
|
||||
type: "turn_started",
|
||||
provider: "codex",
|
||||
turnId: "finalized-turn",
|
||||
});
|
||||
await running;
|
||||
}
|
||||
|
||||
const cancellation = await Promise.race([
|
||||
fixture.manager.cancelAgentRun(fixture.agentId),
|
||||
new Promise<"pending">((resolve) => setTimeout(() => resolve("pending"), 3_000)),
|
||||
]);
|
||||
expect(cancellation).toEqual({ status: "settled" });
|
||||
expect(fixture.manager.getAgent(fixture.agentId)).toMatchObject({
|
||||
lifecycle: "idle",
|
||||
activeForegroundTurnId: null,
|
||||
});
|
||||
|
||||
await expect(fixture.manager.cancelAgentRun(fixture.agentId)).resolves.toEqual({
|
||||
status: "not_running",
|
||||
});
|
||||
await fixture.startForegroundRun();
|
||||
expect(fixture.manager.getAgent(fixture.agentId)).toMatchObject({
|
||||
lifecycle: "running",
|
||||
activeForegroundTurnId: "finalized-turn",
|
||||
});
|
||||
} finally {
|
||||
await fixture.cleanup();
|
||||
}
|
||||
},
|
||||
10_000,
|
||||
);
|
||||
|
||||
test("the provider's terminal for a run bound to an already finalized turn settles the run", async () => {
|
||||
const fixture = await createControlledInterruptFixture({
|
||||
name: "interrupt-finalized-provider-terminal",
|
||||
agentId: "00000000-0000-4000-8000-000000000309",
|
||||
turnId: "finalized-provider-terminal-turn",
|
||||
interrupt: async () => {},
|
||||
});
|
||||
|
||||
try {
|
||||
await fixture.startForegroundRun();
|
||||
await expect(fixture.manager.cancelAgentRun(fixture.agentId)).resolves.toEqual({
|
||||
status: "settled",
|
||||
});
|
||||
|
||||
await fixture.startForegroundRun();
|
||||
const idle = waitForAgentLifecycle(fixture.manager, fixture.agentId, "idle");
|
||||
fixture.session.pushEvent({
|
||||
type: "turn_completed",
|
||||
provider: "codex",
|
||||
turnId: "finalized-provider-terminal-turn",
|
||||
});
|
||||
const settlement = await Promise.race([
|
||||
idle.then(() => "idle" as const),
|
||||
new Promise<"pending">((resolve) => setTimeout(() => resolve("pending"), 1_000)),
|
||||
]);
|
||||
|
||||
expect(settlement).toBe("idle");
|
||||
expect(fixture.manager.getAgent(fixture.agentId)).toMatchObject({
|
||||
lifecycle: "idle",
|
||||
activeForegroundTurnId: null,
|
||||
});
|
||||
await expect(fixture.manager.cancelAgentRun(fixture.agentId)).resolves.toEqual({
|
||||
status: "not_running",
|
||||
});
|
||||
} finally {
|
||||
await fixture.cleanup();
|
||||
}
|
||||
}, 10_000);
|
||||
|
||||
test("listProviderAvailability uses registered client keys, including custom providers", async () => {
|
||||
const customClient: AgentClient = {
|
||||
provider: "zai",
|
||||
|
||||
@@ -5132,7 +5132,8 @@ export class AgentManager {
|
||||
if (
|
||||
eventTurnId &&
|
||||
isTurnTerminalEvent(event) &&
|
||||
this.runs.hasFinalizedTurn(agent, eventTurnId)
|
||||
this.runs.hasFinalizedTurn(agent, eventTurnId) &&
|
||||
this.runs.getTurnId(agent.id) !== eventTurnId
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -266,6 +266,7 @@ function buildAgentManagerSpies() {
|
||||
archiveAgent: vi.fn().mockResolvedValue({ archivedAt: new Date().toISOString() }),
|
||||
notifyAgentState: vi.fn(),
|
||||
getAgent: vi.fn(),
|
||||
getAgentBackgroundWorkSummary: vi.fn().mockReturnValue(undefined),
|
||||
listAgents: vi.fn().mockReturnValue([]),
|
||||
getTimeline: vi.fn().mockReturnValue([]),
|
||||
resumeAgentFromPersistence: vi.fn(),
|
||||
@@ -6196,6 +6197,36 @@ describe("agent snapshot MCP serialization", () => {
|
||||
expect(structured.agents[0]).not.toHaveProperty("pendingPermissions");
|
||||
});
|
||||
|
||||
it("reports an idle agent's background work from get_agent_status and list_agents", async () => {
|
||||
const { agentManager, agentStorage, spies } = createTestDeps();
|
||||
const agent = createManagedAgent({ id: "agent-with-shell", cwd: REPO_CWD });
|
||||
spies.agentManager.getAgent.mockReturnValue(agent);
|
||||
spies.agentManager.listAgents.mockReturnValue([agent]);
|
||||
spies.agentManager.getAgentBackgroundWorkSummary.mockReturnValue({ count: 1 });
|
||||
|
||||
const server = await createAgentMcpServer({
|
||||
agentManager,
|
||||
agentStorage,
|
||||
providerSnapshotManager: createOpenCodeManager().manager,
|
||||
logger,
|
||||
});
|
||||
const status = await registeredTool(server, "get_agent_status").handler({
|
||||
agentId: "agent-with-shell",
|
||||
});
|
||||
const list = await registeredTool(server, "list_agents").handler({});
|
||||
|
||||
expect(status.structuredContent).toEqual({
|
||||
status: "idle",
|
||||
snapshot: expect.objectContaining({ status: "idle", backgroundWork: { count: 1 } }),
|
||||
});
|
||||
expect(list.structuredContent).toEqual({
|
||||
agents: [expect.objectContaining({ status: "idle", backgroundWork: { count: 1 } })],
|
||||
});
|
||||
expect(spies.agentManager.getAgentBackgroundWorkSummary).toHaveBeenCalledWith(
|
||||
"agent-with-shell",
|
||||
);
|
||||
});
|
||||
|
||||
it("returns archived agent snapshots from storage for get_agent_status", async () => {
|
||||
const { agentManager, agentStorage, spies } = createTestDeps();
|
||||
const record = createStoredRecord({
|
||||
|
||||
@@ -123,7 +123,8 @@ test.each(["mode", "model", "commands"] as const)(
|
||||
try {
|
||||
await session.startTurn("Run the foreground command");
|
||||
await running.promise;
|
||||
expect(await session.setThinkingOption?.("medium")).toMatchObject({
|
||||
// Ultracode is launched with the query, so the change waits for a restart.
|
||||
expect(await session.setThinkingOption?.("ultracode")).toMatchObject({
|
||||
message: "Thinking level applies next turn",
|
||||
});
|
||||
if (control === "mode") await session.setMode("acceptEdits");
|
||||
@@ -149,7 +150,7 @@ test.each(["mode", "model", "commands"] as const)(
|
||||
await session.startTurn("Run another command with the new thinking level");
|
||||
queries[1].work.resolve();
|
||||
expect(await terminal.promise).toBe("turn_completed");
|
||||
expect(efforts).toEqual(["low", "medium"]);
|
||||
expect(efforts).toEqual(["low", "xhigh"]);
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
|
||||
@@ -44,6 +44,7 @@ function createQueryMock(events: unknown[], options: QueryMockOptions = {}): Que
|
||||
close: vi.fn(() => undefined),
|
||||
setPermissionMode: vi.fn(async () => undefined),
|
||||
setModel: vi.fn(async () => undefined),
|
||||
applyFlagSettings: vi.fn(async () => undefined),
|
||||
supportedModels: vi.fn(async () => [{ value: "opus", displayName: "Opus" }]),
|
||||
supportedCommands: vi.fn(async () => []),
|
||||
rewindFiles: vi.fn(async () => ({ canRewind: true })),
|
||||
@@ -382,6 +383,84 @@ describe("Claude runtime exit", () => {
|
||||
}
|
||||
});
|
||||
|
||||
test("keeps the process and its background work when the effort level changes", async () => {
|
||||
let capturedOptions: Options | undefined;
|
||||
const child = createChildProcessStub();
|
||||
const query = createQueryMock(BACKGROUND_SHELL_TURN_EVENTS, {
|
||||
tail: new Promise<never>(() => undefined),
|
||||
onReturn: () => child.emit("exit", 0, null),
|
||||
});
|
||||
const queryFactory = vi.fn(({ options }: ClaudeQueryInput) => {
|
||||
capturedOptions = options;
|
||||
return query;
|
||||
});
|
||||
vi.spyOn(spawnUtils, "spawnProcess").mockReturnValue(child);
|
||||
const client = new ClaudeAgentClient({
|
||||
logger: createTestLogger(),
|
||||
queryFactory,
|
||||
resolveBinary: async () => "/test/claude/bin",
|
||||
});
|
||||
const session = await client.createSession({
|
||||
provider: "claude",
|
||||
cwd: process.cwd(),
|
||||
thinkingOptionId: "low",
|
||||
});
|
||||
|
||||
try {
|
||||
await session.run("start a background shell");
|
||||
capturedOptions?.spawnClaudeCodeProcess?.(SPAWN_OPTIONS);
|
||||
const events: AgentStreamEvent[] = [];
|
||||
session.subscribe((event) => events.push(event));
|
||||
|
||||
await expect(session.setThinkingOption?.("high")).resolves.toBeUndefined();
|
||||
// A pending restart would be carried out here.
|
||||
await session.listCommands();
|
||||
|
||||
expect(query.applyFlagSettings).toHaveBeenCalledWith({ effortLevel: "high" });
|
||||
expect(queryFactory).toHaveBeenCalledTimes(1);
|
||||
expect(query.return).not.toHaveBeenCalled();
|
||||
expect(child.killSignals).toEqual([]);
|
||||
expect(events).not.toContainEqual(
|
||||
expect.objectContaining({ type: "background_work", provider: "claude", items: null }),
|
||||
);
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("restarts with the new effort level when the running process does not take it", async () => {
|
||||
const efforts: Options["effort"][] = [];
|
||||
const queryFactory = vi.fn(({ options }: ClaudeQueryInput) => {
|
||||
efforts.push(options.effort);
|
||||
const query = createQueryMock(BACKGROUND_SHELL_TURN_EVENTS, {
|
||||
tail: new Promise<never>(() => undefined),
|
||||
});
|
||||
vi.mocked(query.applyFlagSettings).mockRejectedValue(new Error("unsupported"));
|
||||
return query;
|
||||
});
|
||||
vi.spyOn(spawnUtils, "spawnProcess").mockReturnValue(createChildProcessStub());
|
||||
const client = new ClaudeAgentClient({
|
||||
logger: createTestLogger(),
|
||||
queryFactory,
|
||||
resolveBinary: async () => "/test/claude/bin",
|
||||
});
|
||||
const session = await client.createSession({
|
||||
provider: "claude",
|
||||
cwd: process.cwd(),
|
||||
thinkingOptionId: "low",
|
||||
});
|
||||
|
||||
try {
|
||||
await session.run("start a background shell");
|
||||
await session.setThinkingOption?.("high");
|
||||
await session.listCommands();
|
||||
|
||||
expect(efforts).toEqual(["low", "high"]);
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("ignores background work a retired query reports after its restart", async () => {
|
||||
let capturedOptions: Options | undefined;
|
||||
let deliverLateEvent: ((event: unknown) => void) | undefined;
|
||||
|
||||
@@ -1544,6 +1544,60 @@ describe("ClaudeAgentSession features", () => {
|
||||
}
|
||||
});
|
||||
|
||||
test("accepts a steer while Claude compacts, so the compaction is not interrupted", async () => {
|
||||
const { queryFactory, push } = createStreamingQueryMock();
|
||||
const client = new ClaudeAgentClient({
|
||||
logger,
|
||||
queryFactory,
|
||||
resolveBinary: async () => "/test/claude/bin",
|
||||
});
|
||||
const session = await client.createSession({ provider: "claude", cwd: process.cwd() });
|
||||
const events: AgentStreamEvent[] = [];
|
||||
const unsubscribe = session.subscribe((event) => events.push(event));
|
||||
try {
|
||||
const { turnId } = await session.startTurn("/compact");
|
||||
const input = queryFactory.mock.calls[0]?.[0].prompt as AsyncIterable<SDKUserMessage>;
|
||||
const iterator = input[Symbol.asyncIterator]();
|
||||
await expect(iterator.next()).resolves.toMatchObject({ value: { type: "user" } });
|
||||
await vi.waitFor(() =>
|
||||
expect(events).toContainEqual(
|
||||
expect.objectContaining({
|
||||
type: "timeline",
|
||||
item: expect.objectContaining({ type: "user_message" }),
|
||||
}),
|
||||
),
|
||||
);
|
||||
push({
|
||||
type: "system",
|
||||
subtype: "status",
|
||||
status: "compacting",
|
||||
session_id: "session-1",
|
||||
} as unknown as SDKMessage);
|
||||
await vi.waitFor(() =>
|
||||
expect(events).toContainEqual(
|
||||
expect.objectContaining({
|
||||
type: "timeline",
|
||||
item: { type: "compaction", status: "loading" },
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const admission = await session.steerActiveTurn?.("message during compaction", {
|
||||
expectedTurnId: turnId,
|
||||
});
|
||||
|
||||
// Claude Code holds a `next` message until the compaction finishes. Refusing it makes the
|
||||
// manager replace the turn, and the interrupt cancels the compaction.
|
||||
expect(admission).toEqual({ status: "accepted", providerMessageId: expect.any(String) });
|
||||
await expect(iterator.next()).resolves.toMatchObject({
|
||||
value: { type: "user", priority: "next" },
|
||||
});
|
||||
} finally {
|
||||
unsubscribe();
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("a human steer supersedes blocking permissions until Claude reads it", async () => {
|
||||
const { queryFactory } = createQueryMock();
|
||||
const client = new ClaudeAgentClient({
|
||||
|
||||
@@ -2637,7 +2637,10 @@ class ClaudeAgentSession implements AgentSession {
|
||||
return { status: "unavailable" };
|
||||
}
|
||||
const activeTurnId = this.activeForegroundTurnId ?? this.autonomousTurn?.id;
|
||||
if (this.compacting || activeTurnId !== options.expectedTurnId) {
|
||||
// A compacting turn still takes a steer: Claude Code holds a `next` message until the
|
||||
// compaction finishes. Refusing it makes the manager replace the turn, and that interrupt
|
||||
// cancels the compaction.
|
||||
if (activeTurnId !== options.expectedTurnId) {
|
||||
return { status: "unavailable" };
|
||||
}
|
||||
|
||||
@@ -2859,6 +2862,7 @@ class ClaudeAgentSession implements AgentSession {
|
||||
? thinkingOptionId
|
||||
: null;
|
||||
|
||||
const previousThinkingOptionId = this.config.thinkingOptionId;
|
||||
if (!normalizedThinkingOptionId || normalizedThinkingOptionId === "default") {
|
||||
this.config.thinkingOptionId = undefined;
|
||||
} else if (isClaudeThinkingOption(normalizedThinkingOptionId)) {
|
||||
@@ -2867,12 +2871,35 @@ class ClaudeAgentSession implements AgentSession {
|
||||
} else {
|
||||
throw new Error(`Unknown thinking option: ${normalizedThinkingOptionId}`);
|
||||
}
|
||||
this.queryRestartNeeded = true;
|
||||
if (!(await this.applyEffortToRunningQuery(previousThinkingOptionId))) {
|
||||
this.queryRestartNeeded = true;
|
||||
}
|
||||
if (this.activeForegroundTurnId || this.autonomousTurn) {
|
||||
return THINKING_APPLIES_NEXT_TURN_NOTICE;
|
||||
}
|
||||
}
|
||||
|
||||
// A move between two effort levels changes only the effort, which a running Claude process
|
||||
// takes through flag settings, so the process and its background work stay. Switching thinking
|
||||
// off, to ultracode or back to the default changes how the query is launched, so it still
|
||||
// restarts the query. The recorded option feeds every later launch either way.
|
||||
private async applyEffortToRunningQuery(
|
||||
previousThinkingOptionId: string | undefined,
|
||||
): Promise<boolean> {
|
||||
const effort = this.config.thinkingOptionId;
|
||||
if (!this.query || this.queryRestartNeeded) return false;
|
||||
if (!isClaudeThinkingEffort(previousThinkingOptionId) || !isClaudeThinkingEffort(effort)) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
await this.query.applyFlagSettings({ effortLevel: effort });
|
||||
return true;
|
||||
} catch (error) {
|
||||
this.logger.warn({ err: error, effort }, "Claude did not take a live effort change");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async applyOptions(options: ProviderOptions): Promise<void> {
|
||||
// Every option but Fast is read when the query is built, and replacing a started query would
|
||||
// end its background work, so once it exists only Fast can change.
|
||||
|
||||
@@ -15,7 +15,7 @@ import { ensureValidJson } from "../../json-utils.js";
|
||||
import type { Logger } from "pino";
|
||||
|
||||
import type { AgentMode, AgentProvider, AgentSessionConfig } from "../agent-sdk-types.js";
|
||||
import type { AgentManager } from "../agent-manager.js";
|
||||
import type { AgentManager, ManagedAgent } from "../agent-manager.js";
|
||||
import { ActiveTurnBehaviorSchema, AgentProfileSchema } from "@getpaseo/protocol/messages";
|
||||
import type { DaemonConfigStore } from "../../daemon-config-store.js";
|
||||
import { featuresFromControls } from "@getpaseo/protocol/option-controls";
|
||||
@@ -2099,6 +2099,13 @@ function createToolCatalog(
|
||||
},
|
||||
);
|
||||
|
||||
// Match the WebSocket snapshot: idle agents can still own background work.
|
||||
async function projectLiveAgent(agent: ManagedAgent) {
|
||||
const snapshot = await serializeSnapshotWithMetadata(agentStorage, agent, childLogger);
|
||||
const backgroundWork = agentManager.getAgentBackgroundWorkSummary(agent.id);
|
||||
return backgroundWork ? { ...snapshot, backgroundWork } : snapshot;
|
||||
}
|
||||
|
||||
registerTool(
|
||||
"get_agent_status",
|
||||
{
|
||||
@@ -2116,11 +2123,7 @@ function createToolCatalog(
|
||||
async ({ agentId }) => {
|
||||
const snapshot = agentManager.getAgent(agentId);
|
||||
if (snapshot) {
|
||||
const structuredSnapshot = await serializeSnapshotWithMetadata(
|
||||
agentStorage,
|
||||
snapshot,
|
||||
childLogger,
|
||||
);
|
||||
const structuredSnapshot = await projectLiveAgent(snapshot);
|
||||
return {
|
||||
content: [],
|
||||
structuredContent: ensureValidJson({
|
||||
@@ -2188,8 +2191,7 @@ function createToolCatalog(
|
||||
manager: agentManager,
|
||||
storage: agentStorage,
|
||||
workspaces: options.workspaceRegistry,
|
||||
projectLive: (snapshot) =>
|
||||
serializeSnapshotWithMetadata(agentStorage, snapshot, childLogger),
|
||||
projectLive: projectLiveAgent,
|
||||
projectStored: (record) =>
|
||||
buildStoredAgentPayload(
|
||||
record,
|
||||
|
||||
+122
@@ -0,0 +1,122 @@
|
||||
import { beforeAll, beforeEach, describe, expect, test } from "vitest";
|
||||
import { mkdtempSync, rmSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import pino from "pino";
|
||||
|
||||
import { ClaudeAgentClient } from "../agent/providers/claude/agent.js";
|
||||
import { DaemonClient } from "../test-utils/daemon-client.js";
|
||||
import { createTestPaseoDaemon } from "../test-utils/paseo-daemon.js";
|
||||
import { canRunRealProvider, getRealProviderConfig } from "./real-provider-test-config.js";
|
||||
|
||||
function tmpCwd(): string {
|
||||
return mkdtempSync(path.join(tmpdir(), "daemon-real-claude-steer-compaction-"));
|
||||
}
|
||||
|
||||
type TimelineItem = Awaited<
|
||||
ReturnType<DaemonClient["fetchAgentTimeline"]>
|
||||
>["entries"][number]["item"];
|
||||
|
||||
// The steer must land while the compaction is still running, or it takes the idle path.
|
||||
function isCompacting(items: TimelineItem[]): boolean {
|
||||
const statuses = new Set(
|
||||
items.flatMap((item) => (item.type === "compaction" ? [item.status] : [])),
|
||||
);
|
||||
return statuses.has("loading") && !statuses.has("completed");
|
||||
}
|
||||
|
||||
function hasAssistantText(items: TimelineItem[], text: string): boolean {
|
||||
return items.some((item) => item.type === "assistant_message" && item.text.includes(text));
|
||||
}
|
||||
|
||||
async function timelineItems(client: DaemonClient, agentId: string): Promise<TimelineItem[]> {
|
||||
const timeline = await client.fetchAgentTimeline(agentId, {
|
||||
direction: "tail",
|
||||
limit: 200,
|
||||
});
|
||||
return timeline.entries.map((entry) => entry.item);
|
||||
}
|
||||
|
||||
async function waitForTimeline(
|
||||
client: DaemonClient,
|
||||
agentId: string,
|
||||
check: (items: TimelineItem[]) => boolean,
|
||||
timeoutMs: number,
|
||||
label: string,
|
||||
): Promise<TimelineItem[]> {
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
for (;;) {
|
||||
const items = await timelineItems(client, agentId);
|
||||
if (check(items)) return items;
|
||||
if (Date.now() > deadline) {
|
||||
throw new Error(`Timed out: ${label}: ${JSON.stringify(items.slice(-6)).slice(0, 2000)}`);
|
||||
}
|
||||
await new Promise((resolve) => setTimeout(resolve, 100));
|
||||
}
|
||||
}
|
||||
|
||||
describe("daemon E2E (real claude) - steer during compaction", () => {
|
||||
let canRun = false;
|
||||
|
||||
beforeAll(async () => {
|
||||
canRun = await canRunRealProvider("claude");
|
||||
});
|
||||
|
||||
beforeEach((context) => {
|
||||
if (!canRun) context.skip();
|
||||
});
|
||||
|
||||
test("a steered message waits for a running /compact instead of cancelling it", async () => {
|
||||
const logger = pino({ level: "silent" });
|
||||
const cwd = tmpCwd();
|
||||
const daemon = await createTestPaseoDaemon({
|
||||
agentClients: { claude: new ClaudeAgentClient({ logger }) },
|
||||
logger,
|
||||
});
|
||||
const client = new DaemonClient({
|
||||
url: `ws://127.0.0.1:${daemon.port}/ws`,
|
||||
});
|
||||
try {
|
||||
await client.connect();
|
||||
await client.fetchAgents({ subscribe: {} });
|
||||
const agent = await client.createAgent({
|
||||
cwd,
|
||||
title: "claude-steer-during-compaction",
|
||||
...getRealProviderConfig("claude"),
|
||||
});
|
||||
await client.sendAgentMessage(
|
||||
agent.id,
|
||||
`Remember this list for later and reply exactly: NOTED. ${Array.from(
|
||||
{ length: 400 },
|
||||
(_, index) => `item-${index}`,
|
||||
).join(" ")}`,
|
||||
);
|
||||
const firstFinish = await client.waitForFinish(agent.id, 120_000);
|
||||
expect(firstFinish.status, firstFinish.error).toBe("idle");
|
||||
|
||||
await client.sendAgentMessage(agent.id, "/compact");
|
||||
await waitForTimeline(client, agent.id, isCompacting, 60_000, "Claude reports compacting");
|
||||
|
||||
await client.sendAgentMessage(agent.id, "Reply exactly: AFTER_COMPACT", {
|
||||
activeTurnBehavior: "steer",
|
||||
});
|
||||
await waitForTimeline(
|
||||
client,
|
||||
agent.id,
|
||||
(items) => hasAssistantText(items, "AFTER_COMPACT"),
|
||||
180_000,
|
||||
"Claude answers the steered message",
|
||||
);
|
||||
await client.waitForFinish(agent.id, 120_000);
|
||||
const finalItems = await timelineItems(client, agent.id);
|
||||
expect(
|
||||
finalItems.filter((item) => item.type === "compaction").map((item) => item.status),
|
||||
).toContain("completed");
|
||||
expect(hasAssistantText(finalItems, "Compaction canceled")).toBe(false);
|
||||
} finally {
|
||||
await client.close().catch(() => undefined);
|
||||
await daemon.close().catch(() => undefined);
|
||||
rmSync(cwd, { recursive: true, force: true });
|
||||
}
|
||||
}, 420_000);
|
||||
});
|
||||
@@ -554,7 +554,7 @@ test("Hub resolves persisted execution ownership after daemon restart", async ()
|
||||
expect(workspaceId).toEqual(expect.any(String));
|
||||
expect(await hub.archivedWorkspaceAt(workspaceId!)).toEqual(expect.any(String));
|
||||
expect(await hub.worktreeState(worktreeCwd)).toEqual({ exists: false, listed: false });
|
||||
}, 20_000);
|
||||
}, 60_000);
|
||||
|
||||
test("Hub treats missing and foreign executions as already controlled without exposing ownership", async () => {
|
||||
const hub = await launchRelationship();
|
||||
|
||||
@@ -3,7 +3,7 @@ import type { WorktreeSource } from "../utils/worktree.js";
|
||||
|
||||
export type WorktreeCreationIntent = Exclude<
|
||||
WorktreeSource,
|
||||
{ kind: "restore" | "restore-from-base" }
|
||||
{ kind: "restore" | "restore-from-base" | "restore-commit" }
|
||||
>;
|
||||
|
||||
export interface ResolveWorktreeCreationIntentInput {
|
||||
|
||||
+177
-7
@@ -335,11 +335,15 @@ async function createBaseRecoveryFixture(baseBranch: string | null) {
|
||||
await registry.update(record.workspaceId, (value) => ({ ...value, archivedAt: null }));
|
||||
},
|
||||
});
|
||||
async function archiveAndRemove() {
|
||||
await archivePersistedWorkspaceRecord({
|
||||
workspaceId: workspace.workspaceId,
|
||||
workspaceRegistry: registry,
|
||||
});
|
||||
async function archiveAndRemove(legacy = false) {
|
||||
if (legacy) {
|
||||
await registry.archive(workspace.workspaceId, new Date().toISOString());
|
||||
} else {
|
||||
await archivePersistedWorkspaceRecord({
|
||||
workspaceId: workspace.workspaceId,
|
||||
workspaceRegistry: registry,
|
||||
});
|
||||
}
|
||||
await deletePaseoWorktree({ cwd: repoDir, worktreePath: workspace.cwd, paseoHome });
|
||||
expect(existsSync(workspace.cwd)).toBe(false);
|
||||
}
|
||||
@@ -357,6 +361,134 @@ test("preserves ordinary checkout behavior when no separate base was recorded",
|
||||
).toMatchObject({ currentBranch: "feature", baseRef: "feature" });
|
||||
});
|
||||
|
||||
test("records the full HEAD ref of an archived checkout", async () => {
|
||||
const fixture = await createBaseRecoveryFixture(null);
|
||||
await fixture.archiveAndRemove();
|
||||
expect(await fixture.registry.get(fixture.workspace.workspaceId)).toMatchObject({
|
||||
branch: "feature",
|
||||
head: "refs/heads/feature",
|
||||
});
|
||||
});
|
||||
|
||||
test("archives a workspace whose worktree Git administration is missing", async () => {
|
||||
const fixture = await createBaseRecoveryFixture(null);
|
||||
const gitDir = execFileSync("git", ["rev-parse", "--absolute-git-dir"], {
|
||||
cwd: fixture.workspace.cwd,
|
||||
encoding: "utf8",
|
||||
}).trim();
|
||||
rmSync(gitDir, { recursive: true, force: true });
|
||||
await archivePersistedWorkspaceRecord({
|
||||
workspaceId: fixture.workspace.workspaceId,
|
||||
workspaceRegistry: fixture.registry,
|
||||
});
|
||||
expect((await fixture.registry.get(fixture.workspace.workspaceId))?.archivedAt).toBeTruthy();
|
||||
});
|
||||
|
||||
test("restores a branch that shares its name with a tag", async () => {
|
||||
const fixture = await createBaseRecoveryFixture("main");
|
||||
execFileSync("git", ["tag", "feature"], { cwd: fixture.repoDir });
|
||||
await fixture.archiveAndRemove();
|
||||
expect((await fixture.registry.get(fixture.workspace.workspaceId))?.head).toBe(
|
||||
"refs/heads/feature",
|
||||
);
|
||||
expect(await fixture.service.inspect(fixture.workspace.workspaceId)).toMatchObject({
|
||||
branch: "feature",
|
||||
});
|
||||
await fixture.service.restore(fixture.workspace.workspaceId);
|
||||
expect(
|
||||
execFileSync("git", ["symbolic-ref", "HEAD"], {
|
||||
cwd: fixture.workspace.cwd,
|
||||
encoding: "utf8",
|
||||
}).trim(),
|
||||
).toBe("refs/heads/feature");
|
||||
});
|
||||
|
||||
test("restores detached HEAD even when the stored branch is stale", async () => {
|
||||
const fixture = await createBaseRecoveryFixture("main");
|
||||
execFileSync("git", ["switch", "--detach"], { cwd: fixture.workspace.cwd });
|
||||
const commit = execFileSync("git", ["rev-parse", "HEAD"], {
|
||||
cwd: fixture.workspace.cwd,
|
||||
encoding: "utf8",
|
||||
}).trim();
|
||||
await fixture.archiveAndRemove();
|
||||
expect(await fixture.registry.get(fixture.workspace.workspaceId)).toMatchObject({
|
||||
branch: "feature",
|
||||
head: commit,
|
||||
});
|
||||
expect(await fixture.service.inspect(fixture.workspace.workspaceId)).toMatchObject({
|
||||
branch: null,
|
||||
});
|
||||
await fixture.service.restore(fixture.workspace.workspaceId);
|
||||
expect(
|
||||
execFileSync("git", ["rev-parse", "--abbrev-ref", "HEAD"], {
|
||||
cwd: fixture.workspace.cwd,
|
||||
encoding: "utf8",
|
||||
}).trim(),
|
||||
).toBe("HEAD");
|
||||
expect(
|
||||
execFileSync("git", ["rev-parse", "HEAD"], {
|
||||
cwd: fixture.workspace.cwd,
|
||||
encoding: "utf8",
|
||||
}).trim(),
|
||||
).toBe(commit);
|
||||
});
|
||||
|
||||
test.each(["manual", "reconciliation"] as const)(
|
||||
"a later %s archive without a readable HEAD restores the latest recorded branch",
|
||||
async (route) => {
|
||||
const fixture = await createBaseRecoveryFixture("main");
|
||||
await fixture.archiveAndRemove();
|
||||
await fixture.service.restore(fixture.workspace.workspaceId);
|
||||
execFileSync("git", ["switch", "-c", "feature-b"], { cwd: fixture.workspace.cwd });
|
||||
writeFileSync(join(fixture.workspace.cwd, "newer.txt"), "newer\n");
|
||||
execFileSync("git", ["add", "newer.txt"], { cwd: fixture.workspace.cwd });
|
||||
execFileSync("git", ["-c", "commit.gpgsign=false", "commit", "-m", "newer"], {
|
||||
cwd: fixture.workspace.cwd,
|
||||
});
|
||||
const commit = execFileSync("git", ["rev-parse", "HEAD"], {
|
||||
cwd: fixture.workspace.cwd,
|
||||
encoding: "utf8",
|
||||
}).trim();
|
||||
// Placement reconciliation records the branch observed while the workspace is active.
|
||||
await fixture.registry.update(fixture.workspace.workspaceId, (workspace) => ({
|
||||
...workspace,
|
||||
branch: "feature-b",
|
||||
}));
|
||||
execFileSync("git", ["worktree", "remove", "--force", fixture.workspace.cwd], {
|
||||
cwd: fixture.repoDir,
|
||||
});
|
||||
if (route === "manual") {
|
||||
await archivePersistedWorkspaceRecord({
|
||||
workspaceId: fixture.workspace.workspaceId,
|
||||
workspaceRegistry: fixture.registry,
|
||||
});
|
||||
} else {
|
||||
await fixture.registry.archive(fixture.workspace.workspaceId, new Date().toISOString());
|
||||
}
|
||||
|
||||
expect(await fixture.registry.get(fixture.workspace.workspaceId)).toMatchObject({
|
||||
branch: "feature-b",
|
||||
head: undefined,
|
||||
});
|
||||
expect(await fixture.service.inspect(fixture.workspace.workspaceId)).toMatchObject({
|
||||
branch: "feature-b",
|
||||
});
|
||||
await fixture.service.restore(fixture.workspace.workspaceId);
|
||||
expect(
|
||||
execFileSync("git", ["symbolic-ref", "HEAD"], {
|
||||
cwd: fixture.workspace.cwd,
|
||||
encoding: "utf8",
|
||||
}).trim(),
|
||||
).toBe("refs/heads/feature-b");
|
||||
expect(
|
||||
execFileSync("git", ["rev-parse", "HEAD"], {
|
||||
cwd: fixture.workspace.cwd,
|
||||
encoding: "utf8",
|
||||
}).trim(),
|
||||
).toBe(commit);
|
||||
},
|
||||
);
|
||||
|
||||
test("restores a branchless workspace from its recorded base so work can continue", async () => {
|
||||
const fixture = await createBaseRecoveryFixture("refs/heads/release");
|
||||
execFileSync("git", ["switch", "-c", "release"], { cwd: fixture.repoDir, stdio: "pipe" });
|
||||
@@ -368,7 +500,7 @@ test("restores a branchless workspace from its recorded base so work can continu
|
||||
...workspace,
|
||||
branch: null,
|
||||
}));
|
||||
await fixture.archiveAndRemove();
|
||||
await fixture.archiveAndRemove(true);
|
||||
|
||||
await expect(fixture.service.inspect(fixture.workspace.workspaceId)).resolves.toMatchObject({
|
||||
kind: "recoverable",
|
||||
@@ -402,7 +534,7 @@ test("restores a branchless workspace from the repository default when its base
|
||||
...workspace,
|
||||
branch: null,
|
||||
}));
|
||||
await fixture.archiveAndRemove();
|
||||
await fixture.archiveAndRemove(true);
|
||||
|
||||
await expect(fixture.service.restore(fixture.workspace.workspaceId)).resolves.toEqual({
|
||||
workspaceId: fixture.workspace.workspaceId,
|
||||
@@ -418,6 +550,44 @@ test("restores a branchless workspace from the repository default when its base
|
||||
);
|
||||
});
|
||||
|
||||
test("restores the archived detached checkout at its recorded commit", async () => {
|
||||
const fixture = await createBaseRecoveryFixture("refs/heads/main");
|
||||
execFileSync("git", ["switch", "--detach"], { cwd: fixture.workspace.cwd });
|
||||
writeFileSync(join(fixture.workspace.cwd, "detached.txt"), "detached\n");
|
||||
execFileSync("git", ["add", "detached.txt"], { cwd: fixture.workspace.cwd });
|
||||
execFileSync("git", ["-c", "commit.gpgsign=false", "commit", "-m", "detached"], {
|
||||
cwd: fixture.workspace.cwd,
|
||||
});
|
||||
const commit = execFileSync("git", ["rev-parse", "HEAD"], {
|
||||
cwd: fixture.workspace.cwd,
|
||||
encoding: "utf8",
|
||||
}).trim();
|
||||
await fixture.archiveAndRemove();
|
||||
expect(await fixture.registry.get(fixture.workspace.workspaceId)).toMatchObject({
|
||||
branch: "feature",
|
||||
head: commit,
|
||||
});
|
||||
execFileSync("git", ["reflog", "expire", "--expire=now", "--all"], { cwd: fixture.repoDir });
|
||||
execFileSync("git", ["gc", "--prune=now"], { cwd: fixture.repoDir });
|
||||
await fixture.service.restore(fixture.workspace.workspaceId);
|
||||
expect(await readPaseoWorktreeMetadata(fixture.workspace.cwd)).toMatchObject({
|
||||
baseRefName: "main",
|
||||
baseRef: "refs/heads/main",
|
||||
});
|
||||
expect(
|
||||
execFileSync("git", ["rev-parse", "HEAD"], {
|
||||
cwd: fixture.workspace.cwd,
|
||||
encoding: "utf8",
|
||||
}).trim(),
|
||||
).toBe(commit);
|
||||
expect(
|
||||
execFileSync("git", ["rev-parse", "--abbrev-ref", "HEAD"], {
|
||||
cwd: fixture.workspace.cwd,
|
||||
encoding: "utf8",
|
||||
}).trim(),
|
||||
).toBe("HEAD");
|
||||
});
|
||||
|
||||
test("restores the branch HEAD with a base name when the exact base is missing", async () => {
|
||||
const fixture = await createBaseRecoveryFixture("refs/remotes/upstream/main");
|
||||
const headBeforeArchive = execFileSync("git", ["rev-parse", "HEAD"], {
|
||||
|
||||
+35
-8
@@ -151,13 +151,27 @@ export function createWorkspaceRecoveryService(deps: {
|
||||
workspace: PersistedWorkspaceRecord,
|
||||
sourceRepoRoot: string,
|
||||
): Promise<void> {
|
||||
const source: WorktreeSource = workspace.branch
|
||||
? { kind: "restore", branchName: workspace.branch, baseRef: workspace.baseBranch }
|
||||
: {
|
||||
kind: "restore-from-base",
|
||||
branchName: `restored/${randomUUID().slice(0, 8)}`,
|
||||
baseRef: await resolveRecoveryBase(sourceRepoRoot, workspace.baseBranch),
|
||||
};
|
||||
let source: WorktreeSource;
|
||||
const checkout = parseWorkspaceHead(workspace);
|
||||
if (checkout.kind === "branch") {
|
||||
source = {
|
||||
kind: "restore",
|
||||
branchName: checkout.branch,
|
||||
baseRef: workspace.baseBranch,
|
||||
};
|
||||
} else if (checkout.kind === "commit") {
|
||||
source = {
|
||||
kind: "restore-commit",
|
||||
commit: checkout.commit,
|
||||
baseRef: await resolveRecoveryBase(sourceRepoRoot, workspace.baseBranch),
|
||||
};
|
||||
} else {
|
||||
source = {
|
||||
kind: "restore-from-base",
|
||||
branchName: `restored/${randomUUID().slice(0, 8)}`,
|
||||
baseRef: await resolveRecoveryBase(sourceRepoRoot, workspace.baseBranch),
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
await runGitCommand(["worktree", "prune"], { cwd: sourceRepoRoot, timeout: 30_000 });
|
||||
@@ -251,16 +265,29 @@ async function resolveRecoveryBase(repoRoot: string, recordedBase: string | null
|
||||
return defaultBranch;
|
||||
}
|
||||
|
||||
function parseWorkspaceHead(
|
||||
workspace: PersistedWorkspaceRecord,
|
||||
): { kind: "branch"; branch: string } | { kind: "commit"; commit: string } | { kind: "missing" } {
|
||||
if (workspace.head) {
|
||||
const prefix = "refs/heads/";
|
||||
return workspace.head.startsWith(prefix)
|
||||
? { kind: "branch", branch: workspace.head.slice(prefix.length) }
|
||||
: { kind: "commit", commit: workspace.head };
|
||||
}
|
||||
return workspace.branch ? { kind: "branch", branch: workspace.branch } : { kind: "missing" };
|
||||
}
|
||||
|
||||
function createRecoveryPlan(
|
||||
input:
|
||||
| { action: "unarchive"; workspace: PersistedWorkspaceRecord }
|
||||
| { action: "restore"; workspace: PersistedWorkspaceRecord; sourceRepoRoot: string },
|
||||
): RecoveryPlan {
|
||||
const checkout = parseWorkspaceHead(input.workspace);
|
||||
const state = {
|
||||
kind: "recoverable" as const,
|
||||
workspaceId: input.workspace.workspaceId,
|
||||
workspaceName: resolveWorkspaceDisplayName(input.workspace),
|
||||
branch: input.workspace.branch,
|
||||
branch: checkout.kind === "branch" ? checkout.branch : null,
|
||||
};
|
||||
if (input.action === "restore") {
|
||||
return {
|
||||
|
||||
@@ -1,5 +1,13 @@
|
||||
import { execFile, execFileSync, spawn } from "node:child_process";
|
||||
import { existsSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { execFile, execFileSync } from "node:child_process";
|
||||
import {
|
||||
chmodSync,
|
||||
existsSync,
|
||||
mkdtempSync,
|
||||
readFileSync,
|
||||
rmSync,
|
||||
statSync,
|
||||
writeFileSync,
|
||||
} from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
@@ -569,7 +577,130 @@ test.skipIf(process.platform === "win32")(
|
||||
60000,
|
||||
);
|
||||
|
||||
async function createWorktreeWithTeardown(
|
||||
slug: string,
|
||||
worktreeConfig: { teardown: string; teardownTimeoutMs?: number },
|
||||
): Promise<{ workspaceId: string; worktreePath: string }> {
|
||||
const repoDir = createGitRepo();
|
||||
writeFileSync(path.join(repoDir, "paseo.json"), JSON.stringify({ worktree: worktreeConfig }));
|
||||
execFileSync("git", ["add", "paseo.json"], { cwd: repoDir, stdio: "pipe" });
|
||||
execFileSync("git", ["-c", "commit.gpgsign=false", "commit", "-m", "add teardown"], {
|
||||
cwd: repoDir,
|
||||
stdio: "pipe",
|
||||
});
|
||||
const result = await ctx.client.createWorkspace({
|
||||
source: { kind: "worktree", cwd: repoDir, worktreeSlug: slug, baseBranch: "main" },
|
||||
});
|
||||
const workspace = result.workspace;
|
||||
if (!workspace?.workspaceDirectory) {
|
||||
throw new Error(result.error ?? "Failed to create worktree workspace");
|
||||
}
|
||||
return { workspaceId: workspace.id, worktreePath: workspace.workspaceDirectory };
|
||||
}
|
||||
|
||||
function isProcessRunning(pid: number): boolean {
|
||||
try {
|
||||
process.kill(pid, 0);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
test.skipIf(process.platform === "win32")(
|
||||
"a paseo.json teardown that never exits is stopped and the archive answers",
|
||||
async () => {
|
||||
const pidFile = path.join(makeTempDir("hanging-teardown-"), "sleep.pid");
|
||||
const { workspaceId, worktreePath } = await createWorktreeWithTeardown("hanging-teardown", {
|
||||
teardown: `sleep 600 & echo $! > ${JSON.stringify(pidFile)}; wait`,
|
||||
teardownTimeoutMs: 2000,
|
||||
});
|
||||
|
||||
try {
|
||||
const archive = await ctx.client.archiveWorkspace(workspaceId);
|
||||
|
||||
expect({
|
||||
error: archive.error,
|
||||
workspaceActive: (await activeWorkspaceIds()).has(workspaceId),
|
||||
worktreeOnDisk: existsSync(worktreePath),
|
||||
}).toEqual({ error: null, workspaceActive: false, worktreeOnDisk: true });
|
||||
const sleepPid = Number(readFileSync(pidFile, "utf8").trim());
|
||||
await expect.poll(() => isProcessRunning(sleepPid), { timeout: 5000 }).toBe(false);
|
||||
} finally {
|
||||
if (existsSync(pidFile)) {
|
||||
const sleepPid = Number(readFileSync(pidFile, "utf8").trim());
|
||||
if (isProcessRunning(sleepPid)) process.kill(sleepPid, "SIGKILL");
|
||||
}
|
||||
}
|
||||
},
|
||||
30000,
|
||||
);
|
||||
|
||||
test.skipIf(process.platform === "win32")(
|
||||
"a paseo.json teardown that prints more than 1 MiB still removes the worktree",
|
||||
async () => {
|
||||
const { workspaceId, worktreePath } = await createWorktreeWithTeardown("chatty-teardown", {
|
||||
teardown: `node -e "process.stdout.write('x'.repeat(2 * 1024 * 1024))"`,
|
||||
});
|
||||
|
||||
const archive = await ctx.client.archiveWorkspace(workspaceId);
|
||||
|
||||
expect({
|
||||
error: archive.error,
|
||||
workspaceActive: (await activeWorkspaceIds()).has(workspaceId),
|
||||
worktreeOnDisk: existsSync(worktreePath),
|
||||
}).toEqual({ error: null, workspaceActive: false, worktreeOnDisk: false });
|
||||
},
|
||||
60000,
|
||||
);
|
||||
|
||||
test.skipIf(process.platform === "win32")(
|
||||
"a teardown that handles SIGTERM and exits zero still leaves the worktree",
|
||||
async () => {
|
||||
const { workspaceId, worktreePath } = await createWorktreeWithTeardown("teardown-trap", {
|
||||
teardown: `trap 'exit 0' TERM; sleep 5 & wait`,
|
||||
teardownTimeoutMs: 2000,
|
||||
});
|
||||
|
||||
const archive = await ctx.client.archiveWorkspace(workspaceId);
|
||||
|
||||
expect({
|
||||
error: archive.error,
|
||||
workspaceActive: (await activeWorkspaceIds()).has(workspaceId),
|
||||
worktreeOnDisk: existsSync(worktreePath),
|
||||
}).toEqual({ error: null, workspaceActive: false, worktreeOnDisk: true });
|
||||
},
|
||||
15000,
|
||||
);
|
||||
|
||||
test.skipIf(process.platform === "win32")(
|
||||
"the archive answers when an exited teardown shell's child holds its output open",
|
||||
async () => {
|
||||
const pidFile = path.join(makeTempDir("teardown-open-output-"), "sleep.pid");
|
||||
const { workspaceId, worktreePath } = await createWorktreeWithTeardown("teardown-open-output", {
|
||||
teardown: `sleep 12 & echo $! > ${JSON.stringify(pidFile)}`,
|
||||
teardownTimeoutMs: 2000,
|
||||
});
|
||||
|
||||
try {
|
||||
const archive = await ctx.client.archiveWorkspace(workspaceId);
|
||||
|
||||
expect({
|
||||
error: archive.error,
|
||||
workspaceActive: (await activeWorkspaceIds()).has(workspaceId),
|
||||
worktreeOnDisk: existsSync(worktreePath),
|
||||
}).toEqual({ error: null, workspaceActive: false, worktreeOnDisk: true });
|
||||
} finally {
|
||||
if (existsSync(pidFile)) {
|
||||
const sleepPid = Number(readFileSync(pidFile, "utf8").trim());
|
||||
if (isProcessRunning(sleepPid)) process.kill(sleepPid, "SIGKILL");
|
||||
}
|
||||
}
|
||||
},
|
||||
10000,
|
||||
);
|
||||
|
||||
test.skipIf(process.platform === "win32" || process.getuid?.() === 0)(
|
||||
"repeating archive removes a residual worktree for an already-archived workspace",
|
||||
async () => {
|
||||
const repoDir = createGitRepo();
|
||||
@@ -586,42 +717,24 @@ test.skipIf(process.platform === "win32")(
|
||||
throw new Error(result.error ?? "Failed to create worktree workspace");
|
||||
}
|
||||
|
||||
const writerStartedPath = path.join(repoDir, "writer-started");
|
||||
const stopWriterPath = path.join(repoDir, "stop-writer");
|
||||
const target = path.join(
|
||||
workspace.workspaceDirectory,
|
||||
"node_modules/react-native-svg/lib/typescript",
|
||||
);
|
||||
const writer = spawn(
|
||||
process.execPath,
|
||||
[
|
||||
"-e",
|
||||
`const fs=require('fs'),path=require('path');const target=${JSON.stringify(target)};const started=${JSON.stringify(writerStartedPath)};const stop=${JSON.stringify(stopWriterPath)};fs.writeFileSync(started,'started');while(!fs.existsSync(stop)){try{fs.mkdirSync(target,{recursive:true});fs.writeFileSync(path.join(target,'active'),String(Date.now()))}catch{}}`,
|
||||
],
|
||||
{ stdio: "ignore" },
|
||||
);
|
||||
const writerExit = new Promise<void>((resolve) => writer.once("exit", () => resolve()));
|
||||
|
||||
const directory = workspace.workspaceDirectory;
|
||||
const originalMode = statSync(directory).mode & 0o777;
|
||||
// Deny removal of entries such as .git until the second archive request.
|
||||
chmodSync(directory, originalMode & ~0o222);
|
||||
try {
|
||||
await expect.poll(() => existsSync(writerStartedPath), { timeout: 10000 }).toBe(true);
|
||||
|
||||
const firstArchive = await ctx.client.archiveWorkspace(workspace.id);
|
||||
|
||||
expect(firstArchive.error).toBeNull();
|
||||
expect((await activeWorkspaceIds()).has(workspace.id)).toBe(false);
|
||||
expect(existsSync(workspace.workspaceDirectory)).toBe(true);
|
||||
|
||||
writeFileSync(stopWriterPath, "stop\n");
|
||||
await writerExit;
|
||||
|
||||
const retry = await ctx.client.archiveWorkspace(workspace.id);
|
||||
|
||||
expect(retry.error).toBeNull();
|
||||
expect(existsSync(workspace.workspaceDirectory)).toBe(false);
|
||||
expect(existsSync(directory)).toBe(true);
|
||||
} finally {
|
||||
writeFileSync(stopWriterPath, "stop\n");
|
||||
await writerExit;
|
||||
if (existsSync(directory)) chmodSync(directory, originalMode);
|
||||
}
|
||||
|
||||
const retry = await ctx.client.archiveWorkspace(workspace.id);
|
||||
|
||||
expect(retry.error).toBeNull();
|
||||
expect(existsSync(directory)).toBe(false);
|
||||
},
|
||||
60000,
|
||||
);
|
||||
|
||||
@@ -8,6 +8,7 @@ import type { WorkspaceGitService } from "./workspace-git-service.js";
|
||||
import type { ForgeService } from "../services/forge-service.js";
|
||||
import {
|
||||
deletePaseoWorktree,
|
||||
readWorktreeHeadReference,
|
||||
isPaseoOwnedWorktreeCwd,
|
||||
runWorktreeTeardownCommands,
|
||||
WorktreeTeardownError,
|
||||
@@ -707,7 +708,15 @@ export async function archivePersistedWorkspaceRecord(input: {
|
||||
}
|
||||
|
||||
const archivedAt = input.archivedAt ?? new Date().toISOString();
|
||||
await input.workspaceRegistry.archive(input.workspaceId, archivedAt, input.context);
|
||||
let head: string | null = null;
|
||||
if (existingWorkspace.kind === "worktree") {
|
||||
const cwd = existingWorkspace.worktreeRoot ?? existingWorkspace.cwd;
|
||||
head = await readWorktreeHeadReference(cwd);
|
||||
}
|
||||
await input.workspaceRegistry.archive(input.workspaceId, archivedAt, {
|
||||
...input.context,
|
||||
...(head ? { head } : {}),
|
||||
});
|
||||
|
||||
return existingWorkspace;
|
||||
}
|
||||
|
||||
@@ -1,6 +1,14 @@
|
||||
import { DaemonClient } from "./test-utils/daemon-client.js";
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { existsSync, mkdtempSync, rmSync, writeFileSync, renameSync, mkdirSync } from "node:fs";
|
||||
import {
|
||||
existsSync,
|
||||
mkdtempSync,
|
||||
readFileSync,
|
||||
rmSync,
|
||||
writeFileSync,
|
||||
renameSync,
|
||||
mkdirSync,
|
||||
} from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { afterEach, beforeEach, expect, test } from "vitest";
|
||||
@@ -125,6 +133,55 @@ test.skipIf(process.platform === "win32")(
|
||||
60000,
|
||||
);
|
||||
|
||||
test.skipIf(process.platform === "win32")(
|
||||
"an undo during a teardown that never exits returns once the deadline stops it",
|
||||
async () => {
|
||||
const tempRoot = mkdtempSync(path.join(tmpdir(), "workspace-archive-undo-hang-"));
|
||||
tempRoots.push(tempRoot);
|
||||
const repoDir = path.join(tempRoot, "repo");
|
||||
const pidFile = path.join(tempRoot, "sleep.pid");
|
||||
execFileSync("git", ["init", "-b", "main", repoDir], { stdio: "pipe" });
|
||||
git(repoDir, ["config", "user.email", "test@getpaseo.local"]);
|
||||
git(repoDir, ["config", "user.name", "Paseo Test"]);
|
||||
writeFileSync(
|
||||
path.join(repoDir, "paseo.json"),
|
||||
JSON.stringify({
|
||||
worktree: {
|
||||
teardown: `sleep 600 & echo $! > ${JSON.stringify(pidFile)}; wait`,
|
||||
teardownTimeoutMs: 2000,
|
||||
},
|
||||
}),
|
||||
);
|
||||
git(repoDir, ["add", "paseo.json"]);
|
||||
git(repoDir, ["-c", "commit.gpgsign=false", "commit", "-m", "hanging teardown"]);
|
||||
const { workspaceId, directory, agentId } = await createWorktreeWorkspaceWithAgent(
|
||||
repoDir,
|
||||
"undo-during-hanging-teardown",
|
||||
);
|
||||
try {
|
||||
const archive = ctx.client.archiveWorkspace(workspaceId);
|
||||
await expect.poll(() => existsSync(pidFile), { timeout: 15000 }).toBe(true);
|
||||
await Promise.all([archive, ctx.client.undoWorkspaceArchive(workspaceId)]);
|
||||
|
||||
expect({
|
||||
workspaceActive: await isWorkspaceActive(workspaceId),
|
||||
directoryExists: existsSync(directory),
|
||||
agentArchived: await isAgentArchived(agentId),
|
||||
}).toEqual({ workspaceActive: true, directoryExists: true, agentArchived: false });
|
||||
} finally {
|
||||
if (existsSync(pidFile)) {
|
||||
const sleepPid = Number(readFileSync(pidFile, "utf8").trim());
|
||||
try {
|
||||
process.kill(sleepPid, "SIGKILL");
|
||||
} catch {
|
||||
// Already stopped by the teardown deadline.
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
30000,
|
||||
);
|
||||
|
||||
test.skipIf(process.platform === "win32")(
|
||||
"an undo after the archive finished recreates the worktree and its agents",
|
||||
async () => {
|
||||
@@ -151,6 +208,40 @@ test.skipIf(process.platform === "win32")(
|
||||
60000,
|
||||
);
|
||||
|
||||
test.skipIf(process.platform === "win32").each([
|
||||
["branch", "restore"],
|
||||
["branch", "undo"],
|
||||
["detached", "restore"],
|
||||
["detached", "undo"],
|
||||
] as const)(
|
||||
"%s checkout survives archive and %s",
|
||||
async (checkout, action) => {
|
||||
const repo = createRepoWithGatedTeardown();
|
||||
repo.releaseTeardown();
|
||||
const { workspaceId, directory } = await createWorktreeWorkspaceWithAgent(
|
||||
repo.repoDir,
|
||||
`keep-${checkout}-${action}`,
|
||||
);
|
||||
if (checkout === "detached") git(directory, ["switch", "--detach"]);
|
||||
writeFileSync(path.join(directory, "change.txt"), `${checkout}\n`);
|
||||
git(directory, ["add", "change.txt"]);
|
||||
git(directory, ["-c", "commit.gpgsign=false", "commit", "-m", "workspace commit"]);
|
||||
const readHead = (args: string[]) =>
|
||||
execFileSync("git", args, { cwd: directory, encoding: "utf8" }).trim();
|
||||
const commit = readHead(["rev-parse", "HEAD"]);
|
||||
const branch = readHead(["rev-parse", "--abbrev-ref", "HEAD"]);
|
||||
expect((await ctx.client.archiveWorkspace(workspaceId)).error).toBeNull();
|
||||
expect(existsSync(directory)).toBe(false);
|
||||
git(repo.repoDir, ["reflog", "expire", "--expire=now", "--all"]);
|
||||
git(repo.repoDir, ["gc", "--prune=now"]);
|
||||
if (action === "undo") await ctx.client.undoWorkspaceArchive(workspaceId);
|
||||
else await ctx.client.restoreWorkspace(workspaceId);
|
||||
expect(readHead(["rev-parse", "HEAD"])).toBe(commit);
|
||||
expect(readHead(["rev-parse", "--abbrev-ref", "HEAD"])).toBe(branch);
|
||||
},
|
||||
60000,
|
||||
);
|
||||
|
||||
test.skipIf(process.platform === "win32")(
|
||||
"archive, undo, archive leaves the workspace archived",
|
||||
async () => {
|
||||
|
||||
@@ -604,6 +604,7 @@ interface WorkspaceGitAuxiliaryReadCacheEntry<T> {
|
||||
|
||||
interface WorkspaceForgePrStatusPollTarget {
|
||||
headRef: string;
|
||||
currentBranch?: string;
|
||||
headSha?: string;
|
||||
headRepositoryOwner?: string;
|
||||
}
|
||||
@@ -3150,11 +3151,7 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
|
||||
if (resolution.service.retainCurrentPullRequestStatusPoll) {
|
||||
target.forgePrStatusPollSubscription = resolution.service.retainCurrentPullRequestStatusPoll({
|
||||
cwd: target.cwd,
|
||||
headRef: pollTarget.headRef,
|
||||
...(pollTarget.headSha ? { headSha: pollTarget.headSha } : {}),
|
||||
...(pollTarget.headRepositoryOwner
|
||||
? { headRepositoryOwner: pollTarget.headRepositoryOwner }
|
||||
: {}),
|
||||
...pollTarget,
|
||||
onStatus: (status) => {
|
||||
if (!this.isActiveObservedWorkspaceTarget(target)) {
|
||||
return;
|
||||
@@ -3226,11 +3223,7 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
|
||||
try {
|
||||
const status = await service.getCurrentPullRequestStatus({
|
||||
cwd: target.cwd,
|
||||
headRef: pollTarget.headRef,
|
||||
...(pollTarget.headSha ? { headSha: pollTarget.headSha } : {}),
|
||||
...(pollTarget.headRepositoryOwner
|
||||
? { headRepositoryOwner: pollTarget.headRepositoryOwner }
|
||||
: {}),
|
||||
...pollTarget,
|
||||
reason: "self-heal-forge-pr-status",
|
||||
});
|
||||
if (!closed && this.isActiveObservedWorkspaceTarget(target)) {
|
||||
@@ -3285,13 +3278,14 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
|
||||
target.latestFacts?.isGit && target.latestFacts.currentBranch === git.currentBranch
|
||||
? target.latestFacts.pullRequestLookupTarget
|
||||
: null;
|
||||
if (target.latestFacts?.isGit && target.latestFacts.paseoWorktree.isPaseoOwnedWorktree) {
|
||||
return lookupTarget;
|
||||
}
|
||||
if (lookupTarget) {
|
||||
return lookupTarget;
|
||||
return git.currentBranch === lookupTarget.headRef
|
||||
? lookupTarget
|
||||
: { ...lookupTarget, currentBranch: git.currentBranch };
|
||||
}
|
||||
if (target.latestFacts?.isGit && target.latestFacts.paseoWorktree.isPaseoOwnedWorktree) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return { headRef: git.currentBranch };
|
||||
}
|
||||
|
||||
@@ -4424,6 +4418,7 @@ function buildWorkspaceForgePrStatusPollKey({
|
||||
forge,
|
||||
remoteUrl,
|
||||
target.headRef,
|
||||
target.currentBranch ?? null,
|
||||
target.headSha ?? null,
|
||||
target.headRepositoryOwner ?? null,
|
||||
]);
|
||||
|
||||
@@ -72,6 +72,7 @@ const PersistedWorkspaceRecordSchema = z.object({
|
||||
.nullable()
|
||||
.optional()
|
||||
.transform((value) => value ?? null),
|
||||
head: z.string().optional(),
|
||||
// Exact checkout/worktree root backing cwd. This differs from cwd when the
|
||||
// selected project is a subdirectory inside a repository. Persist it so
|
||||
// archive and recovery do not need the directory to still exist in order to
|
||||
@@ -126,6 +127,7 @@ export interface WorkspaceMutationContext {
|
||||
|
||||
export interface WorkspaceArchiveContext {
|
||||
autoArchivedChangeRequestUrl?: string;
|
||||
head?: string;
|
||||
}
|
||||
|
||||
export interface ProjectMutation {
|
||||
@@ -586,6 +588,7 @@ export class FileBackedWorkspaceRegistry
|
||||
...existing,
|
||||
updatedAt: archivedAt,
|
||||
archivedAt,
|
||||
head: context?.head,
|
||||
...(context?.autoArchivedChangeRequestUrl
|
||||
? { autoArchivedChangeRequestUrl: context.autoArchivedChangeRequestUrl }
|
||||
: {}),
|
||||
|
||||
@@ -436,6 +436,22 @@ export interface CreatePullRequestOptions {
|
||||
body?: string;
|
||||
}
|
||||
|
||||
export interface CurrentPullRequestLookup {
|
||||
cwd: string;
|
||||
headRef: string;
|
||||
headSha?: string;
|
||||
headRepositoryOwner?: string;
|
||||
/** Local branch name when it differs from the PR source ref. */
|
||||
currentBranch?: string;
|
||||
}
|
||||
|
||||
export function isOnDefaultBranch(
|
||||
lookup: Pick<CurrentPullRequestLookup, "currentBranch" | "headRef">,
|
||||
defaultBranch: string | null | undefined,
|
||||
): boolean {
|
||||
return (lookup.currentBranch ?? lookup.headRef) === defaultBranch;
|
||||
}
|
||||
|
||||
export interface ForgeService {
|
||||
listPullRequests(options: ListPullRequestsOptions): Promise<PullRequestSummary[]>;
|
||||
listIssues(options: ListIssuesOptions): Promise<IssueSummary[]>;
|
||||
@@ -475,12 +491,7 @@ export interface ForgeService {
|
||||
*/
|
||||
getReferenceRepository?(options: { cwd: string } & ForgeReadOptions): Promise<string | null>;
|
||||
getCurrentPullRequestStatus(
|
||||
options: {
|
||||
cwd: string;
|
||||
headRef: string;
|
||||
headSha?: string;
|
||||
headRepositoryOwner?: string;
|
||||
} & ForgeReadOptions,
|
||||
options: CurrentPullRequestLookup & ForgeReadOptions,
|
||||
): Promise<CurrentPullRequestStatus | null>;
|
||||
getPullRequestTimeline(options: GetPullRequestTimelineOptions): Promise<PullRequestTimeline>;
|
||||
getCheckDetails(options: GetCheckDetailsOptions): Promise<CheckDetails>;
|
||||
@@ -516,14 +527,12 @@ export interface ForgeService {
|
||||
* cannot change the outcome and is pure overhead.
|
||||
*/
|
||||
authProbeCanThrow?: boolean;
|
||||
retainCurrentPullRequestStatusPoll?(options: {
|
||||
cwd: string;
|
||||
headRef: string;
|
||||
headSha?: string;
|
||||
headRepositoryOwner?: string;
|
||||
onStatus?: (status: CurrentPullRequestStatus | null) => void;
|
||||
onError?: (error: unknown) => void;
|
||||
}): { unsubscribe: () => void };
|
||||
retainCurrentPullRequestStatusPoll?(
|
||||
options: CurrentPullRequestLookup & {
|
||||
onStatus?: (status: CurrentPullRequestStatus | null) => void;
|
||||
onError?: (error: unknown) => void;
|
||||
},
|
||||
): { unsubscribe: () => void };
|
||||
invalidate(options: { cwd: string }): void;
|
||||
dispose?(): void;
|
||||
}
|
||||
|
||||
@@ -2036,6 +2036,33 @@ describe("createGiteaService", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it("hides a historical PR on the repository's default branch", async () => {
|
||||
const historical = currentPullRequestApi({
|
||||
number: 8,
|
||||
state: "closed",
|
||||
headRef: "trunk",
|
||||
headSha: "8888888888888888888888888888888888888888",
|
||||
});
|
||||
const { service } = makeService((args) => {
|
||||
if (args[0] === "pr" && args[1] === "list") return ok("[]");
|
||||
if (args[0] === "api" && args[1].includes("/pulls?state=all")) {
|
||||
return ok(JSON.stringify([historical]));
|
||||
}
|
||||
if (args[0] === "api" && args[1] === "repos/example-user/sample-repo") {
|
||||
return ok(
|
||||
JSON.stringify({
|
||||
full_name: "example-user/sample-repo",
|
||||
default_branch: "trunk",
|
||||
}),
|
||||
);
|
||||
}
|
||||
throw new Error(`unexpected call: ${args.join(" ")}`);
|
||||
});
|
||||
await expect(
|
||||
service.getCurrentPullRequestStatus({ cwd: "/repo", headRef: "trunk" }),
|
||||
).resolves.toBeNull();
|
||||
});
|
||||
|
||||
it("falls back to the recent all-state PR window for a recently closed current branch PR", async () => {
|
||||
const headSha = "8888888888888888888888888888888888888888";
|
||||
const closedPr = currentPullRequestApi({
|
||||
|
||||
@@ -26,11 +26,13 @@ import {
|
||||
compareTimelineItems,
|
||||
createUnavailableSearchResult,
|
||||
normalizeForgeSearchKinds,
|
||||
isOnDefaultBranch,
|
||||
parseOptionalTime,
|
||||
} from "./forge-service.js";
|
||||
import type {
|
||||
CheckDetails,
|
||||
CreatePullRequestOptions,
|
||||
CurrentPullRequestLookup,
|
||||
CurrentPullRequestStatus,
|
||||
DisablePullRequestAutoMergeOptions,
|
||||
EnablePullRequestAutoMergeOptions,
|
||||
@@ -251,6 +253,7 @@ const GiteaPullRequestApiSchema = z
|
||||
const GiteaRepositoryApiSchema = z
|
||||
.object({
|
||||
full_name: z.string(),
|
||||
default_branch: z.string().nullish(),
|
||||
parent: z.object({ full_name: z.string().optional() }).nullable().optional(),
|
||||
})
|
||||
.passthrough();
|
||||
@@ -1585,11 +1588,9 @@ export function createGiteaService(options: CreateGiteaServiceOptions = {}): For
|
||||
return { items, truncated: true };
|
||||
}
|
||||
|
||||
async function loadCurrentPullRequestStatus(input: {
|
||||
cwd: string;
|
||||
headRef: string;
|
||||
headSha?: string;
|
||||
}): Promise<CurrentPullRequestStatus | null> {
|
||||
async function loadCurrentPullRequestStatus(
|
||||
input: CurrentPullRequestLookup,
|
||||
): Promise<CurrentPullRequestStatus | null> {
|
||||
const match = await findCurrentPullRequestForHeadRef(input);
|
||||
if (!match) {
|
||||
return null;
|
||||
@@ -1613,11 +1614,19 @@ export function createGiteaService(options: CreateGiteaServiceOptions = {}): For
|
||||
return identity ? { owner: identity.owner, name: identity.name } : null;
|
||||
}
|
||||
|
||||
async function findCurrentPullRequestForHeadRef(input: {
|
||||
cwd: string;
|
||||
headRef: string;
|
||||
headSha?: string;
|
||||
}): Promise<GiteaPrListItem | null> {
|
||||
function readRepository(cwd: string, repoPath: string) {
|
||||
return runJson(["api", repoPath], { cwd }, GiteaRepositoryApiSchema);
|
||||
}
|
||||
|
||||
function repositoryApiPath(repo: { owner: string; name: string } | null): string {
|
||||
return repo
|
||||
? `repos/${encodeURIComponent(repo.owner)}/${encodeURIComponent(repo.name)}`
|
||||
: "repos/{owner}/{repo}";
|
||||
}
|
||||
|
||||
async function findCurrentPullRequestForHeadRef(
|
||||
input: CurrentPullRequestLookup,
|
||||
): Promise<GiteaPrListItem | null> {
|
||||
const repoIdentity = await resolveCurrentRepoIdentity(input.cwd);
|
||||
const expectedHeadOwner = repoIdentity?.owner ?? null;
|
||||
const openMatch = await findOpenPullRequestForHeadRef(input, expectedHeadOwner);
|
||||
@@ -1628,9 +1637,7 @@ export function createGiteaService(options: CreateGiteaServiceOptions = {}): For
|
||||
// tea discovers repository context from any configured git remote, while
|
||||
// the default remote resolver reads origin only. Preserve that broader
|
||||
// discovery for repositories whose primary remote has another name.
|
||||
const repoPath = repoIdentity
|
||||
? `repos/${encodeURIComponent(repoIdentity.owner)}/${encodeURIComponent(repoIdentity.name)}`
|
||||
: "repos/{owner}/{repo}";
|
||||
const repoPath = repositoryApiPath(repoIdentity);
|
||||
const recentItems = await runJsonArray(
|
||||
[
|
||||
"api",
|
||||
@@ -1666,6 +1673,12 @@ export function createGiteaService(options: CreateGiteaServiceOptions = {}): For
|
||||
) ??
|
||||
candidates[0] ??
|
||||
null;
|
||||
if (match && mapGiteaState(match.state) !== "open") {
|
||||
const repository = await readRepository(input.cwd, repoPath).catch(() => null);
|
||||
if (isOnDefaultBranch(input, repository?.default_branch)) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
return match ? currentPullRequestApiToListItem(match) : null;
|
||||
}
|
||||
|
||||
@@ -2020,20 +2033,12 @@ export function createGiteaService(options: CreateGiteaServiceOptions = {}): For
|
||||
if (!repo) {
|
||||
return null;
|
||||
}
|
||||
const repository = await runJson(
|
||||
["api", `repos/${encodeURIComponent(repo.owner)}/${encodeURIComponent(repo.name)}`],
|
||||
{ cwd: input.cwd },
|
||||
GiteaRepositoryApiSchema,
|
||||
);
|
||||
const repository = await readRepository(input.cwd, repositoryApiPath(repo));
|
||||
return repository.parent?.full_name ?? null;
|
||||
},
|
||||
|
||||
getCurrentPullRequestStatus(input): Promise<CurrentPullRequestStatus | null> {
|
||||
return loadCurrentPullRequestStatus({
|
||||
cwd: input.cwd,
|
||||
headRef: input.headRef,
|
||||
headSha: input.headSha,
|
||||
});
|
||||
return loadCurrentPullRequestStatus(input);
|
||||
},
|
||||
|
||||
async getPullRequest(input: GetPullRequestOptions): Promise<PullRequestSummary> {
|
||||
|
||||
@@ -552,7 +552,7 @@ describe("ForgeService", () => {
|
||||
"view",
|
||||
"fork-owner/repo",
|
||||
"--json",
|
||||
"owner,name,parent",
|
||||
"owner,name,parent,defaultBranchRef",
|
||||
]);
|
||||
});
|
||||
|
||||
@@ -862,7 +862,7 @@ describe("ForgeService", () => {
|
||||
expect(runner.calls).toHaveLength(2);
|
||||
expect(runner.calls[0]).toEqual({
|
||||
cwd: "/repo",
|
||||
args: ["repo", "view", "--json", "owner,name,parent"],
|
||||
args: ["repo", "view", "--json", "owner,name,parent,defaultBranchRef"],
|
||||
});
|
||||
expect(runner.calls[1]?.cwd).toBe("/repo");
|
||||
expect(runner.calls[1]?.args.slice(0, 3)).toEqual(["api", "graphql", "-f"]);
|
||||
@@ -1111,6 +1111,56 @@ describe("ForgeService", () => {
|
||||
expect(currentPullRequestStatusCalls(runner.calls)).toHaveLength(1);
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ currentBranch: undefined, state: "MERGED", expected: null, calls: 1 },
|
||||
{ currentBranch: undefined, state: "OPEN", expected: "open", calls: 2 },
|
||||
{ currentBranch: "fork/trunk", state: "MERGED", expected: "merged", calls: 2 },
|
||||
])(
|
||||
"polls a $state PR with source trunk from checkout $currentBranch",
|
||||
async ({ currentBranch, state, expected, calls }) => {
|
||||
const runner = createScriptedRunner([
|
||||
batchPollStatusJson({
|
||||
t0: batchPollRepositoryJson(
|
||||
[
|
||||
batchPollPrNodeJson({
|
||||
headRefName: "trunk",
|
||||
state,
|
||||
...(state === "OPEN" ? { mergedAt: null } : {}),
|
||||
}),
|
||||
],
|
||||
{
|
||||
defaultBranchRef: { name: "trunk" },
|
||||
},
|
||||
),
|
||||
}),
|
||||
batchPollStatusJson({ t0: batchPollChecksAliasJson([]) }),
|
||||
]);
|
||||
const service = createGitHubService({
|
||||
runner: runner.runner,
|
||||
resolveGhPath: async () => "/usr/bin/gh",
|
||||
resolveRepoHost: async () => null,
|
||||
resolveRepoSlug: async () => "acme/widgets",
|
||||
now: () => 0,
|
||||
});
|
||||
const statuses: Array<CurrentPullRequestStatus | null> = [];
|
||||
try {
|
||||
service.retainCurrentPullRequestStatusPoll?.({
|
||||
cwd: "/repo",
|
||||
headRef: "trunk",
|
||||
currentBranch,
|
||||
onStatus: (status) => statuses.push(status),
|
||||
});
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
await flushMicrotasks();
|
||||
|
||||
expect(statuses.map((status) => status?.state ?? null)).toEqual([expected]);
|
||||
expect(runner.calls).toHaveLength(calls);
|
||||
} finally {
|
||||
service.dispose?.();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it("batches PR status polls across workspaces into one GraphQL request", async () => {
|
||||
let now = 0;
|
||||
const runner = createScriptedRunner([
|
||||
@@ -1490,13 +1540,19 @@ describe("ForgeService", () => {
|
||||
batchPollStatusJson({
|
||||
t0: batchPollRepositoryJson([], { isFork: true, parent }),
|
||||
}),
|
||||
batchPollStatusJson({ t0: batchPollRepositoryJson([forkPr]) }),
|
||||
batchPollStatusJson({
|
||||
t0: batchPollRepositoryJson([forkPr], { defaultBranchRef: { name: "feat-a" } }),
|
||||
origin0: { defaultBranchRef: { name: "main" } },
|
||||
}),
|
||||
batchPollStatusJson({
|
||||
t0: batchPollChecksAliasJson([
|
||||
{ __typename: "StatusContext", context: "ci", state: "SUCCESS" },
|
||||
]),
|
||||
}),
|
||||
batchPollStatusJson({ t0: batchPollRepositoryJson([forkPr]) }),
|
||||
batchPollStatusJson({
|
||||
t0: batchPollRepositoryJson([forkPr], { defaultBranchRef: { name: "feat-a" } }),
|
||||
origin0: { defaultBranchRef: { name: "main" } },
|
||||
}),
|
||||
]);
|
||||
const service = createGitHubService({
|
||||
ttlMs: 0,
|
||||
@@ -1524,6 +1580,9 @@ describe("ForgeService", () => {
|
||||
expect(runner.calls[1]?.args[3]).toContain(
|
||||
't0: repository(owner: "upstream", name: "widgets")',
|
||||
);
|
||||
expect(runner.calls[1]?.args[3]).toContain(
|
||||
'origin0: repository(owner: "forkowner", name: "widgets")',
|
||||
);
|
||||
expect(statuses).toEqual([
|
||||
expect.objectContaining({ number: 42, repoOwner: "upstream", checksStatus: "success" }),
|
||||
]);
|
||||
@@ -3278,6 +3337,30 @@ describe("ForgeService", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
["main", "CLOSED"],
|
||||
["master", "MERGED"],
|
||||
])("hides a %s PR on the default branch in a direct read (state %s)", async (headRef, state) => {
|
||||
const historical = currentPullRequestJson({
|
||||
headRefName: headRef,
|
||||
headRepositoryOwner: { login: "acme" },
|
||||
state,
|
||||
});
|
||||
const runner = createScriptedRunner([
|
||||
historical,
|
||||
JSON.stringify({ owner: { login: "acme" }, defaultBranchRef: { name: headRef } }),
|
||||
JSON.stringify([JSON.parse(historical)]),
|
||||
]);
|
||||
const service = createGitHubService({
|
||||
runner: runner.runner,
|
||||
resolveGhPath: async () => "/usr/bin/gh",
|
||||
});
|
||||
|
||||
await expect(
|
||||
service.getCurrentPullRequestStatus({ cwd: "/repo", headRef }),
|
||||
).resolves.toBeNull();
|
||||
});
|
||||
|
||||
it("keeps a merged PR when headRefOid matches the checkout HEAD", async () => {
|
||||
const headSha = "2222222222222222222222222222222222222222";
|
||||
const runner = createRunner([
|
||||
@@ -3605,7 +3688,7 @@ describe("ForgeService", () => {
|
||||
});
|
||||
expect(runner.calls.slice(0, 5).map((call) => call.args)).toEqual([
|
||||
["pr", "view", "--json", CURRENT_PR_STATUS_FIELDS],
|
||||
["repo", "view", "--json", "owner,name,parent"],
|
||||
["repo", "view", "--json", "owner,name,parent,defaultBranchRef"],
|
||||
["api", `repos/parentOwner/parentRepo/pulls?${FORK_PR_QUERY}`],
|
||||
["pr", "view", "41", "--repo", "parentOwner/parentRepo", "--json", CURRENT_PR_STATUS_FIELDS],
|
||||
["pr", "view", "42", "--repo", "parentOwner/parentRepo", "--json", CURRENT_PR_STATUS_FIELDS],
|
||||
@@ -3837,7 +3920,7 @@ describe("ForgeService", () => {
|
||||
});
|
||||
expect(runner.calls.slice(0, 5).map((call) => call.args)).toEqual([
|
||||
["pr", "view", "--json", CURRENT_PR_STATUS_FIELDS],
|
||||
["repo", "view", "--json", "owner,name,parent"],
|
||||
["repo", "view", "--json", "owner,name,parent,defaultBranchRef"],
|
||||
["api", `repos/parentOwner/parentRepo/pulls?${FORK_PR_QUERY}`],
|
||||
["pr", "view", "42", "--repo", "parentOwner/parentRepo", "--json", CURRENT_PR_STATUS_FIELDS],
|
||||
[
|
||||
@@ -3902,7 +3985,7 @@ describe("ForgeService", () => {
|
||||
).resolves.toBeNull();
|
||||
expect(calls.map((call) => call.args)).toEqual([
|
||||
["pr", "view", "--json", CURRENT_PR_STATUS_FIELDS],
|
||||
["repo", "view", "--json", "owner,name,parent"],
|
||||
["repo", "view", "--json", "owner,name,parent,defaultBranchRef"],
|
||||
[
|
||||
"pr",
|
||||
"list",
|
||||
@@ -4750,7 +4833,12 @@ describe("ForgeService", () => {
|
||||
}),
|
||||
).resolves.toEqual({ url: "https://github.com/acme/repo/pull/7", number: 7 });
|
||||
|
||||
expect(runner.calls[0]?.args).toEqual(["repo", "view", "--json", "owner,name,parent"]);
|
||||
expect(runner.calls[0]?.args).toEqual([
|
||||
"repo",
|
||||
"view",
|
||||
"--json",
|
||||
"owner,name,parent,defaultBranchRef",
|
||||
]);
|
||||
expect(runner.calls[1]?.args).toEqual([
|
||||
"api",
|
||||
"-X",
|
||||
@@ -4824,7 +4912,7 @@ describe("ForgeService", () => {
|
||||
expect(readFakeGitHubCliLog(fixture.logPath)).toEqual(
|
||||
expect.arrayContaining([
|
||||
"auth status --hostname github.acme.internal|",
|
||||
"repo view --json owner,name,parent|github.acme.internal",
|
||||
"repo view --json owner,name,parent,defaultBranchRef|github.acme.internal",
|
||||
"api -X POST repos/acme/repo/pulls -f title=Add thing -f head=feature -f base=main|github.acme.internal",
|
||||
]),
|
||||
);
|
||||
@@ -4869,7 +4957,7 @@ describe("ForgeService", () => {
|
||||
).toHaveLength(2);
|
||||
expect(log).toEqual(
|
||||
expect.arrayContaining([
|
||||
"repo view --json owner,name,parent|github.acme.internal",
|
||||
"repo view --json owner,name,parent,defaultBranchRef|github.acme.internal",
|
||||
"api -X POST repos/acme/repo/pulls -f title=Add thing -f head=feature -f base=main|github.acme.internal",
|
||||
]),
|
||||
);
|
||||
|
||||
@@ -27,6 +27,7 @@ import {
|
||||
computeChecksStatus,
|
||||
compareTimelineItems,
|
||||
createUnavailableSearchResult,
|
||||
isOnDefaultBranch,
|
||||
normalizeForgeSearchKinds,
|
||||
parseOptionalTime,
|
||||
} from "./forge-service.js";
|
||||
@@ -34,6 +35,7 @@ import type {
|
||||
CheckAnnotation,
|
||||
CheckDetails,
|
||||
CheckFailedJob,
|
||||
CurrentPullRequestLookup,
|
||||
CurrentPullRequestStatus,
|
||||
DisablePullRequestAutoMergeOptions,
|
||||
EnablePullRequestAutoMergeOptions,
|
||||
@@ -446,7 +448,11 @@ const PullRequestTimelineGraphqlSchema = z.object({
|
||||
.optional(),
|
||||
});
|
||||
|
||||
const GitHubRepoViewSchema = z.object({
|
||||
const GitHubDefaultBranchSchema = z.object({
|
||||
defaultBranchRef: z.object({ name: z.string() }).nullish(),
|
||||
});
|
||||
|
||||
const GitHubRepoViewSchema = GitHubDefaultBranchSchema.extend({
|
||||
owner: z
|
||||
.object({
|
||||
login: z.string().optional(),
|
||||
@@ -657,7 +663,7 @@ const BatchPollPrNodeSchema = z.object({
|
||||
isInMergeQueue: z.boolean().optional().catch(false),
|
||||
});
|
||||
|
||||
const BatchPollRepositorySchema = z.object({
|
||||
const BatchPollRepositorySchema = GitHubDefaultBranchSchema.extend({
|
||||
owner: z.object({ login: z.string().optional() }).nullable().optional().catch(null),
|
||||
isFork: z.boolean().optional().catch(false),
|
||||
parent: z
|
||||
@@ -779,9 +785,7 @@ function graphqlString(value: string): string {
|
||||
return JSON.stringify(value);
|
||||
}
|
||||
|
||||
function buildBatchPullRequestStatusQuery(
|
||||
entries: Array<{ owner: string; name: string; headRef: string }>,
|
||||
): string {
|
||||
function buildBatchPullRequestStatusQuery(entries: GitHubBatchPollEntry[]): string {
|
||||
const aliases = entries.map(
|
||||
(entry, index) => ` ${batchAlias(index)}: repository(owner: ${graphqlString(
|
||||
entry.owner,
|
||||
@@ -789,6 +793,9 @@ function buildBatchPullRequestStatusQuery(
|
||||
owner {
|
||||
login
|
||||
}
|
||||
defaultBranchRef {
|
||||
name
|
||||
}
|
||||
isFork
|
||||
parent {
|
||||
owner {
|
||||
@@ -802,7 +809,7 @@ function buildBatchPullRequestStatusQuery(
|
||||
rebaseMergeAllowed
|
||||
viewerDefaultMergeMethod
|
||||
pullRequests(headRefName: ${graphqlString(
|
||||
entry.headRef,
|
||||
entry.target.headRef,
|
||||
)}, first: ${BATCH_PR_CANDIDATE_LIMIT}, orderBy: {field: CREATED_AT, direction: DESC}) {
|
||||
nodes {
|
||||
...PaseoPollPullRequest
|
||||
@@ -810,13 +817,26 @@ function buildBatchPullRequestStatusQuery(
|
||||
}
|
||||
}`,
|
||||
);
|
||||
const originAliases = entries.flatMap((entry, index) =>
|
||||
entry.owner === entry.originOwner && entry.name === entry.originName
|
||||
? []
|
||||
: [
|
||||
` origin${index}: repository(owner: ${graphqlString(
|
||||
entry.originOwner,
|
||||
)}, name: ${graphqlString(entry.originName)}) {
|
||||
defaultBranchRef {
|
||||
name
|
||||
}
|
||||
}`,
|
||||
],
|
||||
);
|
||||
return `query PaseoBatchPullRequestStatus {
|
||||
rateLimit {
|
||||
limit
|
||||
remaining
|
||||
resetAt
|
||||
}
|
||||
${aliases.join("\n")}
|
||||
${[...aliases, ...originAliases].join("\n")}
|
||||
}\n${BATCH_PR_STATUS_FRAGMENT}`;
|
||||
}
|
||||
|
||||
@@ -1076,11 +1096,7 @@ interface InFlightCacheEntry {
|
||||
force: boolean;
|
||||
}
|
||||
|
||||
interface GitHubPollTarget {
|
||||
cwd: string;
|
||||
headRef: string;
|
||||
headSha?: string;
|
||||
headRepositoryOwner?: string;
|
||||
interface GitHubPollTarget extends CurrentPullRequestLookup {
|
||||
retainCount: number;
|
||||
/** Absolute due time on the shared poll grid; null while a poll is in flight. */
|
||||
nextDueAt: number | null;
|
||||
@@ -1364,12 +1380,7 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G
|
||||
});
|
||||
}
|
||||
|
||||
function getPollTargetKey(target: {
|
||||
cwd: string;
|
||||
headRef: string;
|
||||
headSha?: string;
|
||||
headRepositoryOwner?: string;
|
||||
}): string {
|
||||
function getPollTargetKey(target: CurrentPullRequestLookup): string {
|
||||
return buildCacheKey({
|
||||
cwd: target.cwd,
|
||||
method: "getCurrentPullRequestStatus",
|
||||
@@ -1377,18 +1388,17 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G
|
||||
headRef: target.headRef,
|
||||
headSha: target.headSha,
|
||||
headRepositoryOwner: target.headRepositoryOwner,
|
||||
currentBranch: target.currentBranch,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function updatePollTargetAfterSuccess(update: {
|
||||
cwd: string;
|
||||
headRef: string;
|
||||
headSha?: string;
|
||||
headRepositoryOwner?: string;
|
||||
status: CurrentPullRequestStatus | null;
|
||||
notify: boolean;
|
||||
}): void {
|
||||
function updatePollTargetAfterSuccess(
|
||||
update: CurrentPullRequestLookup & {
|
||||
status: CurrentPullRequestStatus | null;
|
||||
notify: boolean;
|
||||
},
|
||||
): void {
|
||||
const target = pollTargets.get(getPollTargetKey(update));
|
||||
if (!target) {
|
||||
return;
|
||||
@@ -1638,13 +1648,7 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G
|
||||
if (!firstEntry) {
|
||||
return;
|
||||
}
|
||||
const query = buildBatchPullRequestStatusQuery(
|
||||
addressedEntries.map((entry) => ({
|
||||
owner: entry.owner,
|
||||
name: entry.name,
|
||||
headRef: entry.target.headRef,
|
||||
})),
|
||||
);
|
||||
const query = buildBatchPullRequestStatusQuery(addressedEntries);
|
||||
const args = ["api", "graphql", "-f", `query=${query}`];
|
||||
const response = await loadGitHubPollBatchResponse({
|
||||
entries: addressedEntries,
|
||||
@@ -1760,6 +1764,18 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (
|
||||
isTerminalOnDefaultBranch(entry, node, repository.data, input.aliases[`origin${index}`])
|
||||
) {
|
||||
finalizeBatchPollTarget({
|
||||
entry,
|
||||
node: null,
|
||||
repository: repository.data,
|
||||
rollup: null,
|
||||
startedAt: input.startedAt,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
const frozenKey =
|
||||
node.state !== "OPEN" && node.headRefOid.length > 0
|
||||
? `${entry.owner}/${entry.name}#${node.number}@${node.headRefOid}`
|
||||
@@ -1786,6 +1802,22 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G
|
||||
return distribution;
|
||||
}
|
||||
|
||||
function isTerminalOnDefaultBranch(
|
||||
entry: GitHubBatchPollEntry,
|
||||
node: BatchPollPrNode,
|
||||
repository: BatchPollRepository,
|
||||
originAlias: unknown,
|
||||
): boolean {
|
||||
if (node.state === "OPEN") {
|
||||
return false;
|
||||
}
|
||||
const origin =
|
||||
entry.owner === entry.originOwner && entry.name === entry.originName
|
||||
? repository
|
||||
: GitHubDefaultBranchSchema.safeParse(originAlias).data;
|
||||
return isOnDefaultBranch(entry.target, origin?.defaultBranchRef?.name);
|
||||
}
|
||||
|
||||
function addressGitHubBatchEntry(entry: GitHubBatchPollEntry): GitHubBatchPollEntry {
|
||||
const redirect = pollRepositoryRedirects.get(batchRepositoryRedirectKey(entry));
|
||||
return redirect
|
||||
@@ -1963,25 +1995,14 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G
|
||||
);
|
||||
status = built ? { ...built, forgeSpecific: { forge: "github", ...facts } } : null;
|
||||
}
|
||||
const cacheKey = buildCacheKey({
|
||||
cwd: entry.target.cwd,
|
||||
method: "getCurrentPullRequestStatus",
|
||||
args: {
|
||||
headRef: entry.target.headRef,
|
||||
headSha: entry.target.headSha,
|
||||
headRepositoryOwner: entry.target.headRepositoryOwner,
|
||||
},
|
||||
});
|
||||
const cacheKey = getPollTargetKey(entry.target);
|
||||
// A direct or forced read can finish between this batch becoming due and
|
||||
// its checks query returning. Its cache write is newer than this cycle, so
|
||||
// converge on it instead of overwriting fresher data with the batch's.
|
||||
const existing = cache.get(cacheKey);
|
||||
if (existing && existing.expiresAt - ttlMs > input.startedAt) {
|
||||
updatePollTargetAfterSuccess({
|
||||
cwd: entry.target.cwd,
|
||||
headRef: entry.target.headRef,
|
||||
headSha: entry.target.headSha,
|
||||
headRepositoryOwner: entry.target.headRepositoryOwner,
|
||||
...entry.target,
|
||||
status: existing.value as CurrentPullRequestStatus | null,
|
||||
notify: true,
|
||||
});
|
||||
@@ -1991,10 +2012,7 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G
|
||||
// between polls reuse the batch result instead of spawning gh again.
|
||||
cache.set(cacheKey, { value: status, cwd: entry.target.cwd, expiresAt: deps.now() + ttlMs });
|
||||
updatePollTargetAfterSuccess({
|
||||
cwd: entry.target.cwd,
|
||||
headRef: entry.target.headRef,
|
||||
headSha: entry.target.headSha,
|
||||
headRepositoryOwner: entry.target.headRepositoryOwner,
|
||||
...entry.target,
|
||||
status,
|
||||
notify: true,
|
||||
});
|
||||
@@ -2007,6 +2025,7 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G
|
||||
headRef: target.headRef,
|
||||
headSha: target.headSha,
|
||||
headRepositoryOwner: target.headRepositoryOwner,
|
||||
currentBranch: target.currentBranch,
|
||||
reason: "self-heal-github",
|
||||
});
|
||||
} catch (error) {
|
||||
@@ -2173,14 +2192,17 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G
|
||||
headRef: input.headRef,
|
||||
headSha: input.headSha,
|
||||
headRepositoryOwner: input.headRepositoryOwner,
|
||||
currentBranch: input.currentBranch,
|
||||
},
|
||||
readOptions: input,
|
||||
load: async () => {
|
||||
const status = await resolveCurrentPullRequestView({
|
||||
const status = await loadCurrentPullRequestView({
|
||||
cwd: input.cwd,
|
||||
headRef: input.headRef,
|
||||
headSha: input.headSha,
|
||||
headRepositoryOwner: input.headRepositoryOwner,
|
||||
currentBranch: input.currentBranch,
|
||||
resolveOriginRepo: () => resolveRepoSlugCached(input.cwd),
|
||||
run,
|
||||
});
|
||||
return addCurrentPullRequestGithubFacts({ cwd: input.cwd, status, run });
|
||||
@@ -2191,6 +2213,7 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G
|
||||
headRef: input.headRef,
|
||||
headSha: input.headSha,
|
||||
headRepositoryOwner: input.headRepositoryOwner,
|
||||
currentBranch: input.currentBranch,
|
||||
status,
|
||||
notify: input.reason === "self-heal-github",
|
||||
});
|
||||
@@ -2603,6 +2626,7 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G
|
||||
headRef: input.headRef,
|
||||
headSha: input.headSha,
|
||||
headRepositoryOwner: input.headRepositoryOwner,
|
||||
currentBranch: input.currentBranch,
|
||||
retainCount: 0,
|
||||
nextDueAt: null,
|
||||
pollCycleStartedAt: null,
|
||||
@@ -2984,13 +3008,35 @@ function isGitHubRateLimitError(error: unknown): boolean {
|
||||
);
|
||||
}
|
||||
|
||||
async function resolveCurrentPullRequestView(options: {
|
||||
cwd: string;
|
||||
headRef: string;
|
||||
headSha?: string;
|
||||
headRepositoryOwner?: string;
|
||||
run: (args: string[], options: GitHubCommandRunnerOptions) => Promise<string>;
|
||||
}): Promise<CurrentPullRequestStatus | null> {
|
||||
async function loadCurrentPullRequestView(
|
||||
options: CurrentPullRequestLookup & {
|
||||
resolveOriginRepo(): Promise<string | null>;
|
||||
run: (args: string[], options: GitHubCommandRunnerOptions) => Promise<string>;
|
||||
},
|
||||
): Promise<CurrentPullRequestStatus | null> {
|
||||
let repoRead: ReturnType<typeof getGitHubRepoView> | undefined;
|
||||
const readRepo = () => (repoRead ??= getGitHubRepoView(options));
|
||||
const status = await resolveCurrentPullRequestView({ ...options, readRepo });
|
||||
if (!status || status.state === "open") {
|
||||
return status;
|
||||
}
|
||||
|
||||
const originRepo = await options.resolveOriginRepo();
|
||||
const repo = await repoRead;
|
||||
const repoName = repo?.owner?.login && repo.name ? `${repo.owner.login}/${repo.name}` : null;
|
||||
const origin =
|
||||
originRepo && originRepo.toLowerCase() !== repoName?.toLowerCase()
|
||||
? await getGitHubRepoView({ ...options, repo: originRepo })
|
||||
: await readRepo();
|
||||
return isOnDefaultBranch(options, origin?.defaultBranchRef?.name) ? null : status;
|
||||
}
|
||||
|
||||
async function resolveCurrentPullRequestView(
|
||||
options: CurrentPullRequestLookup & {
|
||||
readRepo(): Promise<z.infer<typeof GitHubRepoViewSchema> | null>;
|
||||
run: (args: string[], options: GitHubCommandRunnerOptions) => Promise<string>;
|
||||
},
|
||||
): Promise<CurrentPullRequestStatus | null> {
|
||||
const viewCandidate = await tryCurrentPullRequestView(options);
|
||||
const viewMatch = viewCandidate
|
||||
? pickPullRequestCandidate({
|
||||
@@ -3007,7 +3053,7 @@ async function resolveCurrentPullRequestView(options: {
|
||||
let headRepositoryOwner = options.headRepositoryOwner;
|
||||
|
||||
if (!headRepositoryOwner) {
|
||||
const repo = await getGitHubRepoView(options);
|
||||
const repo = await options.readRepo();
|
||||
const forkOwner = repo?.owner?.login;
|
||||
const parentOwner = repo?.parent?.owner?.login;
|
||||
const parentName = repo?.parent?.name;
|
||||
@@ -3282,7 +3328,7 @@ async function readGitHubRepoView(
|
||||
"view",
|
||||
...(options.repo ? [options.repo] : []),
|
||||
"--json",
|
||||
"owner,name,parent",
|
||||
"owner,name,parent,defaultBranchRef",
|
||||
];
|
||||
const stdout = await options.run(args, {
|
||||
cwd: options.cwd,
|
||||
|
||||
@@ -389,6 +389,26 @@ describe("createGitLabService", () => {
|
||||
expect(calls[1]).toEqual(["mr", "view", "270", "-F", "json"]);
|
||||
});
|
||||
|
||||
it("hides a historical MR on the project's default branch", async () => {
|
||||
const historical = { ...OPEN_MR, state: "merged", source_branch: "trunk" };
|
||||
const { service } = makeService((args) => {
|
||||
if (args[1] === "list") return ok(JSON.stringify([historical]));
|
||||
if (args[1] === "view") return ok(JSON.stringify(historical));
|
||||
if (args[0] === "api" && args[1] === "projects/example-group%2Fexample-project") {
|
||||
return ok(
|
||||
JSON.stringify({
|
||||
path_with_namespace: "example-group/example-project",
|
||||
default_branch: "trunk",
|
||||
}),
|
||||
);
|
||||
}
|
||||
return ok("{}");
|
||||
});
|
||||
await expect(
|
||||
service.getCurrentPullRequestStatus({ cwd: "/repo", headRef: "trunk" }),
|
||||
).resolves.toBeNull();
|
||||
});
|
||||
|
||||
it("keeps a merged MR when its remote head advances beyond the checkout", async () => {
|
||||
const stale = {
|
||||
...OPEN_MR,
|
||||
|
||||
@@ -16,6 +16,7 @@ import {
|
||||
compareTimelineItems,
|
||||
createUnavailableSearchResult,
|
||||
normalizeForgeSearchKinds,
|
||||
isOnDefaultBranch,
|
||||
parseOptionalTime,
|
||||
} from "./forge-service.js";
|
||||
import type {
|
||||
@@ -252,6 +253,7 @@ const GitLabApprovalsSchema = z
|
||||
const GitLabProjectSchema = z
|
||||
.object({
|
||||
path_with_namespace: z.string(),
|
||||
default_branch: z.string().nullish(),
|
||||
forked_from_project: z
|
||||
.object({ path_with_namespace: z.string().optional() })
|
||||
.nullable()
|
||||
@@ -1142,6 +1144,19 @@ export function createGitLabService(options: CreateGitLabServiceOptions = {}): F
|
||||
return issues.map(toIssueSummary);
|
||||
}
|
||||
|
||||
async function readOriginProject(cwd: string) {
|
||||
const remoteUrl = await resolveRemoteUrl(cwd);
|
||||
const projectPath = remoteUrl ? parseGitRemoteLocation(remoteUrl)?.path : null;
|
||||
if (!projectPath) {
|
||||
return null;
|
||||
}
|
||||
return runJson(
|
||||
["api", `projects/${encodeURIComponent(projectPath)}`],
|
||||
{ cwd: cwd },
|
||||
GitLabProjectSchema,
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
async isAuthenticated(input: { cwd: string } & ForgeReadOptions): Promise<boolean> {
|
||||
const glabPath = await resolveGlab();
|
||||
@@ -1162,17 +1177,8 @@ export function createGitLabService(options: CreateGitLabServiceOptions = {}): F
|
||||
},
|
||||
|
||||
async getReferenceRepository(input): Promise<string | null> {
|
||||
const remoteUrl = await resolveRemoteUrl(input.cwd);
|
||||
const projectPath = remoteUrl ? parseGitRemoteLocation(remoteUrl)?.path : null;
|
||||
if (!projectPath) {
|
||||
return null;
|
||||
}
|
||||
const project = await runJson(
|
||||
["api", `projects/${encodeURIComponent(projectPath)}`],
|
||||
{ cwd: input.cwd },
|
||||
GitLabProjectSchema,
|
||||
);
|
||||
return project.forked_from_project?.path_with_namespace ?? null;
|
||||
const project = await readOriginProject(input.cwd);
|
||||
return project?.forked_from_project?.path_with_namespace ?? null;
|
||||
},
|
||||
|
||||
async getCurrentPullRequestStatus(input): Promise<CurrentPullRequestStatus | null> {
|
||||
@@ -1181,6 +1187,12 @@ export function createGitLabService(options: CreateGitLabServiceOptions = {}): F
|
||||
if (!mr) {
|
||||
return null;
|
||||
}
|
||||
if (mapMergeRequestState(mr.state) !== "open") {
|
||||
const project = await readOriginProject(input.cwd).catch(() => null);
|
||||
if (isOnDefaultBranch(input, project?.default_branch)) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
const [approvals, pipelineChecks] = await Promise.all([
|
||||
fetchApprovals(input.cwd, mr),
|
||||
fetchPipelineChecks(input.cwd, mr),
|
||||
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
import { createRequire } from "node:module";
|
||||
import { access, readdir, rm } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { setTimeout as delay } from "node:timers/promises";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { ensurePrivateDirectory } from "../server/private-files.js";
|
||||
import { listTerminalWorkerRecords, terminalWorkerDirectory } from "./terminal-worker-record.js";
|
||||
@@ -193,6 +194,28 @@ export function prepareTerminalWorkerRuntime(input: {
|
||||
return entry;
|
||||
}
|
||||
|
||||
// Windows keeps a just-exited worker's files open for a moment, so a delete that fails with one
|
||||
// of these codes is retried for a short window. Each attempt is a single rm: rm's own maxRetries
|
||||
// repeats at every directory level, so a file that stays locked deep in node-pty would hold
|
||||
// daemon start and stop far past any window.
|
||||
const TRANSIENT_REMOVE_ERRORS = new Set(["EPERM", "EBUSY", "EACCES", "ENOTEMPTY"]);
|
||||
const TRANSIENT_REMOVE_WINDOW_MS = 3_000;
|
||||
const TRANSIENT_REMOVE_PAUSE_MS = 100;
|
||||
|
||||
async function removeCopy(directory: string): Promise<void> {
|
||||
const deadline = Date.now() + TRANSIENT_REMOVE_WINDOW_MS;
|
||||
for (;;) {
|
||||
try {
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
return;
|
||||
} catch (error) {
|
||||
const code = (error as NodeJS.ErrnoException).code;
|
||||
if (!code || !TRANSIENT_REMOVE_ERRORS.has(code) || Date.now() >= deadline) throw error;
|
||||
await delay(TRANSIENT_REMOVE_PAUSE_MS);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export interface PruneTerminalWorkerRuntimesResult {
|
||||
removed: string[];
|
||||
/** Copies that could not be deleted (a worker that just exited can still hold files on Windows). */
|
||||
@@ -236,7 +259,7 @@ export async function pruneTerminalWorkerRuntimes(
|
||||
)
|
||||
continue;
|
||||
try {
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
await removeCopy(directory);
|
||||
result.removed.push(directory);
|
||||
} catch (error) {
|
||||
result.failed.push({
|
||||
|
||||
@@ -178,6 +178,7 @@ function createPullRequestStatus(overrides?: Partial<CurrentPullRequestStatus>)
|
||||
|
||||
interface RequestedPullRequestTarget {
|
||||
headRef: string;
|
||||
currentBranch?: string;
|
||||
headSha?: string;
|
||||
headRepositoryOwner?: string;
|
||||
}
|
||||
@@ -194,6 +195,7 @@ function createGitHubServiceRecordingPullRequestTargets(
|
||||
github.getCurrentPullRequestStatus = async (request) => {
|
||||
options.requestedTargets.push({
|
||||
headRef: request.headRef,
|
||||
...(request.currentBranch ? { currentBranch: request.currentBranch } : {}),
|
||||
...(request.headSha ? { headSha: request.headSha } : {}),
|
||||
...(request.headRepositoryOwner ? { headRepositoryOwner: request.headRepositoryOwner } : {}),
|
||||
});
|
||||
@@ -3460,7 +3462,7 @@ const x = 1;
|
||||
{ paseoHome },
|
||||
);
|
||||
|
||||
expect(requestedTargets).toEqual([factsTarget]);
|
||||
expect(requestedTargets).toEqual([{ ...factsTarget, currentBranch: "tender-parrot" }]);
|
||||
});
|
||||
|
||||
it("uses the tracked fork branch for PR worktree status lookup", async () => {
|
||||
@@ -3490,7 +3492,11 @@ const x = 1;
|
||||
const status = await getPullRequestStatus(repoDir, github);
|
||||
|
||||
expect(requestedTargets).toEqual([
|
||||
expect.objectContaining({ headRef: "main", headRepositoryOwner: "chethanuk" }),
|
||||
expect.objectContaining({
|
||||
headRef: "main",
|
||||
currentBranch: "chethanuk/main",
|
||||
headRepositoryOwner: "chethanuk",
|
||||
}),
|
||||
]);
|
||||
expect(status.status?.number).toBe(345);
|
||||
expect(status.status?.headRefName).toBe("main");
|
||||
@@ -3521,6 +3527,20 @@ const x = 1;
|
||||
expect(status.status?.state).toBe("closed");
|
||||
});
|
||||
|
||||
it("looks up PR status again when switching branches at the same commit", async () => {
|
||||
execFileSync("git", ["checkout", "-b", "feature"], { cwd: repoDir });
|
||||
const requestedTargets: RequestedPullRequestTarget[] = [];
|
||||
const forge = createGitHubServiceRecordingPullRequestTargets({ requestedTargets });
|
||||
|
||||
const feature = await getPullRequestStatus(repoDir, forge);
|
||||
execFileSync("git", ["checkout", "main"], { cwd: repoDir });
|
||||
const main = await getPullRequestStatus(repoDir, forge);
|
||||
|
||||
expect(feature.status?.headRefName).toBe("feature");
|
||||
expect(main.status?.headRefName).toBe("main");
|
||||
expect(requestedTargets.map(({ headRef }) => headRef)).toEqual(["feature", "main"]);
|
||||
});
|
||||
|
||||
it("caches PR status results for duplicate lookups", async () => {
|
||||
execFileSync("git", ["checkout", "-b", "feature"], { cwd: repoDir });
|
||||
execFileSync("git", ["remote", "add", "origin", "https://github.com/getpaseo/paseo.git"], {
|
||||
|
||||
@@ -153,8 +153,12 @@ function createShortstatCache(ttlMs: number) {
|
||||
});
|
||||
}
|
||||
|
||||
function getPullRequestStatusCacheKey(cwd: string, headSha: string | null): string {
|
||||
return `${resolve(cwd)}\u0000${headSha ?? ""}`;
|
||||
function getPullRequestStatusCacheKey(
|
||||
cwd: string,
|
||||
currentBranch: string | null,
|
||||
headSha: string | null,
|
||||
): string {
|
||||
return `${resolve(cwd)}\u0000${currentBranch ?? ""}\u0000${headSha ?? ""}`;
|
||||
}
|
||||
|
||||
function rememberPullRequestStatus(cacheKey: string, status: PullRequestStatusResult): void {
|
||||
@@ -4437,8 +4441,11 @@ export async function getPullRequestStatus(
|
||||
options?: CheckoutReadCacheOptions,
|
||||
context?: CheckoutContext,
|
||||
): Promise<PullRequestStatusResult> {
|
||||
const headSha = await getCurrentHeadSha(cwd, context);
|
||||
const cacheKey = getPullRequestStatusCacheKey(cwd, headSha);
|
||||
const [headSha, head] = await Promise.all([
|
||||
getCurrentHeadSha(cwd, context),
|
||||
context?.facts?.isGit ? context.facts.currentBranch : getCurrentBranch(cwd, context),
|
||||
]);
|
||||
const cacheKey = getPullRequestStatusCacheKey(cwd, head, headSha);
|
||||
if (!options?.force) {
|
||||
const cached = pullRequestStatusCache.get(cacheKey);
|
||||
if (cached) {
|
||||
@@ -4451,7 +4458,7 @@ export async function getPullRequestStatus(
|
||||
}
|
||||
}
|
||||
|
||||
const lookup = getPullRequestStatusUncached(cwd, forgeService, options, context, headSha)
|
||||
const lookup = getPullRequestStatusUncached(cwd, forgeService, head, options, context, headSha)
|
||||
.then((status) => {
|
||||
pullRequestStatusCache.set(cacheKey, status);
|
||||
rememberPullRequestStatus(cacheKey, status);
|
||||
@@ -4477,6 +4484,7 @@ export async function getPullRequestStatus(
|
||||
async function getPullRequestStatusUncached(
|
||||
cwd: string,
|
||||
forgeService: ForgeService,
|
||||
head: string | null,
|
||||
options?: CheckoutReadCacheOptions,
|
||||
context?: CheckoutContext,
|
||||
headSha?: string | null,
|
||||
@@ -4486,18 +4494,16 @@ async function getPullRequestStatusUncached(
|
||||
if (!context?.facts?.isGit) {
|
||||
await requireGitRepo(cwd, context);
|
||||
}
|
||||
const head = context?.facts?.isGit
|
||||
? context.facts.currentBranch
|
||||
: await getCurrentBranch(cwd, context);
|
||||
if (!head) {
|
||||
return buildPullRequestStatusResult(null, "no_remote");
|
||||
}
|
||||
try {
|
||||
const resolvedLookupTarget = await resolvePullRequestStatusLookupTarget(cwd, head, context);
|
||||
const lookupTarget =
|
||||
headSha && !resolvedLookupTarget.headSha
|
||||
? { ...resolvedLookupTarget, headSha }
|
||||
: resolvedLookupTarget;
|
||||
const lookupTarget = {
|
||||
...resolvedLookupTarget,
|
||||
...(headSha && !resolvedLookupTarget.headSha ? { headSha } : {}),
|
||||
...(head !== resolvedLookupTarget.headRef ? { currentBranch: head } : {}),
|
||||
};
|
||||
let status: CurrentPullRequestStatus | null;
|
||||
if (options?.force) {
|
||||
const reason = options.reason;
|
||||
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
PaseoConfigRawSchema,
|
||||
getWorktreeSetupCommands,
|
||||
getWorktreeTeardownCommands,
|
||||
getWorktreeTeardownTimeoutMs,
|
||||
} from "./worktree.js";
|
||||
import {
|
||||
readPaseoConfigForEdit,
|
||||
@@ -295,6 +296,34 @@ describe("paseo config file substrate", () => {
|
||||
expect(await getWorktreeTeardownCommands(tempDir)).toEqual(["npm run clean", "npm run reset"]);
|
||||
});
|
||||
|
||||
it("reads the teardown time limit and defaults to one minute", async () => {
|
||||
expect(await getWorktreeTeardownTimeoutMs(tempDir)).toBe(60_000);
|
||||
|
||||
for (const teardownTimeoutMs of [1, 300_000, 2_147_483_647]) {
|
||||
writeFileSync(
|
||||
join(tempDir, "paseo.json"),
|
||||
JSON.stringify({ worktree: { teardownTimeoutMs } }),
|
||||
);
|
||||
expect(await getWorktreeTeardownTimeoutMs(tempDir)).toBe(teardownTimeoutMs);
|
||||
}
|
||||
});
|
||||
|
||||
it.each([0, -1000, 1500.5, 2_147_483_648, "90000", null, true, { ms: 90_000 }])(
|
||||
"falls back to the default teardown time limit for %j and keeps the commands",
|
||||
async (teardownTimeoutMs) => {
|
||||
const config = { worktree: { teardown: "npm run clean", teardownTimeoutMs } };
|
||||
writeFileSync(join(tempDir, "paseo.json"), JSON.stringify(config));
|
||||
|
||||
expect(await getWorktreeTeardownTimeoutMs(tempDir)).toBe(60_000);
|
||||
expect(await getWorktreeTeardownCommands(tempDir)).toEqual(["npm run clean"]);
|
||||
expect(await readPaseoConfigForEdit(tempDir)).toEqual({
|
||||
ok: true,
|
||||
config,
|
||||
revision: await statPaseoConfigPath(tempDir),
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it("writes pretty JSON with a trailing newline when revision matches", async () => {
|
||||
writeFileSync(join(tempDir, "paseo.json"), JSON.stringify({ worktree: { setup: "old" } }));
|
||||
const expectedRevision = await statPaseoConfigPath(tempDir);
|
||||
|
||||
@@ -5,17 +5,8 @@ import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const execFileMock = vi.hoisted(() => vi.fn());
|
||||
const spawnProcessMock = vi.hoisted(() => vi.fn());
|
||||
|
||||
vi.mock("child_process", async () => {
|
||||
const actual = await vi.importActual<typeof import("child_process")>("child_process");
|
||||
return {
|
||||
...actual,
|
||||
execFile: execFileMock,
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("./spawn.js", async () => {
|
||||
const actual = await vi.importActual<typeof import("./spawn.js")>("./spawn.js");
|
||||
return {
|
||||
@@ -42,19 +33,7 @@ describe("worktree shell selection", () => {
|
||||
const originalPlatform = process.platform;
|
||||
|
||||
beforeEach(() => {
|
||||
execFileMock.mockReset();
|
||||
spawnProcessMock.mockReset();
|
||||
execFileMock.mockImplementation(
|
||||
(
|
||||
_file: string,
|
||||
_args: string[],
|
||||
_options: unknown,
|
||||
callback?: (error: Error | null, stdout: string, stderr: string) => void,
|
||||
) => {
|
||||
callback?.(null, "", "");
|
||||
return {};
|
||||
},
|
||||
);
|
||||
spawnProcessMock.mockImplementation(createSpawnChildStub);
|
||||
});
|
||||
|
||||
@@ -94,8 +73,8 @@ describe("worktree shell selection", () => {
|
||||
branchName: "main",
|
||||
});
|
||||
|
||||
expect(execFileMock).toHaveBeenCalledTimes(1);
|
||||
expect(execFileMock).toHaveBeenCalledWith(
|
||||
expect(spawnProcessMock).toHaveBeenCalledTimes(1);
|
||||
expect(spawnProcessMock).toHaveBeenCalledWith(
|
||||
"powershell",
|
||||
[
|
||||
"-NoProfile",
|
||||
@@ -105,11 +84,10 @@ describe("worktree shell selection", () => {
|
||||
"-Command",
|
||||
"Write-Output 'teardown'",
|
||||
],
|
||||
expect.objectContaining({ cwd: worktreePath }),
|
||||
expect.any(Function),
|
||||
expect.objectContaining({ cwd: worktreePath, shell: false }),
|
||||
);
|
||||
const execOptions = execFileMock.mock.calls[0]?.[2] as { env?: NodeJS.ProcessEnv };
|
||||
expect(execOptions.env?.BASH_ENV).toBeUndefined();
|
||||
const spawnOptions = spawnProcessMock.mock.calls[0]?.[2] as { env?: NodeJS.ProcessEnv };
|
||||
expect(spawnOptions.env?.BASH_ENV).toBeUndefined();
|
||||
} finally {
|
||||
if (originalBashEnv === undefined) {
|
||||
delete process.env.BASH_ENV;
|
||||
|
||||
@@ -1406,6 +1406,32 @@ describe.skipIf(isPlatform("win32"))("worktree POSIX-only", () => {
|
||||
rmSync(tempDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it("keeps an otherwise unreachable detached commit after deleting the worktree", async () => {
|
||||
const result = await createWorktreePrimitive({
|
||||
cwd: repoDir,
|
||||
worktreeSlug: "keep-commit",
|
||||
source: { kind: "branch-off", baseBranch: "main", branchName: "feature/keep-commit" },
|
||||
paseoHome,
|
||||
});
|
||||
execFileSync("git", ["checkout", "--detach"], { cwd: result.worktreePath });
|
||||
writeFileSync(join(result.worktreePath, "file.txt"), "detached change\n");
|
||||
execFileSync("git", ["add", "file.txt"], { cwd: result.worktreePath });
|
||||
execFileSync("git", ["-c", "commit.gpgsign=false", "commit", "-m", "detached"], {
|
||||
cwd: result.worktreePath,
|
||||
});
|
||||
const commit = execFileSync("git", ["rev-parse", "HEAD"], {
|
||||
cwd: result.worktreePath,
|
||||
encoding: "utf8",
|
||||
}).trim();
|
||||
|
||||
await deletePaseoWorktree({ cwd: repoDir, worktreePath: result.worktreePath, paseoHome });
|
||||
execFileSync("git", ["reflog", "expire", "--expire=now", "--all"], { cwd: repoDir });
|
||||
execFileSync("git", ["gc", "--prune=now"], { cwd: repoDir });
|
||||
expect(
|
||||
execFileSync("git", ["cat-file", "-t", commit], { cwd: repoDir, encoding: "utf8" }).trim(),
|
||||
).toBe("commit");
|
||||
});
|
||||
|
||||
it("places, owns, lists, and deletes a worktree outside the legacy root", async () => {
|
||||
// Sibling layout: <repo-parent>/wt-<slug>
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@ import {
|
||||
createWorktree as createWorktreePrimitive,
|
||||
deriveWorktreeProjectHash,
|
||||
deletePaseoWorktree,
|
||||
readWorktreeHead,
|
||||
isPaseoOwnedWorktreeCwd,
|
||||
mapWorkspaceCwdToWorktree,
|
||||
runWorktreeTeardownCommands,
|
||||
@@ -189,6 +190,30 @@ describe("paseo worktree manager", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("retains bounded diagnostic text per teardown output stream", async () => {
|
||||
const limit = 1024 * 1024;
|
||||
writeFileSync(
|
||||
join(repoDir, "paseo.json"),
|
||||
JSON.stringify({
|
||||
worktree: {
|
||||
teardown: `node -e "process.stdout.write('x'.repeat(${2 * limit})); process.stderr.write('y'.repeat(${2 * limit}))"`,
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
const [result] = await runWorktreeTeardownCommands({
|
||||
worktreePath: repoDir,
|
||||
repoRootPath: repoDir,
|
||||
branchName: "main",
|
||||
});
|
||||
|
||||
expect({
|
||||
exitCode: result.exitCode,
|
||||
stdoutLength: result.stdout.length,
|
||||
stderrLength: result.stderr.length,
|
||||
}).toEqual({ exitCode: 0, stdoutLength: limit, stderrLength: limit });
|
||||
});
|
||||
|
||||
it("rejects paths that are not under the paseo worktrees root", async () => {
|
||||
const outsidePath = join(tempDir, "outside-paseo-home");
|
||||
mkdirSync(outsidePath, { recursive: true });
|
||||
@@ -302,6 +327,29 @@ describe("paseo worktree manager", () => {
|
||||
expect(existsSync(created.worktreePath)).toBe(false);
|
||||
});
|
||||
|
||||
it("does not read a parent repository's HEAD when the worktree has no .git", async () => {
|
||||
const directory = join(repoDir, "missing-worktree");
|
||||
mkdirSync(directory);
|
||||
await expect(readWorktreeHead(directory)).resolves.toBeNull();
|
||||
});
|
||||
|
||||
it("keeps a worktree when writing its retention ref fails", async () => {
|
||||
const created = await createLegacyWorktreeForTest({
|
||||
branchName: "ref-write-failure",
|
||||
cwd: repoDir,
|
||||
baseBranch: "main",
|
||||
worktreeSlug: "ref-write-failure",
|
||||
paseoHome,
|
||||
});
|
||||
mkdirSync(join(repoDir, ".git", "refs", "paseo"), { recursive: true });
|
||||
writeFileSync(join(repoDir, ".git", "refs", "paseo", "kept-commits"), "blocked\n");
|
||||
|
||||
await expect(
|
||||
deletePaseoWorktree({ cwd: repoDir, worktreePath: created.worktreePath, paseoHome }),
|
||||
).rejects.toThrow();
|
||||
expect(existsSync(created.worktreePath)).toBe(true);
|
||||
});
|
||||
|
||||
it("deletes a worktree when Git reports its source through native and long path spellings", async () => {
|
||||
const created = await createLegacyWorktreeForTest({
|
||||
branchName: "identity-delete",
|
||||
|
||||
@@ -146,6 +146,13 @@ export class WorktreeSetupError extends Error {
|
||||
|
||||
export type WorktreeTeardownCommandResult = WorktreeSetupCommandResult;
|
||||
|
||||
// paseo.json can change this with worktree.teardownTimeoutMs. Archive waits for teardown before it
|
||||
// answers, and the app stops waiting for an archive answer after 60 seconds
|
||||
// (DEFAULT_SESSION_RPC_TIMEOUT_MS in the client). A teardown that runs to this limit, or to a longer
|
||||
// one, answers after the app has reported the archive as failed.
|
||||
const DEFAULT_WORKTREE_TEARDOWN_TIMEOUT_MS = 60_000;
|
||||
const MAX_WORKTREE_TEARDOWN_OUTPUT_CHARS_PER_STREAM = 1024 * 1024;
|
||||
|
||||
export class WorktreeTeardownError extends Error {
|
||||
readonly results: WorktreeTeardownCommandResult[];
|
||||
|
||||
@@ -188,6 +195,7 @@ export type WorktreeSource =
|
||||
| { kind: "branch-off"; baseBranch: string; branchName: string }
|
||||
| { kind: "checkout-branch"; branchName: string }
|
||||
| { kind: "restore"; branchName: string; baseRef: string | null }
|
||||
| { kind: "restore-commit"; commit: string; baseRef: string }
|
||||
| { kind: "restore-from-base"; baseRef: string; branchName: string }
|
||||
| {
|
||||
kind: "checkout-change-request";
|
||||
@@ -280,6 +288,13 @@ export async function getWorktreeTeardownCommands(repoRoot: string): Promise<str
|
||||
return (await readPaseoConfigOrThrow(repoRoot))?.worktree?.teardown ?? [];
|
||||
}
|
||||
|
||||
export async function getWorktreeTeardownTimeoutMs(repoRoot: string): Promise<number> {
|
||||
return (
|
||||
(await readPaseoConfigOrThrow(repoRoot))?.worktree?.teardownTimeoutMs ??
|
||||
DEFAULT_WORKTREE_TEARDOWN_TIMEOUT_MS
|
||||
);
|
||||
}
|
||||
|
||||
export async function getWorktreeTerminalSpecs(
|
||||
repoRoot: string,
|
||||
): Promise<WorktreeTerminalConfig[]> {
|
||||
@@ -448,12 +463,14 @@ async function execSetupCommandStreamed(options: {
|
||||
index: number;
|
||||
total: number;
|
||||
signal?: AbortSignal;
|
||||
maxOutputCharsPerStream?: number;
|
||||
onEvent?: (event: WorktreeSetupCommandProgressEvent) => void;
|
||||
}): Promise<WorktreeSetupCommandResult> {
|
||||
return new Promise((resolvePromise) => {
|
||||
const startedAt = Date.now();
|
||||
const stdoutChunks: string[] = [];
|
||||
const stderrChunks: string[] = [];
|
||||
const outputChunks: Record<"stdout" | "stderr", string[]> = { stdout: [], stderr: [] };
|
||||
const outputLimit = options.maxOutputCharsPerStream ?? Infinity;
|
||||
const remainingOutputChars = { stdout: outputLimit, stderr: outputLimit };
|
||||
let settled = false;
|
||||
let termination: Promise<unknown> | null = null;
|
||||
|
||||
@@ -462,10 +479,10 @@ async function execSetupCommandStreamed(options: {
|
||||
if (!text) {
|
||||
return;
|
||||
}
|
||||
if (stream === "stdout") {
|
||||
stdoutChunks.push(text);
|
||||
} else {
|
||||
stderrChunks.push(text);
|
||||
const retainedText = text.slice(0, remainingOutputChars[stream]);
|
||||
if (retainedText) {
|
||||
outputChunks[stream].push(retainedText);
|
||||
remainingOutputChars[stream] -= retainedText.length;
|
||||
}
|
||||
options.onEvent?.({
|
||||
type: "output",
|
||||
@@ -484,12 +501,17 @@ async function execSetupCommandStreamed(options: {
|
||||
}
|
||||
settled = true;
|
||||
options.signal?.removeEventListener("abort", abort);
|
||||
await termination;
|
||||
if (termination) {
|
||||
await termination;
|
||||
// A descendant can keep these pipes open after the shell exits.
|
||||
child.stdout?.destroy();
|
||||
child.stderr?.destroy();
|
||||
}
|
||||
const result: WorktreeSetupCommandResult = {
|
||||
command: options.command,
|
||||
cwd: options.cwd,
|
||||
stdout: stdoutChunks.join(""),
|
||||
stderr: stderrChunks.join(""),
|
||||
stdout: outputChunks.stdout.join(""),
|
||||
stderr: outputChunks.stderr.join(""),
|
||||
exitCode,
|
||||
durationMs: Date.now() - startedAt,
|
||||
};
|
||||
@@ -528,6 +550,7 @@ async function execSetupCommandStreamed(options: {
|
||||
gracefulTimeoutMs: 1000,
|
||||
forceTimeoutMs: 1000,
|
||||
});
|
||||
void finish(null);
|
||||
};
|
||||
if (options.signal?.aborted) {
|
||||
abort();
|
||||
@@ -767,17 +790,26 @@ export async function runWorktreeTeardownCommands(options: {
|
||||
}),
|
||||
);
|
||||
|
||||
// One deadline covers every command. Reaching it counts as failure and keeps the worktree.
|
||||
const timeoutMs = await getWorktreeTeardownTimeoutMs(teardownCwd);
|
||||
const deadline = AbortSignal.timeout(timeoutMs);
|
||||
const results: WorktreeTeardownCommandResult[] = [];
|
||||
for (const cmd of teardownCommands) {
|
||||
const result = await execSetupCommand(cmd, {
|
||||
for (const [index, cmd] of teardownCommands.entries()) {
|
||||
const result = await execSetupCommandStreamed({
|
||||
command: cmd,
|
||||
cwd: teardownCwd,
|
||||
env: teardownEnv,
|
||||
index: index + 1,
|
||||
total: teardownCommands.length,
|
||||
signal: deadline,
|
||||
maxOutputCharsPerStream: MAX_WORKTREE_TEARDOWN_OUTPUT_CHARS_PER_STREAM,
|
||||
});
|
||||
results.push(result);
|
||||
|
||||
if (result.exitCode !== 0) {
|
||||
const reason = deadline.aborted ? `Timed out after ${timeoutMs / 1000}s` : result.stderr;
|
||||
throw new WorktreeTeardownError(
|
||||
`Worktree teardown command failed: ${cmd}\n${result.stderr}`.trim(),
|
||||
`Worktree teardown command failed: ${cmd}\n${reason}`.trim(),
|
||||
results,
|
||||
);
|
||||
}
|
||||
@@ -1153,6 +1185,32 @@ async function assertWorktreeBelongsToRepo(cwd: string, worktreePath: string): P
|
||||
}
|
||||
}
|
||||
|
||||
export async function readWorktreeHead(worktreePath: string): Promise<string | null> {
|
||||
if (!(await pathExists(join(worktreePath, ".git")))) return null;
|
||||
try {
|
||||
const { stdout } = await runGitCommand(["rev-parse", "--verify", "HEAD^{commit}"], {
|
||||
cwd: worktreePath,
|
||||
});
|
||||
return stdout.trim();
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export async function readWorktreeHeadReference(worktreePath: string): Promise<string | null> {
|
||||
if (!(await pathExists(join(worktreePath, ".git")))) return null;
|
||||
try {
|
||||
const result = await runGitCommand(["symbolic-ref", "--quiet", "HEAD"], {
|
||||
cwd: worktreePath,
|
||||
acceptExitCodes: [0, 1],
|
||||
});
|
||||
if (result.exitCode === 0) return result.stdout.trim();
|
||||
return readWorktreeHead(worktreePath);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export async function deletePaseoWorktree({
|
||||
cwd,
|
||||
worktreePath,
|
||||
@@ -1208,6 +1266,12 @@ export async function deletePaseoWorktree({
|
||||
teardownCwd,
|
||||
});
|
||||
}
|
||||
const commit = await readWorktreeHead(resolvedWorktree);
|
||||
if (commit) {
|
||||
await runGitCommand(["update-ref", `refs/paseo/kept-commits/${commit}`, commit], {
|
||||
cwd: resolvedWorktree,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (cwd) {
|
||||
@@ -1361,14 +1425,22 @@ export async function resolveDefaultWorktreePath(
|
||||
/**
|
||||
* Create a git worktree with proper naming conventions
|
||||
*/
|
||||
export const createWorktree = async ({
|
||||
export function createWorktree(
|
||||
options: CreateWorktreeOptions & { source: Exclude<WorktreeSource, { kind: "restore-commit" }> },
|
||||
): Promise<CreatedWorktree>;
|
||||
export function createWorktree(
|
||||
options: CreateWorktreeOptions,
|
||||
): Promise<Omit<CreatedWorktree, "branchName"> & { branchName: string | null }>;
|
||||
export async function createWorktree({
|
||||
cwd,
|
||||
source,
|
||||
worktreeSlug,
|
||||
paseoHome,
|
||||
worktreesRoot,
|
||||
worktreePath: explicitWorktreePath,
|
||||
}: CreateWorktreeOptions): Promise<CreatedWorktree> => {
|
||||
}: CreateWorktreeOptions): Promise<
|
||||
Omit<CreatedWorktree, "branchName"> & { branchName: string | null }
|
||||
> {
|
||||
const branchesBefore =
|
||||
source.kind === "checkout-branch" ||
|
||||
source.kind === "checkout-change-request" ||
|
||||
@@ -1394,14 +1466,14 @@ export const createWorktree = async ({
|
||||
});
|
||||
worktreePath = await normalizePathForOwnership(worktreePath);
|
||||
|
||||
if (sourcePlan.pushRemote) {
|
||||
if (sourcePlan.pushRemote && sourcePlan.branchName) {
|
||||
await configureWorktreePushRemote({
|
||||
cwd,
|
||||
branchName: sourcePlan.branchName,
|
||||
remote: sourcePlan.pushRemote,
|
||||
});
|
||||
}
|
||||
if (sourcePlan.trackingRemote) {
|
||||
if (sourcePlan.trackingRemote && sourcePlan.branchName) {
|
||||
await configureWorktreeTrackingRemote({
|
||||
cwd,
|
||||
branchName: sourcePlan.branchName,
|
||||
@@ -1434,7 +1506,7 @@ export const createWorktree = async ({
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
interface ResolveWorktreeSourcePlanOptions {
|
||||
cwd: string;
|
||||
@@ -1443,7 +1515,7 @@ interface ResolveWorktreeSourcePlanOptions {
|
||||
}
|
||||
|
||||
interface WorktreeSourcePlan {
|
||||
branchName: string;
|
||||
branchName: string | null;
|
||||
// Display name and exact ref are two different facts. The name cannot round-trip to a
|
||||
// commit — "main" resolves local-first even when the worktree was cut from a fork's
|
||||
// upstream — so comparisons and actions read the ref and the UI reads the name.
|
||||
@@ -1492,6 +1564,26 @@ async function resolveRestoredWorktreeSourcePlan(
|
||||
};
|
||||
}
|
||||
|
||||
async function resolveRestoredCommitSourcePlan(
|
||||
cwd: string,
|
||||
source: Extract<WorktreeSource, { kind: "restore-commit" }>,
|
||||
): Promise<WorktreeSourcePlan> {
|
||||
let exactBase: string | undefined;
|
||||
if (isQualifiedRef(source.baseRef)) {
|
||||
try {
|
||||
exactBase = await resolveBaseBranchForWorktree(cwd, source.baseRef);
|
||||
} catch {
|
||||
// Restore the saved commit even when its comparison ref no longer exists.
|
||||
}
|
||||
}
|
||||
return {
|
||||
branchName: null,
|
||||
metadataBaseRefName: normalizeRequiredBaseBranch(source.baseRef),
|
||||
...(exactBase ? { metadataBaseRef: exactBase } : {}),
|
||||
addArguments: ["--detach", source.commit],
|
||||
};
|
||||
}
|
||||
|
||||
async function resolveRestoredWorktreeFromBasePlan(
|
||||
cwd: string,
|
||||
source: Extract<WorktreeSource, { kind: "restore-from-base" }>,
|
||||
@@ -1544,6 +1636,8 @@ async function resolveWorktreeSourcePlan({
|
||||
return resolveBranchOffWorktreeSourcePlan(cwd, source, desiredSlug);
|
||||
case "restore":
|
||||
return resolveRestoredWorktreeSourcePlan(cwd, source);
|
||||
case "restore-commit":
|
||||
return resolveRestoredCommitSourcePlan(cwd, source);
|
||||
case "restore-from-base":
|
||||
return resolveRestoredWorktreeFromBasePlan(cwd, source);
|
||||
case "checkout-branch": {
|
||||
|
||||
@@ -0,0 +1,291 @@
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { existsSync } from "node:fs";
|
||||
import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { dirname, join } from "node:path";
|
||||
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
||||
import { copyWorktreeIncludes } from "./copy.js";
|
||||
|
||||
let root: string;
|
||||
let source: string;
|
||||
let worktree: string;
|
||||
|
||||
async function writeSource(files: Record<string, string>): Promise<void> {
|
||||
for (const [file, contents] of Object.entries(files)) {
|
||||
await mkdir(dirname(join(source, file)), { recursive: true });
|
||||
await writeFile(join(source, file), contents);
|
||||
}
|
||||
}
|
||||
|
||||
// Total directories Git visits while listing files, read from its trace2 events.
|
||||
async function directoriesVisited(run: () => Promise<unknown>): Promise<number> {
|
||||
const trace = join(root, "trace.json");
|
||||
process.env.GIT_TRACE2_EVENT = trace;
|
||||
try {
|
||||
await run();
|
||||
} finally {
|
||||
delete process.env.GIT_TRACE2_EVENT;
|
||||
}
|
||||
return (await readFile(trace, "utf8"))
|
||||
.split("\n")
|
||||
.filter(Boolean)
|
||||
.map((line) => JSON.parse(line) as { event: string; key?: string; value?: string })
|
||||
.filter((event) => event.event === "data" && event.key === "directories-visited")
|
||||
.reduce((total, event) => total + Number(event.value), 0);
|
||||
}
|
||||
|
||||
async function copied(): Promise<string[]> {
|
||||
const result = await copyWorktreeIncludes(worktree, source);
|
||||
if (result.kind !== "copied") throw new Error(`expected a copy, got ${result.kind}`);
|
||||
return [...result.copied].sort();
|
||||
}
|
||||
|
||||
beforeEach(async () => {
|
||||
root = await mkdtemp(join(tmpdir(), "worktree-include-"));
|
||||
source = join(root, "source");
|
||||
worktree = join(root, "worktree");
|
||||
await mkdir(source);
|
||||
await mkdir(worktree);
|
||||
execFileSync("git", ["init", "-q", source]);
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await rm(root, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
describe("copyWorktreeIncludes", () => {
|
||||
it("does not search inside an ignored directory that no pattern names", async () => {
|
||||
await writeSource({
|
||||
".gitignore": "node_modules/\n.env\n",
|
||||
".worktreeinclude": ".env\n",
|
||||
".env": "SECRET=root",
|
||||
"apps/web/.env": "SECRET=web",
|
||||
"node_modules/pkg/.env": "SECRET=package",
|
||||
});
|
||||
|
||||
expect(await copied()).toEqual([".env", "apps/web/.env"]);
|
||||
expect(existsSync(join(worktree, "node_modules"))).toBe(false);
|
||||
});
|
||||
|
||||
it("searches inside ignored directories for a pattern that starts with **/", async () => {
|
||||
await writeSource({
|
||||
".gitignore": "node_modules/\n.env\n",
|
||||
".worktreeinclude": "**/.env\n",
|
||||
".env": "SECRET=root",
|
||||
"node_modules/pkg/.env": "SECRET=package",
|
||||
});
|
||||
|
||||
expect(await copied()).toEqual([".env", "node_modules/pkg/.env"]);
|
||||
});
|
||||
|
||||
it("copies a file in an untracked directory once when a **/ pattern also searches it", async () => {
|
||||
await writeSource({
|
||||
".gitignore": ".env\n",
|
||||
".worktreeinclude": "**/.env\nnew-package/.env\n",
|
||||
"new-package/.env": "SECRET=new",
|
||||
});
|
||||
|
||||
const result = await copyWorktreeIncludes(worktree, source);
|
||||
expect(result).toEqual({
|
||||
kind: "copied",
|
||||
copied: ["new-package/.env"],
|
||||
skipped: [],
|
||||
});
|
||||
});
|
||||
|
||||
it("copies a path a pattern names inside an ignored directory", async () => {
|
||||
await writeSource({
|
||||
".gitignore": "node_modules/\n",
|
||||
".worktreeinclude": "node_modules/pkg/.env\n",
|
||||
"node_modules/pkg/.env": "SECRET=package",
|
||||
"node_modules/other/.env": "SECRET=other",
|
||||
});
|
||||
|
||||
expect(await copied()).toEqual(["node_modules/pkg/.env"]);
|
||||
});
|
||||
|
||||
it("copies an ignored directory that a pattern names", async () => {
|
||||
await writeSource({
|
||||
".gitignore": ".secrets/\nbuild/\n",
|
||||
".worktreeinclude": ".secrets/\n",
|
||||
".secrets/a.key": "a",
|
||||
".secrets/nested/b.key": "b",
|
||||
"build/out.js": "built",
|
||||
});
|
||||
|
||||
expect(await copied()).toEqual([".secrets/a.key", ".secrets/nested/b.key"]);
|
||||
});
|
||||
|
||||
it("searches inside an ignored directory for a path a pattern names", async () => {
|
||||
await writeSource({
|
||||
".gitignore": "config/\n",
|
||||
".worktreeinclude": "config/*.local.json\n!config/production.local.json\n",
|
||||
"config/dev.local.json": "dev",
|
||||
"config/production.local.json": "production",
|
||||
"config/defaults.json": "defaults",
|
||||
});
|
||||
|
||||
expect(await copied()).toEqual(["config/dev.local.json"]);
|
||||
expect(await readFile(join(worktree, "config/dev.local.json"), "utf8")).toBe("dev");
|
||||
});
|
||||
|
||||
it("copies ignored files inside an untracked directory", async () => {
|
||||
await writeSource({
|
||||
".gitignore": ".env\n",
|
||||
".worktreeinclude": ".env\n",
|
||||
"new-package/.env": "SECRET=new",
|
||||
});
|
||||
|
||||
expect(await copied()).toEqual(["new-package/.env"]);
|
||||
});
|
||||
|
||||
it("copies nothing that is tracked or not ignored", async () => {
|
||||
await writeSource({
|
||||
".gitignore": ".env\n",
|
||||
".worktreeinclude": ".env\nnotes.txt\n",
|
||||
"notes.txt": "not ignored",
|
||||
});
|
||||
|
||||
expect(await copied()).toEqual([]);
|
||||
});
|
||||
|
||||
it("searches only the path a glob-free pattern names directly inside an ignored directory", async () => {
|
||||
const packages: Record<string, string> = {};
|
||||
for (let i = 0; i < 20; i++) packages[`node_modules/pkg${i}/lib/index.js`] = "code";
|
||||
await writeSource({
|
||||
".gitignore": "node_modules/\n",
|
||||
".worktreeinclude": "node_modules/.cache\n",
|
||||
"node_modules/.cache/state.json": "cache",
|
||||
...packages,
|
||||
});
|
||||
|
||||
let result: Awaited<ReturnType<typeof copyWorktreeIncludes>> | undefined;
|
||||
const visited = await directoriesVisited(async () => {
|
||||
result = await copyWorktreeIncludes(worktree, source);
|
||||
});
|
||||
|
||||
expect(result).toEqual({
|
||||
kind: "copied",
|
||||
copied: ["node_modules/.cache/state.json"],
|
||||
skipped: [],
|
||||
});
|
||||
expect(visited).toBeLessThan(10);
|
||||
});
|
||||
|
||||
it.skipIf(process.platform === "win32")(
|
||||
"copies includes when an ignored file is named like a Git pathspec",
|
||||
async () => {
|
||||
await writeSource({
|
||||
".gitignore": "*.log\n.env\n",
|
||||
".worktreeinclude": ".env\n",
|
||||
".env": "SECRET=root",
|
||||
":(oops.log": "log",
|
||||
":!c.log": "log",
|
||||
});
|
||||
|
||||
expect(await copied()).toEqual([".env"]);
|
||||
},
|
||||
);
|
||||
|
||||
it("ignores exclude patterns from the user's git template", async () => {
|
||||
const template = join(root, "template");
|
||||
await mkdir(join(template, "info"), { recursive: true });
|
||||
await writeFile(join(template, "info", "exclude"), "*.log\n");
|
||||
await writeSource({
|
||||
".gitignore": "*.log\n.env\n",
|
||||
".worktreeinclude": ".env\n",
|
||||
".env": "SECRET=root",
|
||||
"debug.log": "log",
|
||||
});
|
||||
|
||||
process.env.GIT_TEMPLATE_DIR = template;
|
||||
try {
|
||||
expect(await copied()).toEqual([".env"]);
|
||||
} finally {
|
||||
delete process.env.GIT_TEMPLATE_DIR;
|
||||
}
|
||||
});
|
||||
|
||||
it("does not search an ignored directory deeper than a pattern without ** can reach", async () => {
|
||||
const packages: Record<string, string> = {};
|
||||
for (let i = 0; i < 20; i++) packages[`apps/web/node_modules/pkg${i}/lib/index.js`] = "code";
|
||||
await writeSource({
|
||||
".gitignore": "node_modules/\n.env\n",
|
||||
".worktreeinclude": "apps/*/.env\n",
|
||||
"apps/web/.env": "SECRET=web",
|
||||
...packages,
|
||||
});
|
||||
|
||||
let result: Awaited<ReturnType<typeof copyWorktreeIncludes>> | undefined;
|
||||
const visited = await directoriesVisited(async () => {
|
||||
result = await copyWorktreeIncludes(worktree, source);
|
||||
});
|
||||
|
||||
expect(result).toEqual({ kind: "copied", copied: ["apps/web/.env"], skipped: [] });
|
||||
expect(visited).toBeLessThan(10);
|
||||
});
|
||||
|
||||
it("reads the first pattern after a UTF-8 byte order mark", async () => {
|
||||
await writeSource({
|
||||
".gitignore": "node_modules/\n",
|
||||
".worktreeinclude": "\uFEFFnode_modules/.cache/\n",
|
||||
"node_modules/.cache/state.json": "cache",
|
||||
});
|
||||
|
||||
expect(await copied()).toEqual(["node_modules/.cache/state.json"]);
|
||||
});
|
||||
|
||||
it("matches patterns case-insensitively when the source repo ignores case", async () => {
|
||||
execFileSync("git", ["-C", source, "config", "core.ignoreCase", "true"]);
|
||||
await writeSource({
|
||||
".gitignore": ".env\nconfig/\n",
|
||||
".worktreeinclude": ".ENV\nCONFIG/a.json\n",
|
||||
".env": "SECRET=root",
|
||||
"config/a.json": "a",
|
||||
});
|
||||
|
||||
expect(await copied()).toEqual([".env", "config/a.json"]);
|
||||
});
|
||||
|
||||
it("searches a pattern's path in the case it has on disk when the source repo ignores case", async () => {
|
||||
execFileSync("git", ["-C", source, "config", "core.ignoreCase", "true"]);
|
||||
await writeSource({
|
||||
".gitignore": "Config/\nÉTÉ/\n",
|
||||
".worktreeinclude": "config/a.json\nÉTÉ/sub/.env\n",
|
||||
"Config/a.json": "a",
|
||||
"ÉTÉ/sub/.env": "SECRET=summer",
|
||||
});
|
||||
|
||||
expect(await copied()).toEqual(["Config/a.json", "ÉTÉ/sub/.env"]);
|
||||
});
|
||||
|
||||
// Each searched folder is one argument to Git. Windows caps a command line at 32,767
|
||||
// characters and Linux at 2 MB, so each platform gets enough folders to exceed its own
|
||||
// limit, with names short enough for Windows paths.
|
||||
it("searches more ignored folders than fit on one command line", async () => {
|
||||
const folders = process.platform === "win32" ? 300 : 15_000;
|
||||
const name = (i: number) => `${"x".repeat(150)}${i}`;
|
||||
await writeSource({
|
||||
".gitignore": "x*/\n.env\n",
|
||||
".worktreeinclude": "**/.env\n",
|
||||
[`${name(folders - 1)}/.env`]: "SECRET=last",
|
||||
});
|
||||
for (let i = 0; i < folders - 1; i++) await mkdir(join(source, name(i)));
|
||||
await Promise.all(
|
||||
Array.from({ length: folders - 1 }, (_, i) => writeFile(join(source, name(i), "a"), "")),
|
||||
);
|
||||
|
||||
expect(await copied()).toEqual([`${name(folders - 1)}/.env`]);
|
||||
}, 60_000);
|
||||
|
||||
it("copies ignored files inside an untracked directory a pattern names", async () => {
|
||||
await writeSource({
|
||||
".gitignore": ".env\n",
|
||||
".worktreeinclude": "newdir/\n",
|
||||
"newdir/.env": "SECRET=new",
|
||||
"newdir/notes.txt": "untracked",
|
||||
});
|
||||
|
||||
expect(await copied()).toEqual(["newdir/.env"]);
|
||||
});
|
||||
});
|
||||
@@ -2,7 +2,8 @@
|
||||
// Copyright (c) 2026 Carlos Precioso.
|
||||
import { execFile } from "node:child_process";
|
||||
import { constants, existsSync } from "node:fs";
|
||||
import { copyFile, mkdir } from "node:fs/promises";
|
||||
import { copyFile, mkdir, mkdtemp, readFile, rm } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { dirname, join } from "node:path";
|
||||
import { promisify } from "node:util";
|
||||
|
||||
@@ -22,37 +23,33 @@ async function git(cwd: string, args: string[], input?: string): Promise<string>
|
||||
return stdout;
|
||||
}
|
||||
|
||||
async function gitAllowExit1(cwd: string, args: string[], input: string): Promise<string> {
|
||||
// `git check-ignore --stdin` reads each path as a pathspec, so a name such as `:(x`
|
||||
// would be parsed as pathspec magic. A `./` prefix keeps every path literal.
|
||||
async function checkIgnore(cwd: string, args: string[], paths: string[]): Promise<string[]> {
|
||||
const input = paths.map((path) => `./${path}\0`).join("");
|
||||
let output: string;
|
||||
try {
|
||||
return await git(cwd, args, input);
|
||||
output = await git(cwd, [...args, "check-ignore", "--stdin", "-z"], input);
|
||||
} catch (error) {
|
||||
// `git check-ignore` exits 1 when nothing matched.
|
||||
if ((error as { code?: number }).code === 1) return "";
|
||||
if ((error as { code?: number }).code === 1) return [];
|
||||
throw error;
|
||||
}
|
||||
return splitNul(output).map((path) => path.replace(/^\.\//, ""));
|
||||
}
|
||||
|
||||
const splitNul = (s: string) => s.split("\0").filter(Boolean);
|
||||
const isDirectory = (entry: string) => entry.endsWith("/");
|
||||
|
||||
// Copy files that match .worktreeinclude (gitignore syntax)
|
||||
// AND are gitignored, so tracked files are never touched.
|
||||
export async function copyWorktreeIncludes(worktree: string, source: string): Promise<CopyResult> {
|
||||
if (!existsSync(join(source, INCLUDE_FILE))) return { kind: "no-include-file" };
|
||||
|
||||
const matches = splitNul(
|
||||
await git(source, [
|
||||
"ls-files",
|
||||
"--others",
|
||||
"--ignored",
|
||||
`--exclude-from=${INCLUDE_FILE}`,
|
||||
"-z",
|
||||
]),
|
||||
);
|
||||
const matches = await findIncludedFiles(source);
|
||||
if (matches.length === 0) return { kind: "copied", copied: [], skipped: [] };
|
||||
|
||||
const ignored = splitNul(
|
||||
await gitAllowExit1(source, ["check-ignore", "--stdin", "-z"], matches.join("\0") + "\0"),
|
||||
);
|
||||
const ignored = await checkIgnore(source, [], matches);
|
||||
|
||||
const copied: string[] = [];
|
||||
const skipped: string[] = [];
|
||||
@@ -69,3 +66,152 @@ export async function copyWorktreeIncludes(worktree: string, source: string): Pr
|
||||
}
|
||||
return { kind: "copied", copied, skipped };
|
||||
}
|
||||
|
||||
// Git lists a directory it ignores as a whole, such as node_modules/, as one entry.
|
||||
// Only directories that a pattern matches or names a path inside are searched, and
|
||||
// only as deep as the pattern names, so creating a worktree does not walk every file
|
||||
// in large ignored trees.
|
||||
async function findIncludedFiles(source: string): Promise<string[]> {
|
||||
const ignored = splitNul(
|
||||
await git(source, [
|
||||
"ls-files",
|
||||
"--others",
|
||||
"--ignored",
|
||||
"--exclude-standard",
|
||||
"--directory",
|
||||
"-z",
|
||||
]),
|
||||
);
|
||||
if (ignored.length === 0) return [];
|
||||
|
||||
const ignoreCase = await sourceIgnoresCase(source);
|
||||
const patterns = parsePatterns(await readFile(join(source, INCLUDE_FILE), "utf8"));
|
||||
const matched = new Set(await matchIncludePatterns(source, ignored, ignoreCase));
|
||||
const files = ignored.filter((entry) => !isDirectory(entry) && matched.has(entry));
|
||||
const searched = new Set<string>();
|
||||
// Git also lists an untracked folder that holds ignored entries, which are listed on
|
||||
// their own, so only folders Git ignores as a whole are searched.
|
||||
const directories = await checkIgnore(source, [], ignored.filter(isDirectory));
|
||||
for (const directory of directories) {
|
||||
if (matched.has(directory)) {
|
||||
searched.add(directory);
|
||||
continue;
|
||||
}
|
||||
for (const pattern of patterns) {
|
||||
const inside = searchedPathInside(pattern, directory, ignoreCase);
|
||||
if (inside !== null) searched.add(inside);
|
||||
}
|
||||
}
|
||||
if (searched.size === 0) return files;
|
||||
|
||||
const pathspecs = [...searched].map(
|
||||
(path) => `:(${ignoreCase ? "literal,icase" : "literal"})${path}`,
|
||||
);
|
||||
const inside: string[] = [];
|
||||
for (const batch of commandLineBatches(pathspecs)) {
|
||||
const listed = await git(source, [
|
||||
"ls-files",
|
||||
"--others",
|
||||
"--ignored",
|
||||
`--exclude-from=${INCLUDE_FILE}`,
|
||||
"-z",
|
||||
"--",
|
||||
...batch,
|
||||
]);
|
||||
inside.push(...splitNul(listed));
|
||||
}
|
||||
return [...new Set([...files, ...inside])];
|
||||
}
|
||||
|
||||
// Windows caps a command line at 32,767 characters, so a pattern such as `**/.env` in a
|
||||
// repo with many ignored folders searches them over several Git calls.
|
||||
const COMMAND_LINE_BATCH_CHARS = 16_000;
|
||||
|
||||
function commandLineBatches(args: string[]): string[][] {
|
||||
const batches: string[][] = [];
|
||||
let batch: string[] = [];
|
||||
let length = 0;
|
||||
for (const arg of args) {
|
||||
if (batch.length > 0 && length + arg.length + 1 > COMMAND_LINE_BATCH_CHARS) {
|
||||
batches.push(batch);
|
||||
batch = [];
|
||||
length = 0;
|
||||
}
|
||||
batch.push(arg);
|
||||
length += arg.length + 1;
|
||||
}
|
||||
if (batch.length > 0) batches.push(batch);
|
||||
return batches;
|
||||
}
|
||||
|
||||
// Match entries against .worktreeinclude alone, in a scratch repository where no other
|
||||
// ignore rules apply. Directory entries keep their trailing slash, so directory
|
||||
// patterns match them without anything on disk.
|
||||
async function matchIncludePatterns(
|
||||
source: string,
|
||||
entries: string[],
|
||||
ignoreCase: boolean,
|
||||
): Promise<string[]> {
|
||||
const scratch = await mkdtemp(join(tmpdir(), "paseo-worktree-include-"));
|
||||
try {
|
||||
// An empty template keeps the user's template `info/exclude` out of the matching.
|
||||
await git(scratch, ["init", "-q", "--template="]);
|
||||
return await checkIgnore(
|
||||
scratch,
|
||||
[
|
||||
"-c",
|
||||
`core.excludesFile=${join(source, INCLUDE_FILE)}`,
|
||||
"-c",
|
||||
`core.ignoreCase=${ignoreCase}`,
|
||||
],
|
||||
entries,
|
||||
);
|
||||
} finally {
|
||||
await rm(scratch, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
// The scratch repository would otherwise take core.ignoreCase from the temp folder.
|
||||
async function sourceIgnoresCase(source: string): Promise<boolean> {
|
||||
try {
|
||||
return (await git(source, ["config", "--type=bool", "core.ignoreCase"])).trim() === "true";
|
||||
} catch {
|
||||
// `git config` exits 1 when the key is unset.
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function parsePatterns(contents: string): string[] {
|
||||
// Git skips a leading UTF-8 byte order mark in exclude files.
|
||||
return contents
|
||||
.replace(/^\uFEFF/, "")
|
||||
.split(/\r?\n/)
|
||||
.map((line) => line.trimEnd())
|
||||
.filter((line) => line !== "" && !line.startsWith("#") && !line.startsWith("!"));
|
||||
}
|
||||
|
||||
// A pattern with a slash before its end is anchored to the checkout root, so it can
|
||||
// name a path inside `directory` when its literal start and the directory overlap.
|
||||
// Without `**`, a pattern matches paths of exactly its own depth, so a directory that
|
||||
// deep or deeper can hold no match below it. Returns the narrowest path to search: the
|
||||
// whole path when the pattern has no glob, else the folder before its first glob, or
|
||||
// `directory` itself when the path ends above it.
|
||||
function searchedPathInside(
|
||||
pattern: string,
|
||||
rawDirectory: string,
|
||||
ignoreCase: boolean,
|
||||
): string | null {
|
||||
// Git folds only ASCII letters when it ignores case.
|
||||
const fold = (text: string) =>
|
||||
ignoreCase ? text.replace(/[A-Z]+/g, (letters) => letters.toLowerCase()) : text;
|
||||
const path = fold(pattern.replace(/^\//, ""));
|
||||
const directory = fold(rawDirectory);
|
||||
const depth = (text: string) => text.replace(/\/$/, "").split("/").length;
|
||||
if (depth(path) < 2) return null;
|
||||
if (!path.includes("**") && depth(directory) >= depth(path)) return null;
|
||||
const globAt = path.search(/[*?[\\]/);
|
||||
const literal = globAt === -1 ? path : path.slice(0, globAt);
|
||||
if (!literal.startsWith(directory) && !directory.startsWith(literal)) return null;
|
||||
const searched = globAt === -1 ? literal : literal.slice(0, literal.lastIndexOf("/") + 1);
|
||||
return searched.length > directory.length ? searched : directory;
|
||||
}
|
||||
|
||||
@@ -122,6 +122,19 @@ Both fields accept a multiline shell script or an array of commands; commands ru
|
||||
|
||||
Commands run with the worktree as `cwd`. Use `$PASEO_SOURCE_CHECKOUT_PATH` to reach files in the original checkout (untracked config, local caches, etc).
|
||||
|
||||
Teardown commands share a one minute limit. Set `teardownTimeoutMs` to change it, in milliseconds:
|
||||
|
||||
```json
|
||||
{
|
||||
"worktree": {
|
||||
"teardown": "docker compose down",
|
||||
"teardownTimeoutMs": 300000
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
At the limit, Paseo tries to stop the command and its child processes and stops waiting for output. If teardown fails or reaches the limit, the workspace still archives and the worktree stays on disk. `teardownTimeoutMs` accepts whole numbers from 1 to 2147483647. Other values use the default.
|
||||
|
||||
## Scripts and services
|
||||
|
||||
`scripts` are named commands you can run inside a worktree on demand. Mark one as a _service_ and Paseo supervises it as a long-running process, assigns it a port, and routes HTTP traffic to it through the daemon's reverse proxy.
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user