Compare commits

..
Author SHA1 Message Date
paseo-bot[bot] d35d0a0ee3 Remove clean worktrees with initialized submodules 2026-11-30 10:57:26 +00:00
paseo-bot[bot] c8739bdf75 fix(archive): keep worktrees with uncommitted changes
Archive used forced Git removal after workspace teardown, even when a file appeared after a clean status check. Check the worktree after teardown and preserve it unless the caller explicitly requests forced removal.
2026-11-30 10:34:49 +00:00
35 changed files with 488 additions and 557 deletions
@@ -1,89 +0,0 @@
# Online client replacement: timeline recovery
Verified on macOS arm64 with Node 22.20.0, Chromium 145 (Playwright), and a real isolated daemon. Replies use the deterministic test provider; no external AI API is involved.
## Reproduction
1. Open two chats on one host and return to the first.
2. Delay the active connection's real pong frames by 1 second, forwarding all real traffic, and wait for a measured liveness RTT.
3. Add another direct endpoint for the same daemon.
4. Advance the browser clock in 10-second steps. Each step waits for real delayed heartbeat replies and the public probe-cycle completion barrier, including replacement handshakes. The production selector and its timer constants are unchanged.
5. Verify that every observed host snapshot stays online with a client, then confirm exactly one client-generation change to the faster endpoint.
6. Require the Reconnecting alert to disappear within 3 seconds and verify a new message in the visible chat.
7. Commit a message to the hidden second chat before reopening it. Verify that message is recovered, then verify another live message.
The two paths are localhost and 127.0.0.1 to the same daemon. The test does not force host state or replace a private client field. It controls browser time, not the daemon clock or real socket responses. Subscription assertions require the needed agents without requiring all other agents to be absent; exact matching remains the shared helper's default. The test has a 180-second timeout and a bounded clock-step budget allowing one candidate backoff. Observers, handles, timers, and scenario data are cleaned up even on failure.
## Before: exact final test source
Temporarily remove only the production `sync.setConnected(...)` seed, run the final regression, and restore the source in a `finally` block. The host remains online and changes to generation 2, but Reconnecting does not settle:
```text
Error: expect(locator).toHaveCount(expected) failed
Locator: getByRole('alert').filter({ hasText: 'Reconnecting' })
Expected: 0
Received: 1
Timeout: 3000ms
1 failed
```
The frame below is extracted without modification from that final RED trace while the assertion was waiting, before fixture cleanup.
![Before: Reconnecting remains after online replacement](before.jpeg)
## After
Restore the production seed without changing the test files, then run:
```sh
npm run test:e2e --workspace=@getpaseo/app -- \
e2e/browser/viewed-agent-timelines.spec.ts \
--grep 'online connection replacement|visible chat reports updating until reconnect' \
--workers=1
```
```text
✓ an online connection replacement keeps every open chat synchronized (1.6m)
✓ a visible chat reports updating until reconnect catch-up completes (35.9s)
2 passed (2.3m)
```
The online replacement case previously took 4.8 minutes with wall-clock probe waits. The final controlled-clock run takes 1.6 minutes. [Recorded hashes](red-green.json) confirm both test files are identical between final RED and GREEN and the production source was restored exactly.
![After: hidden history recovers and both chats receive messages](after.png)
## Other checks
```sh
npm run typecheck
npm run lint -- packages/app/e2e/browser/viewed-agent-timelines.spec.ts packages/app/e2e/support/helpers/timeline-delivery.ts
npm run format
```
Whole-workspace typecheck exited 0. Changed-file lint reported `Found 0 warnings and 0 errors.` Formatting passed.
The original runtime fix is unchanged by this test follow-up. Its previous native validation remains: both unmodified and fixed renderers exported with `PASEO_WEB_PLATFORM=electron npm exec -- expo export --platform web`; server dependencies and desktop main built through repository scripts; both packaged locally with `electron-builder --config electron-builder.yml --publish never --mac --arm64 --dir -c.mac.notarize=false`, with certificate discovery disabled.
The existing `packages/desktop/e2e/packaged-app-smoke.js --app <built-app>` passed for both packages with fresh temporary user data/daemon homes and loopback ports:
```text
Packaged desktop smoke: real app renderer and preload bridge loaded
Packaged desktop smoke: renderer-started desktop daemon reported running
Packaged desktop smoke: every built-in plugin started
Packaged desktop smoke: running bundled CLI shim daemon status
Packaged desktop smoke: creating terminal through bundled CLI shim
Packaged desktop smoke: terminal hook command completed
Packaged desktop smoke passed: real renderer and preload loaded; renderer-started desktop daemon;
CLI shim daemon status and terminal smoke succeeded
```
The final summary omits ephemeral PID/listen values. The native smoke establishes packaged startup and terminal functionality, not native reconnect coverage.
## Coverage limits
- Web: real browser/daemon regression, with controlled browser scheduling, before and after.
- macOS desktop: prior arm64 packaging and native startup/CLI/terminal smoke of the unchanged runtime fix.
- iOS, Android, Windows desktop, Linux desktop: not tested.
- External relay transport and a real provider turn: not tested by this regression.
- The test requires eventual history recovery; it does not change the product's hidden-chat subscription policy or prohibit every transient toast frame.
- These are local results. No full-suite or GitHub CI pass is claimed.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 128 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 57 KiB

@@ -1,18 +0,0 @@
{
"production_source_restored": true,
"test_sha256": {
"packages/app/e2e/browser/viewed-agent-timelines.spec.ts": "1857d0ca187648d8377557cd82428a64546530795cf884c7474e921a1118c003",
"packages/app/e2e/support/helpers/timeline-delivery.ts": "23d0adb9f92daac6d0841d584abb7aa272a2981861d7d211c8213e98a9af90da"
},
"red": {
"result": "expected failure",
"assertion": "Reconnecting alert expected 0, received 1",
"timeout_ms": 3000
},
"green": {
"passed": 2,
"online_replacement_duration": "1.6m",
"ordinary_reconnect_duration": "35.9s",
"total_duration": "2.3m"
}
}
@@ -3,7 +3,6 @@ import { buildHostAgentDetailRoute } from "@/utils/host-routes";
import { test } from "../support/fixtures";
import { seedWorkspace, type SeedDaemonClient } from "../support/helpers/seed-client";
import { getServerId } from "../support/helpers/server-id";
import { getE2EDaemonPort } from "../support/helpers/daemon-port";
import { observeTimelineSubscriptions } from "../support/helpers/timeline-delivery";
import { waitForWorkspaceTabsVisible } from "../support/helpers/workspace-tabs";
import { selectWorkspaceInSidebar } from "../support/helpers/sidebar";
@@ -255,226 +254,7 @@ async function expectCurrentChatWithoutCatchUp(page: Page, message: string) {
await expect(page.getByRole("alert").filter({ hasText: "Updating messages" })).toHaveCount(0);
}
async function delayActiveDaemonPongs(page: Page, port: string) {
let deliveredPongs = 0;
let inFlightPings = 0;
const delayedPongs = new Set<ReturnType<typeof setTimeout>>();
await page.routeWebSocket(
(url) => url.hostname === "localhost" && url.port === port,
(socket) => {
const server = socket.connectToServer();
socket.onMessage((message) => {
if (typeof message === "string" && JSON.parse(message).type === "ping") inFlightPings += 1;
server.send(message);
});
server.onMessage((message) => {
if (typeof message === "string" && JSON.parse(message).type === "pong") {
const timer = setTimeout(() => {
delayedPongs.delete(timer);
socket.send(message);
deliveredPongs += 1;
inFlightPings -= 1;
}, 1_000);
delayedPongs.add(timer);
} else {
socket.send(message);
}
});
},
);
return {
delivered: () => deliveredPongs,
settled: () => inFlightPings === 0 && delayedPongs.size === 0,
dispose: () => {
for (const timer of delayedPongs) clearTimeout(timer);
},
};
}
async function readActiveLivenessRtt(page: Page): Promise<number> {
return page.evaluate((serverId) => {
const runtime = Reflect.get(globalThis, "__paseoHostRuntimeStore") as {
getClient(id: string): { getLastLivenessRttMs(): number | null } | null;
};
return runtime.getClient(serverId)?.getLastLivenessRttMs() ?? 0;
}, getServerId());
}
async function readHostConnection(page: Page) {
return page.evaluate((serverId) => {
const runtime = Reflect.get(globalThis, "__paseoHostRuntimeStore") as {
getSnapshot(id: string): {
clientGeneration: number;
connectionStatus: string;
activeConnectionId: string;
};
};
const snapshot = runtime.getSnapshot(serverId);
return {
generation: snapshot.clientGeneration,
status: snapshot.connectionStatus,
connection: snapshot.activeConnectionId,
};
}, getServerId());
}
async function settleHostProbeCycle(page: Page): Promise<void> {
await page.evaluate(async (serverId) => {
const runtime = Reflect.get(globalThis, "__paseoHostRuntimeStore") as {
runProbeCycleNow(id: string): Promise<void>;
};
// Joins any in-flight cycle through its final replacement handshake.
await runtime.runProbeCycleNow(serverId);
}, getServerId());
}
async function observeContinuousHostConnection(page: Page) {
const observation = await page.evaluateHandle((serverId) => {
const runtime = Reflect.get(globalThis, "__paseoHostRuntimeStore") as {
getSnapshot(id: string): { connectionStatus: string; client: unknown } | null;
subscribe(id: string, listener: () => void): () => void;
};
const connected: boolean[] = [];
const record = () => {
const snapshot = runtime.getSnapshot(serverId);
connected.push(snapshot?.connectionStatus === "online" && snapshot.client !== null);
};
record();
const unsubscribe = runtime.subscribe(serverId, record);
return {
stop() {
unsubscribe();
return connected;
},
};
}, getServerId());
let stopped: Promise<boolean[]> | null = null;
return {
stop() {
stopped ??= observation
.evaluate((recorder) => recorder.stop())
.finally(() => observation.dispose());
return stopped;
},
};
}
async function advanceToOnlineReplacement(
page: Page,
delayedPongs: Awaited<ReturnType<typeof delayActiveDaemonPongs>>,
beforeGeneration: number,
) {
// Advance scheduling, not the sockets: settle real heartbeat and probe replies
// between hops, including the replacement handshake, without altering production timers.
for (let step = 0; step < 60; step += 1) {
if ((await readHostConnection(page)).generation !== beforeGeneration) break;
await expect.poll(delayedPongs.settled, { timeout: 10_000 }).toBe(true);
await settleHostProbeCycle(page);
const pongsBefore = delayedPongs.delivered();
await page.clock.fastForward(10_000);
await expect
.poll(
async () =>
(await readHostConnection(page)).generation !== beforeGeneration ||
delayedPongs.delivered() > pongsBefore,
{ timeout: 10_000 },
)
.toBe(true);
await settleHostProbeCycle(page);
}
}
test.describe("Viewed agent timelines", () => {
test("an online connection replacement keeps every open chat synchronized", async ({
page,
}, testInfo) => {
test.setTimeout(180_000);
await page.clock.install();
const port = getE2EDaemonPort();
const delayedEndpoint = `localhost:${port}`;
const fasterEndpoint = `127.0.0.1:${port}`;
const delayedPongs = await delayActiveDaemonPongs(page, port);
const subscriptions = observeTimelineSubscriptions(page);
const scenario = await seedViewedTimelineScenario();
let connectionObservation:
| Awaited<ReturnType<typeof observeContinuousHostConnection>>
| undefined;
try {
await commitMessage(scenario, scenario.firstAgentId, "BEFORE_CONNECTION_REPLACEMENT");
await openAgent(page, scenario, scenario.firstAgentId);
await selectAgent(page, "Second viewed chat");
await selectAgent(page, "First viewed chat");
await subscriptions.waitForSubscribedAgents([scenario.firstAgentId, scenario.secondAgentId]);
await expectReconnectingToastGone(page);
// The adaptive selector needs an RTT from the active socket, not only its startup probe.
await expect.poll(delayedPongs.delivered, { timeout: 30_000 }).toBeGreaterThan(1);
await expect
.poll(() => readActiveLivenessRtt(page), { timeout: 30_000 })
.toBeGreaterThanOrEqual(800);
// Add another real route to the same daemon. Delaying only the active route's real
// pong frames gives the ordinary adaptive selector three consistently faster probes.
// No host state is forced offline and no client or timeline owner is replaced by the test.
connectionObservation = await observeContinuousHostConnection(page);
const beforeGeneration = await page.evaluate(
async ({ serverId, endpoint, activeEndpoint }) => {
const runtime = Reflect.get(globalThis, "__paseoHostRuntimeStore") as {
getSnapshot(id: string): {
clientGeneration: number;
connectionStatus: string;
activeConnectionId: string;
};
upsertDirectConnection(input: { serverId: string; endpoint: string }): Promise<unknown>;
};
const before = runtime.getSnapshot(serverId);
if (
before.connectionStatus !== "online" ||
before.activeConnectionId !== `direct:${activeEndpoint}`
) {
throw new Error("Expected the initial real connection to be online");
}
await runtime.upsertDirectConnection({ serverId, endpoint });
return before.clientGeneration;
},
{ serverId: getServerId(), endpoint: fasterEndpoint, activeEndpoint: delayedEndpoint },
);
subscriptions.reset();
await advanceToOnlineReplacement(page, delayedPongs, beforeGeneration);
await expect
.poll(() => readHostConnection(page), { timeout: 3_000 })
.toEqual({
generation: beforeGeneration + 1,
status: "online",
connection: `direct:${fasterEndpoint}`,
});
expect(await connectionObservation.stop()).not.toContain(false);
await expectReconnectingToastGone(page, { timeout: 3_000 });
await page.screenshot({
path: testInfo.outputPath("after-online-connection-replacement.png"),
});
await subscriptions.waitForSubscribedAgents([scenario.firstAgentId], { match: "includes" });
await commitMessage(scenario, scenario.firstAgentId, "FIRST_CHAT_AFTER_REPLACEMENT");
await expect(page.getByText("FIRST_CHAT_AFTER_REPLACEMENT", { exact: true })).toBeVisible();
await commitMessage(scenario, scenario.secondAgentId, "SECOND_CHAT_WHILE_HIDDEN");
await selectAgent(page, "Second viewed chat");
await expectReconnectingToastGone(page, { timeout: 3_000 });
await expect(page.getByText("SECOND_CHAT_WHILE_HIDDEN", { exact: true })).toBeVisible();
await subscriptions.waitForSubscribedAgents([scenario.firstAgentId, scenario.secondAgentId], {
match: "includes",
});
await commitMessage(scenario, scenario.secondAgentId, "SECOND_CHAT_AFTER_REPLACEMENT");
await expect(page.getByText("SECOND_CHAT_AFTER_REPLACEMENT", { exact: true })).toBeVisible();
await page.screenshot({ path: testInfo.outputPath("both-chats-synchronized.png") });
} finally {
try {
await connectionObservation?.stop();
} finally {
delayedPongs.dispose();
await scenario.cleanup();
}
}
});
test("a reloaded layout subscribes only the chat it restores into", async ({ page }) => {
test.setTimeout(120_000);
const subscriptions = observeTimelineSubscriptions(page);
@@ -9,7 +9,6 @@ interface SessionMessage {
interface TimelineSubscriptionWaitOptions {
timeout?: number;
match?: "exact" | "includes";
}
function readSessionMessage(message: WebSocketMessage): SessionMessage | null {
@@ -57,7 +56,7 @@ export function observeTimelineSubscriptions(page: Page) {
.poll(() => acknowledgedAgentIds?.slice().sort() ?? null, {
timeout: options.timeout ?? 15_000,
})
.toEqual(options.match === "includes" ? expect.arrayContaining(expected) : expected);
.toEqual(expected);
},
};
}
@@ -366,8 +366,6 @@ function SessionProviderInternal({ children, serverId, client }: SessionProvider
viewedTimelineSyncRef.current = sync;
setViewedTimelineSync(serverId, sync);
sync.setActive(getIsAppVisible(appStateRef.current));
// An online client replacement leaves isConnected unchanged, so seed each new owner.
sync.setConnected(client.getConnectionState().status === "connected");
const stopObservingOpenChats = observeOpenWorkspaceAgentIds(serverId, (agentIds) =>
sync.replaceOpenTabAgentIds(agentIds),
);
@@ -100,12 +100,14 @@ export async function archiveSelectedWorkspaces(input: {
}
const riskyWorkspaces: WorktreeArchiveConfirmationInput[] = [];
const dirtyWorktrees = new Set<SidebarWorkspaceEntry>();
const worktrees = resolved.filter((item) => item.entry.workspaceKind === "worktree");
if (worktrees.length > 0) {
try {
const risks = await Promise.all(
worktrees.map(async ({ entry, client }) => {
const risk = await deps.readWorktreeRisk(client, entry.workspaceDirectory);
if (risk.isDirty) dirtyWorktrees.add(entry);
return {
workspaceName: entry.name,
diffStat: entry.diffStat,
@@ -162,6 +164,7 @@ export async function archiveSelectedWorkspaces(input: {
return {
client,
workspace,
force: dirtyWorktrees.has(entry) || undefined,
onArchiveCommitted: () => deps.purgeWorkspaceState(workspace),
};
}),
@@ -175,7 +178,11 @@ export async function archiveSelectedWorkspaces(input: {
...legacy.map(async ({ entry, client }) => {
const workspace = { serverId: entry.serverId, workspaceId: entry.workspaceId };
try {
await deps.archiveWithoutUndo({ client, workspace });
await deps.archiveWithoutUndo({
client,
workspace,
force: dirtyWorktrees.has(entry) || undefined,
});
deps.purgeWorkspaceState(workspace);
} catch (error) {
failures.push({ error });
@@ -6,20 +6,21 @@ import {
isWorkspaceListed,
undoWorkspaceArchiveOptimistically,
type WorkspaceArchiveTarget,
type WorkspaceArchiveClient,
} from "@/workspace/workspace-archive";
import { WorkspaceArchivedToast } from "./workspace-archived-toast";
/** How long the archived toast, and with it the chance to undo, stays up. */
export const WORKSPACE_ARCHIVE_UNDO_WINDOW_MS = 6000;
export interface UndoableWorkspaceArchiveClient {
archiveWorkspace: (workspaceId: string) => Promise<{ error: string | null; canceled?: boolean }>;
export interface UndoableWorkspaceArchiveClient extends WorkspaceArchiveClient {
undoWorkspaceArchive: (workspaceId: string) => Promise<void>;
}
export interface UndoableWorkspaceArchiveEntryInput {
client: UndoableWorkspaceArchiveClient;
workspace: WorkspaceArchiveTarget;
force?: boolean;
onArchiveCommitted: () => void;
}
@@ -229,6 +230,7 @@ export async function archiveWorkspacesWithUndo(input: {
export async function archiveWorkspaceWithUndo(input: {
client: UndoableWorkspaceArchiveClient;
workspace: WorkspaceArchiveTarget;
force?: boolean;
toast: ToastApi;
onArchiveCommitted: () => void;
}): Promise<void> {
@@ -237,6 +239,7 @@ export async function archiveWorkspaceWithUndo(input: {
{
client: input.client,
workspace: input.workspace,
force: input.force,
onArchiveCommitted: input.onArchiveCommitted,
},
],
@@ -62,44 +62,47 @@ export function useWorkspaceArchive(input: ArchiveWorkspaceInput): WorkspaceArch
const onArchiveStartedRef = useRef(onArchiveStarted);
onArchiveStartedRef.current = onArchiveStarted;
const archiveWorkspaceRecord = useCallback(async () => {
const client = getHostRuntimeStore().getClient(serverId);
if (!client) {
toast.error(t("sidebar.workspace.toasts.hostDisconnected"));
return;
}
const workspace = { serverId, workspaceId };
onSetHiding?.(true);
try {
onArchiveStartedRef.current(workspace);
if (supportsWorkspaceArchiveUndo(serverId)) {
await archiveWorkspaceWithUndo({
client,
workspace,
toast,
onArchiveCommitted: () => purgeArchivedWorkspaceState(workspace),
});
} else {
// COMPAT(workspaceArchiveUndo): hosts before v0.15.3 cannot undo; remove after 2027-05-06.
await archiveWorkspaceOptimistically({ client, workspace });
purgeArchivedWorkspaceState(workspace);
const archiveWorkspaceRecord = useCallback(
async (options?: { force: boolean }) => {
const client = getHostRuntimeStore().getClient(serverId);
if (!client) {
toast.error(t("sidebar.workspace.toasts.hostDisconnected"));
return;
}
} catch (error) {
toast.error(
error instanceof Error ? error.message : t("sidebar.workspace.toasts.archiveFailed"),
);
} finally {
onSetHiding?.(false);
}
}, [onSetHiding, serverId, t, toast, workspaceId]);
const workspace = { serverId, workspaceId };
onSetHiding?.(true);
try {
onArchiveStartedRef.current(workspace);
if (supportsWorkspaceArchiveUndo(serverId)) {
await archiveWorkspaceWithUndo({
client,
workspace,
force: options?.force,
toast,
onArchiveCommitted: () => purgeArchivedWorkspaceState(workspace),
});
} else {
// COMPAT(workspaceArchiveUndo): hosts before v0.15.3 cannot undo; remove after 2027-05-06.
await archiveWorkspaceOptimistically({ client, workspace, force: options?.force });
purgeArchivedWorkspaceState(workspace);
}
} catch (error) {
toast.error(
error instanceof Error ? error.message : t("sidebar.workspace.toasts.archiveFailed"),
);
} finally {
onSetHiding?.(false);
}
},
[onSetHiding, serverId, t, toast, workspaceId],
);
// The host removes a worktree it archives, uncommitted work included. Ask it what that would
// lose: the sidebar row's git status is empty until the row receives it.
const confirmWorktreeArchive = useCallback(async (): Promise<boolean> => {
// Ask the host what the archive would lose. The sidebar may not have loaded Git status.
const confirmWorktreeArchive = useCallback(async (): Promise<{ force: boolean } | null> => {
const client = getHostRuntimeStore().getClient(serverId);
if (!client) {
toast.error(t("sidebar.workspace.toasts.hostDisconnected"));
return false;
return null;
}
const risk = await readWorktreeArchiveRisk(client, workspaceDirectory).catch(
(error: unknown) => {
@@ -110,12 +113,13 @@ export function useWorkspaceArchive(input: ArchiveWorkspaceInput): WorkspaceArch
},
);
if (!risk) {
return false;
return null;
}
return await confirmRiskyWorktreeArchive(
const confirmed = await confirmRiskyWorktreeArchive(
{ workspaceName: name, diffStat, ...risk },
warningLabels,
);
return confirmed ? { force: risk.isDirty === true } : null;
}, [diffStat, name, serverId, t, toast, warningLabels, workspaceDirectory]);
const archive = useCallback(() => {
@@ -26,8 +26,8 @@ const pendingArchiveAttempts = new Set<string>();
/** Checks and starts one archive at a time for a workspace. */
export async function runWorkspaceArchiveAttempt(input: {
workspace: WorkspaceArchiveTarget;
confirm?: () => Promise<boolean>;
archive: () => Promise<void>;
confirm?: () => Promise<{ force: boolean } | null>;
archive: (options?: { force: boolean }) => Promise<void>;
}): Promise<void> {
const { serverId, workspaceId } = input.workspace;
const key = JSON.stringify([serverId, workspaceId]);
@@ -35,18 +35,23 @@ export async function runWorkspaceArchiveAttempt(input: {
pendingArchiveAttempts.add(key);
try {
if (input.confirm && !(await input.confirm())) return;
const confirmed = input.confirm ? await input.confirm() : undefined;
if (confirmed === null) return;
if (!isWorkspaceListed(input.workspace)) return;
// Archive hides the row synchronously. Undo can restore it and start a new
// archive while the previous daemon request is still settling.
return input.archive();
return input.archive(confirmed);
} finally {
pendingArchiveAttempts.delete(key);
}
}
interface WorkspaceArchiveClient {
archiveWorkspace: (workspaceId: string) => Promise<{ error: string | null; canceled?: boolean }>;
export interface WorkspaceArchiveClient {
archiveWorkspace: (
workspaceId: string,
requestId?: string,
options?: { force?: boolean },
) => Promise<{ error: string | null; canceled?: boolean }>;
}
interface WorkspaceArchiveUndoClient {
@@ -158,8 +163,11 @@ function invalidateAgentHistory(serverId: string): void {
async function archiveWorkspaceOrThrow(input: {
client: WorkspaceArchiveClient;
workspaceId: string;
force?: boolean;
}): Promise<WorkspaceArchiveOutcome> {
const payload = await input.client.archiveWorkspace(input.workspaceId);
const payload = input.force
? await input.client.archiveWorkspace(input.workspaceId, undefined, { force: true })
: await input.client.archiveWorkspace(input.workspaceId);
if (payload.canceled) {
return "canceled";
}
@@ -176,6 +184,7 @@ async function archiveWorkspaceOrThrow(input: {
export function beginOptimisticWorkspaceArchive(input: {
client: WorkspaceArchiveClient;
workspace: WorkspaceArchiveTarget;
force?: boolean;
}): OptimisticWorkspaceArchive {
const snapshot = hideWorkspaceOptimistically(input.workspace);
const done = (async () => {
@@ -183,6 +192,7 @@ export function beginOptimisticWorkspaceArchive(input: {
const outcome = await archiveWorkspaceOrThrow({
client: input.client,
workspaceId: input.workspace.workspaceId,
force: input.force,
});
if (outcome === "canceled") {
restoreOptimisticallyHiddenWorkspace({ serverId: input.workspace.serverId, snapshot });
@@ -201,6 +211,7 @@ export function beginOptimisticWorkspaceArchive(input: {
export async function archiveWorkspaceOptimistically(input: {
client: WorkspaceArchiveClient;
workspace: WorkspaceArchiveTarget;
force?: boolean;
}): Promise<WorkspaceArchiveOutcome> {
return beginOptimisticWorkspaceArchive(input).done;
}
+17 -3
View File
@@ -6,6 +6,8 @@ interface WorkspaceArchiveResult {
workspaceId: string;
status: "archived";
archivedAt: string;
removedDirectory?: boolean;
directoryLeftBehind?: { path: string; reason: string };
}
const workspaceArchiveSchema: OutputSchema<WorkspaceArchiveResult> = {
@@ -14,12 +16,18 @@ const workspaceArchiveSchema: OutputSchema<WorkspaceArchiveResult> = {
{ header: "WORKSPACE ID", field: "workspaceId", width: 20 },
{ header: "STATUS", field: "status", width: 10 },
{ header: "ARCHIVED AT", field: "archivedAt", width: 26 },
{ header: "RETAINED PATH", field: (item) => item.directoryLeftBehind?.path },
{ header: "REASON", field: (item) => item.directoryLeftBehind?.reason },
],
};
export async function runArchiveCommand(
workspaceId: string,
options: { host?: string; daemonTarget: import("../../utils/daemon-target.js").DaemonTarget },
options: {
host?: string;
force?: boolean;
daemonTarget: import("../../utils/daemon-target.js").DaemonTarget;
},
_command: Command,
): Promise<SingleResult<WorkspaceArchiveResult>> {
const host = getDaemonHost({ target: options.daemonTarget });
@@ -31,7 +39,7 @@ export async function runArchiveCommand(
} satisfies CommandError;
});
try {
const payload = await client.archiveWorkspace(workspaceId);
const payload = await client.archiveWorkspace(workspaceId, undefined, { force: options.force });
if (payload.error) {
throw new Error(payload.error);
}
@@ -40,7 +48,13 @@ export async function runArchiveCommand(
}
return {
type: "single",
data: { workspaceId, status: "archived", archivedAt: payload.archivedAt },
data: {
workspaceId,
status: "archived",
archivedAt: payload.archivedAt,
removedDirectory: payload.removedDirectory,
directoryLeftBehind: payload.directoryLeftBehind,
},
schema: workspaceArchiveSchema,
};
} catch (error) {
+3 -2
View File
@@ -61,8 +61,9 @@ export function createWorkspaceCommand(): Command {
addJsonAndDaemonHostOptions(
workspace
.command("archive")
.description("Archive a workspace and everything it owns")
.argument("<workspace-id>", "Workspace id"),
.description("Archive a workspace and keep any worktree with uncommitted changes")
.argument("<workspace-id>", "Workspace id")
.option("--force", "Remove the worktree even if it has uncommitted changes"),
).action(withOutput(runArchiveCommand));
return workspace;
+51 -34
View File
@@ -15,6 +15,8 @@ export interface WorktreeArchiveResult {
name: string;
status: "archived";
removedAgents: string[];
removedDirectory?: boolean;
directoryLeftBehind?: { path: string; reason: string };
}
/** Schema for archive command output */
@@ -23,6 +25,8 @@ export const archiveSchema: OutputSchema<WorktreeArchiveResult> = {
columns: [
{ header: "NAME", field: "name" },
{ header: "STATUS", field: "status" },
{ header: "RETAINED PATH", field: (item) => item.directoryLeftBehind?.path },
{ header: "REASON", field: (item) => item.directoryLeftBehind?.reason },
{
header: "REMOVED AGENTS",
field: (item) => (item.removedAgents.length > 0 ? item.removedAgents.join(", ") : "-"),
@@ -33,6 +37,7 @@ export const archiveSchema: OutputSchema<WorktreeArchiveResult> = {
export interface WorktreeArchiveOptions extends CommandOptions {
host?: string;
cwd?: string;
force?: boolean;
}
export type WorktreeArchiveCommandResult = SingleResult<WorktreeArchiveResult>;
@@ -78,41 +83,13 @@ export async function runArchiveCommandWithDeps(
}
try {
// Get the list of worktrees first to resolve the name
const listResponse = await client.getPaseoWorktreeList({ cwd });
if (listResponse.error) {
const error: CommandError = {
code: "WORKTREE_LIST_FAILED",
message: `Failed to list worktrees: ${listResponse.error.message}`,
};
throw error;
}
// Find the worktree by name or branch
const worktree = listResponse.worktrees.find((wt) => {
const name = path.basename(wt.worktreePath);
return name === nameArg || wt.branchName === nameArg;
});
if (!worktree) {
const error: CommandError = {
code: "WORKTREE_NOT_FOUND",
message: `Worktree not found: ${nameArg}`,
details: 'Use "paseo worktree ls" to list available worktrees',
};
throw error;
}
// Archive the worktree. scope:"worktree" archives every active workspace on
// the directory and then removes the directory (Paseo-owned gated).
const worktreePath = await resolveWorktreePath(client, cwd, nameArg);
const response = await client.archivePaseoWorktree({
worktreePath: worktree.worktreePath,
worktreePath,
scope: "worktree",
force: options.force,
});
await client.close();
if (response.error) {
const error: CommandError = {
code: "WORKTREE_ARCHIVE_FAILED",
@@ -121,7 +98,7 @@ export async function runArchiveCommandWithDeps(
throw error;
}
const worktreeName = path.basename(worktree.worktreePath) || nameArg;
const worktreeName = basename(worktreePath) || nameArg;
return {
type: "single",
@@ -129,12 +106,12 @@ export async function runArchiveCommandWithDeps(
name: worktreeName,
status: "archived",
removedAgents: response.removedAgents ?? [],
removedDirectory: response.removedDirectory,
directoryLeftBehind: response.directoryLeftBehind,
},
schema: archiveSchema,
};
} catch (err) {
await client.close().catch(() => {});
// Re-throw CommandError as-is
if (err && typeof err === "object" && "code" in err) {
throw err;
@@ -146,5 +123,45 @@ export async function runArchiveCommandWithDeps(
message: `Failed to archive worktree: ${message}`,
};
throw error;
} finally {
await client.close().catch(() => {});
}
}
async function resolveWorktreePath(
client: DaemonClient,
cwd: string,
name: string,
): Promise<string> {
if (path.posix.isAbsolute(name) || path.win32.isAbsolute(name)) return name;
const listResponse = await client.getPaseoWorktreeList({ cwd });
if (listResponse.error) {
const error: CommandError = {
code: "WORKTREE_LIST_FAILED",
message: `Failed to list worktrees: ${listResponse.error.message}`,
};
throw error;
}
const worktree = listResponse.worktrees.find(
(entry) => basename(entry.worktreePath) === name || entry.branchName === name,
);
if (!worktree) {
const error: CommandError = {
code: "WORKTREE_NOT_FOUND",
message: `Worktree not found: ${name}`,
details: 'Use "paseo worktree ls" to list available worktrees',
};
throw error;
}
return worktree.worktreePath;
}
function basename(worktreePath: string): string {
return path.posix.isAbsolute(worktreePath)
? path.posix.basename(worktreePath)
: path.win32.basename(worktreePath);
}
+3 -2
View File
@@ -33,8 +33,9 @@ export function createWorktreeCommand(): Command {
addJsonAndDaemonHostOptions(
worktree
.command("archive")
.description("Archive a worktree (removes worktree and associated branch)")
.argument("<name>", "Worktree name or branch name")
.description("Archive a worktree, keeping the branch and any uncommitted work by default")
.option("--force", "Remove the directory even if it has uncommitted changes")
.argument("<name>", "Worktree name, branch name, or absolute path")
.option("--cwd <path>", "Repository directory (default: current)"),
).action(withOutput(runArchiveCommand));
+1
View File
@@ -92,6 +92,7 @@ try {
assert(result.stdout.includes("--host"), "help should mention --host option");
assert(result.stdout.includes("--cwd"), "help should mention --cwd option");
assert(result.stdout.includes("<name>"), "help should mention required name argument");
assert(result.stdout.includes("--force"), "help should mention --force option");
console.log("✓ worktree archive --help shows options\n");
}
+4 -4
View File
@@ -1786,8 +1786,6 @@ export class DaemonClientCore {
// An endpoint security policy close cannot be fixed by retrying.
const securityFailure = describeEndpointSecurityClose(event);
if (securityFailure) this.setReconnectEnabled(false);
// A transport error may already have scheduled this socket's retry before its close.
if (this.reconnectTimeout && !securityFailure && !this.authFailureReasonValue) return;
const reason = this.authFailureReasonValue
? new DaemonAuthenticationError(this.authFailureReasonValue).message
: (securityFailure ?? describeTransportClose(event));
@@ -3266,8 +3264,6 @@ export class DaemonClientCore {
listProjectSuggestions(options?: ProjectSuggestionsOptions): Promise<ProjectSuggestionsPayload> {
return this.sendNamespacedCorrelatedSessionRequest<"project.suggestions.response">({
requestId: options?.requestId,
// Provider session discovery can take 90 seconds before the daemon resolves project roots.
timeout: 120_000,
message: {
type: "project.suggestions.request",
...(options?.providers ? { providers: options.providers } : {}),
@@ -3411,12 +3407,14 @@ export class DaemonClientCore {
async archiveWorkspace(
workspaceId: string,
requestId?: string,
options?: { force?: boolean },
): Promise<ArchiveWorkspacePayload> {
return this.sendCorrelatedSessionRequest({
requestId,
message: {
type: "archive_workspace_request",
workspaceId,
...(options?.force === true ? { force: true } : {}),
},
responseType: "archive_workspace_response",
// Archive may wait for a queued checkout operation and then run teardown/manager removal,
@@ -5648,6 +5646,7 @@ export class DaemonClientCore {
branchName?: string;
workspaceId?: string;
scope?: "workspace" | "worktree";
force?: boolean;
},
requestId?: string,
): Promise<PaseoWorktreeArchivePayload> {
@@ -5660,6 +5659,7 @@ export class DaemonClientCore {
branchName: input.branchName,
...(input.workspaceId !== undefined ? { workspaceId: input.workspaceId } : {}),
...(input.scope !== undefined ? { scope: input.scope } : {}),
...(input.force ? { force: true } : {}),
},
responseType: "paseo_worktree_archive_response",
// Archive may wait for a queued checkout operation and then run teardown/manager removal,
-62
View File
@@ -3020,34 +3020,6 @@ test("foreground keeps a connect attempt that just started", async () => {
expect(client.getConnectionState().status).toBe("connected");
});
test("a handshake error followed by a close consumes one reconnect attempt", async () => {
useHeartbeatClock();
const [first, failed, recovered] = [
new FakeDaemon(),
new FakeDaemon(),
new FakeDaemon(),
] as const;
const { client, attempts } = connectThroughReplacements("error-and-close", [
first,
failed,
recovered,
]);
const connection = client.connect();
first.openConnection();
await connection;
first.daemonClosesWith("connection lost");
await vi.advanceTimersByTimeAsync(1_500);
expect(attempts()).toBe(2);
failed.triggerError(new Error("read ECONNRESET"));
failed.daemonClosesWith("abnormal closure");
await vi.advanceTimersByTimeAsync(2_999);
expect(attempts()).toBe(2);
await vi.advanceTimersByTimeAsync(1);
expect(attempts()).toBe(3);
recovered.openConnection();
expect(client.getConnectionState().status).toBe("connected");
});
test("foreground resets the retry delay after failed connections in the background", async () => {
useHeartbeatClock();
const daemons = Array.from({ length: 7 }, () => new FakeDaemon());
@@ -9508,40 +9480,6 @@ test("rejects usage requests when the host has neither capability", async () =>
expect(mock.sent).toEqual([]);
});
test("project suggestions accept a slow provider response past the default deadline", async () => {
useHeartbeatClock();
const mock = createMockTransport();
const client = new DaemonClient({
url: "ws://test",
clientId: "slow-projects",
logger: noopLogger,
reconnect: { enabled: false },
transportFactory: () => mock.transport,
});
clients.push(client);
const connected = client.connect();
mock.triggerOpen();
await connected;
const requestId = "slow-source";
const payload = {
requestId,
suggestions: [
{
rootPath: "/repo",
displayName: "repo",
sessionCount: 1,
providerIds: ["opencode"],
lastActivityAt: "2026-11-01T00:00:00Z",
},
],
providerErrors: [],
};
const result = client.listProjectSuggestions({ requestId }).catch((error: unknown) => error);
await vi.advanceTimersByTimeAsync(65_000);
mock.triggerMessage(wrapSessionMessage({ type: "project.suggestions.response", payload }));
expect(await result).toEqual(payload);
});
test("usage request timeout detaches its update listener", async () => {
vi.useFakeTimers();
try {
+6
View File
@@ -2957,6 +2957,7 @@ export const PaseoWorktreeArchiveRequestSchema = z.object({
// cwd resolves to the target directory, then removes the directory if it is
// Paseo-owned. Omitted/unknown values default to "workspace" for old-client safety.
scope: z.enum(["workspace", "worktree"]).optional().default("workspace"),
force: z.boolean().optional(),
// COMPAT(worktreeDiskDeletion): added in v0.1.97, ignored as of v0.1.97
// (disk removal derived from scope + last-reference + ownership); field
// retained for wire parse-compat, drop when floor >= v0.1.97.
@@ -3073,6 +3074,7 @@ export const ProjectGithubCloneRequestSchema = z.object({
export const ArchiveWorkspaceRequestSchema = z.object({
type: z.literal("archive_workspace_request"),
workspaceId: z.string(),
force: z.boolean().optional(),
requestId: z.string(),
});
@@ -5274,6 +5276,8 @@ export const ArchiveWorkspaceResponseMessageSchema = z.object({
workspaceId: z.string(),
archivedAt: z.string().nullable(),
error: z.string().nullable(),
removedDirectory: z.boolean().optional(),
directoryLeftBehind: z.object({ path: z.string(), reason: z.string() }).optional(),
// An undo stopped this archive before it finished; `error` carries the reason.
canceled: z.boolean().optional(),
}),
@@ -6825,6 +6829,8 @@ export const PaseoWorktreeArchiveResponseSchema = z.object({
payload: z.object({
success: z.boolean(),
removedAgents: z.array(z.string()).optional(),
removedDirectory: z.boolean().optional(),
directoryLeftBehind: z.object({ path: z.string(), reason: z.string() }).optional(),
error: CheckoutErrorSchema.nullable(),
requestId: z.string(),
}),
@@ -1,7 +1,7 @@
import os from "node:os";
import path from "node:path";
import { execSync } from "node:child_process";
import { mkdtemp, rm, writeFile } from "node:fs/promises";
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { afterAll, beforeAll, describe, expect, test } from "vitest";
import { experimental_createMCPClient } from "ai";
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
@@ -1154,6 +1154,36 @@ describe("Suite D: Provider Tools", () => {
});
describe("Suite E: Workspace Tools", () => {
test.each([false, true])(
"archive_workspace respects force=%s for untracked files",
async (force) => {
const created = await callToolStructured(topLevelClient, "create_workspace", {
isolation: "worktree",
path: worktreeRepoCwd,
baseBranch: "main",
branchName: `parity-archive-${force}`,
});
const cwd = str(created.cwd);
const file = path.join(cwd, "untracked.txt");
await writeFile(file, "keep this file");
const result = await callToolStructured(topLevelClient, "archive_workspace", {
workspaceId: str(created.workspaceId),
...(force ? { force } : {}),
});
expect(result.removedDirectory).toBe(force);
if (force) {
await expect(readFile(file, "utf8")).rejects.toMatchObject({ code: "ENOENT" });
} else {
expect(result.directoryLeftBehind).toEqual({
path: cwd,
reason: "The worktree has uncommitted changes.",
});
await expect(readFile(file, "utf8")).resolves.toBe("keep this file");
}
},
);
test("background worktree creation, discovery and archive use ordinary workspace ownership", async () => {
const created = await callToolStructured(topLevelClient, "create_workspace", {
isolation: "worktree",
@@ -1652,15 +1652,17 @@ function createToolCatalog(
"archive_workspace",
{
title: "Archive workspace",
description: "Archive a workspace and everything it owns.",
inputSchema: { workspaceId: z.string().min(1) },
description:
"Archive a workspace. Keep worktrees with uncommitted changes unless force is true.",
inputSchema: { workspaceId: z.string().min(1), force: z.boolean().optional() },
outputSchema: {
workspaceId: z.string(),
archivedAgentIds: z.array(z.string()),
removedDirectory: z.boolean(),
directoryLeftBehind: z.object({ path: z.string(), reason: z.string() }).optional(),
},
},
async ({ workspaceId }) => {
async ({ workspaceId, force }) => {
if (!options.listActiveWorkspaces) {
throw new Error("Active workspace lister is required to archive workspaces");
}
@@ -1677,6 +1679,7 @@ function createToolCatalog(
}),
{
requestId: "mcp:archive_workspace",
force,
scope: { kind: "workspace", workspaceId: workspace.workspaceId },
},
);
@@ -1686,6 +1689,9 @@ function createToolCatalog(
workspaceId,
archivedAgentIds: result.archivedAgentIds,
removedDirectory: result.removedDirectory,
...(result.directoryLeftBehind
? { directoryLeftBehind: result.directoryLeftBehind }
: {}),
}),
};
},
@@ -1500,7 +1500,11 @@ test.each([false, true])(
expect((await client.fetchWorkspaces()).entries.map((workspace) => workspace.id)).toContain(
created.workspace!.id,
);
await client.archiveWorkspace(created.workspace!.id);
// The hook creates an untracked fixture. This flow needs to restore after disk removal.
const archived = await client.archiveWorkspace(created.workspace!.id, undefined, {
force: true,
});
expect(archived.removedDirectory).toBe(true);
await expect(stat(cwd)).rejects.toMatchObject({ code: "ENOENT" });
const hookRecordsBeforeRestore = await readFile(orderFile, "utf8");
await client.close();
@@ -268,7 +268,14 @@ export default function contribute(server) {
expect(await readFile(path.join(retriedAfterPath, ".wt-hook-ran"), "utf8")).toBe("pre-start");
// Archive delegates removal to `wt remove` (run from repoRoot) AFTER Paseo writes refs/paseo/kept-commits/*.
const archived = await client.archiveWorkspace(workspaceId);
const retained = await client.archiveWorkspace(workspaceId);
expect(retained).toMatchObject({
error: null,
removedDirectory: false,
directoryLeftBehind: { path: worktreePath },
});
expect((await stat(worktreePath)).isDirectory()).toBe(true);
const archived = await client.archiveWorkspace(workspaceId, undefined, { force: true });
expect(archived.error).toBeNull();
await expect(stat(worktreePath)).rejects.toMatchObject({ code: "ENOENT" });
@@ -805,7 +812,14 @@ test("untrusted workspaces pass untrusted=true to worktree manager remove and re
client = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws` });
await client.connect();
const archived = await client.archiveWorkspace(workspaceId);
const retained = await client.archiveWorkspace(workspaceId);
expect(retained).toMatchObject({
error: null,
removedDirectory: false,
directoryLeftBehind: { path: worktreePath },
});
expect((await stat(worktreePath)).isDirectory()).toBe(true);
const archived = await client.archiveWorkspace(workspaceId, undefined, { force: true });
expect(archived.error).toBeNull();
await expect(stat(worktreePath)).rejects.toMatchObject({ code: "ENOENT" });
@@ -843,7 +857,7 @@ test("untrusted workspaces pass untrusted=true to worktree manager remove and re
expect((await client.archiveWorkspace(workspaceId)).error).toBeNull();
expect((await stat(worktreePath)).isDirectory()).toBe(true);
expect((await client.archiveWorkspace(siblingId)).error).toBeNull();
expect((await client.archiveWorkspace(siblingId, undefined, { force: true })).error).toBeNull();
await expect(stat(worktreePath)).rejects.toMatchObject({ code: "ENOENT" });
await client.restoreWorkspace(siblingId);
@@ -1438,7 +1452,9 @@ test("built-in archive removes the worktree with dependency clones and recursive
const checkout = created.workspace!.workspaceDirectory;
await addNestedGitContent(checkout, leaf, middle);
const archived = await client.archiveWorkspace(created.workspace!.id);
const archived = await client.archiveWorkspace(created.workspace!.id, undefined, {
force: true,
});
expect(archived.error).toBeNull();
await expect(stat(checkout)).rejects.toMatchObject({ code: "ENOENT" });
expect(git(repository, ["worktree", "list", "--porcelain"])).not.toContain(
@@ -1583,7 +1599,9 @@ export default function contribute(server) {
const checkout = managed.workspace!.workspaceDirectory;
await addNestedGitContent(checkout, otherRepo, middle);
const archivedWithContent = await client.archiveWorkspace(managed.workspace!.id);
const archivedWithContent = await client.archiveWorkspace(managed.workspace!.id, undefined, {
force: true,
});
expect(archivedWithContent.error).toBeNull();
expect(path.normalize((await readFile(removeCallsFile, "utf8")).trim())).toBe(
path.normalize(checkout),
+4
View File
@@ -8785,11 +8785,13 @@ export class Session {
},
{
scope: { kind: "workspace", workspaceId: existing.workspaceId },
force: request.force,
requestId: request.requestId,
signal,
},
);
},
request.force,
);
if (outcome.kind === "canceled") {
@@ -8815,6 +8817,8 @@ export class Session {
workspaceId: request.workspaceId,
archivedAt,
error: null,
removedDirectory: outcome.result.removedDirectory,
directoryLeftBehind: outcome.result.directoryLeftBehind,
},
});
} catch (error) {
@@ -128,6 +128,25 @@ describe("WorkspaceArchiveOperations", () => {
expect(runs).toBe(1);
});
test.each([false, true])(
"an in-flight archive with force=%s only accepts matching requests",
async (force) => {
const operations = new WorkspaceArchiveOperations();
const archive = parkedArchive(["agent-a"]);
const first = operations.archive("ws", archive.run, force);
await archive.started;
try {
await expect(operations.archive("ws", archive.run, !force)).rejects.toThrow(
"An archive with different force settings is already running.",
);
} finally {
archive.release();
await first;
}
},
);
test("an archive requested during an undo runs after the undo, and wins", async () => {
const operations = new WorkspaceArchiveOperations();
await operations.archive("ws", async () => archived(["agent-a"]));
@@ -17,7 +17,7 @@ interface PendingArchive {
}
type LaneEntry =
| { kind: "archiving"; controller: AbortController; done: Promise<WorkspaceArchiveOutcome> }
| ({ kind: "archiving"; force: boolean } & PendingArchive)
| {
kind: "restoring";
pendingArchive: PendingArchive | null;
@@ -30,7 +30,7 @@ type LaneEntry =
* Daemon-wide coordinator for workspace archive, undo, and restore operations.
*
* Per-workspace lanes:
* - An archive while one runs joins it.
* - An archive while one runs joins it if both requests use the same removal policy.
* - An undo while an archive runs (including when a restore queued behind it) aborts the archive,
* waits for it to stop, then restores.
* - A restore while an archive runs waits for the archive without aborting it, then restores.
@@ -75,10 +75,14 @@ export class WorkspaceArchiveOperations {
archive(
workspaceId: string,
run: (signal: AbortSignal) => Promise<ArchiveResult>,
force = false,
): Promise<WorkspaceArchiveOutcome> {
const current = this.lanes.get(workspaceId);
if (current?.kind === "archiving") {
return current.done;
if (current.force === force) return current.done;
return Promise.reject(
new Error("An archive with different force settings is already running."),
);
}
const controller = new AbortController();
const done = (async (): Promise<WorkspaceArchiveOutcome> => {
@@ -91,7 +95,7 @@ export class WorkspaceArchiveOperations {
return { kind: "canceled", archivedAt: error.archivedAt };
}
})();
this.claim(workspaceId, { kind: "archiving", controller, done });
this.claim(workspaceId, { kind: "archiving", force, controller, done });
return done;
}
@@ -27,8 +27,7 @@ import {
// to a directory on disk. A directory can back multiple workspaces, so archiving
// one must never tear down a sibling's agents/terminals, and must never delete a
// directory another workspace still references. On-disk worktree removal is
// derived from scope + last-reference + Paseo ownership; there is no caller-
// supplied disk flag.
// gated on scope, the last active reference, ownership, and checkout cleanliness.
let ctx: DaemonTestContext;
const tempRoots: string[] = [];
@@ -398,6 +397,83 @@ test("an archived workspace keeps its base when a later workspace reuses its pat
);
});
test.each([
{ command: "workspace", mode: "default", force: false },
{ command: "workspace", mode: "forced", force: true },
{ command: "worktree", mode: "default", force: false },
{ command: "worktree", mode: "forced", force: true },
])("$command archive handles a late untracked file in $mode mode", async ({ command, force }) => {
const repoDir = createGitRepo();
const sibling = await ctx.client.createWorkspace({
source: { kind: "worktree", cwd: repoDir, baseBranch: "main", worktreeSlug: "control" },
});
if (!sibling.workspace) throw new Error(sibling.error ?? "Failed to create control worktree");
const created = await ctx.client.createWorkspace({
source: { kind: "worktree", cwd: repoDir, baseBranch: "main", worktreeSlug: "late-file" },
});
const workspace = created.workspace;
if (!workspace) throw new Error(created.error ?? "Failed to create worktree workspace");
const cwd = workspace.workspaceDirectory;
const status = () =>
execFileSync("git", ["status", "--porcelain", "--untracked-files=all"], { cwd }).toString();
expect(status()).toBe("");
const lateFile = path.join(cwd, "late-untracked.txt");
writeFileSync(lateFile, "disposable fixture\n");
expect(status()).toBe("?? late-untracked.txt\n");
const target = command === "workspace" ? workspace.id : path.basename(cwd);
const archived = JSON.parse(
await runCli([command, "archive", target, "--json", ...(force ? ["--force"] : [])], repoDir),
);
expect(archived.status).toBe("archived");
expect(await activeWorkspaceIds()).not.toContain(workspace.id);
expect(await activeWorkspaceIds()).toContain(sibling.workspace.id);
expect(existsSync(sibling.workspace.workspaceDirectory)).toBe(true);
expect(existsSync(lateFile)).toBe(!force);
expect(archived.removedDirectory).toBe(force);
if (!force) {
expect(readFileSync(lateFile, "utf8")).toBe("disposable fixture\n");
expect(archived.directoryLeftBehind).toEqual({
path: cwd,
reason: "The worktree has uncommitted changes.",
});
}
});
test("worktree archive by absolute path keeps an orphaned directory until forced", async () => {
const repoDir = createGitRepo();
const { workspace, error } = await ctx.client.createWorkspace({
source: { kind: "worktree", cwd: repoDir, baseBranch: "main", worktreeSlug: "orphaned" },
});
if (!workspace) throw new Error(error ?? "Failed to create worktree workspace");
const cwd = workspace.workspaceDirectory;
const gitDir = execFileSync("git", ["rev-parse", "--absolute-git-dir"], { cwd })
.toString()
.trim();
rmSync(gitDir, { recursive: true, force: true });
const archive = ["worktree", "archive", cwd, "--json"];
expect(JSON.parse(await runCli(archive, repoDir))).toMatchObject({
status: "archived",
removedDirectory: false,
directoryLeftBehind: {
path: cwd,
reason: "Git could not check the worktree for uncommitted changes.",
},
});
expect(await activeWorkspaceIds()).not.toContain(workspace.id);
expect(existsSync(cwd)).toBe(true);
expect(JSON.parse(await runCli([...archive, "--force"], repoDir))).toMatchObject({
status: "archived",
removedDirectory: true,
});
expect(existsSync(cwd)).toBe(false);
});
test.each(["worktree", "workspace"] as const)(
"%s archive immediately removes the deleted worktree from a warm CLI listing",
async (command) => {
@@ -564,12 +640,15 @@ test.skipIf(process.platform === "win32")(
const archive = await ctx.client.archiveWorkspace(workspace.id);
const retry = await ctx.client.archiveWorkspace(workspace.id);
expect({ archiveError: archive.error, retryError: retry.error }).toEqual({
archiveError: null,
retryError: null,
});
for (const response of [archive, retry]) {
expect(response).toMatchObject({
error: null,
removedDirectory: false,
directoryLeftBehind: { path: workspace.workspaceDirectory },
});
}
expect((await activeWorkspaceIds()).has(workspace.id)).toBe(false);
expect(existsSync(workspace.workspaceDirectory)).toBe(false);
expect(existsSync(workspace.workspaceDirectory)).toBe(true);
} finally {
writeFileSync(stopSetupPath, "stop\n");
}
@@ -731,7 +810,7 @@ test.skipIf(process.platform === "win32" || process.getuid?.() === 0)(
if (existsSync(directory)) chmodSync(directory, originalMode);
}
const retry = await ctx.client.archiveWorkspace(workspace.id);
const retry = await ctx.client.archiveWorkspace(workspace.id, undefined, { force: true });
expect(retry.error).toBeNull();
expect(existsSync(directory)).toBe(false);
@@ -359,7 +359,7 @@ describe("archiveByScope", () => {
requestId: "slug-archive",
},
);
expect(result).toEqual({ ok: true, removedAgents: [] });
expect(result).toMatchObject({ ok: true, removedAgents: [], removedDirectory: true });
expect(existsSync(worktreePath)).toBe(false);
});
@@ -1188,9 +1188,13 @@ describe("archiveByScope", () => {
expect(deps.emitWorkspaceUpdatesForWorkspaceIds).not.toHaveBeenCalled();
});
test.each(["intact", "missing"] as const)(
"worktree scope removes an owned directory with zero matching records and %s Git administration",
async (gitAdministration) => {
test.each([
{ gitAdministration: "intact", force: false, removed: true },
{ gitAdministration: "missing", force: false, removed: false },
{ gitAdministration: "missing", force: true, removed: true },
])(
"worktree scope with $gitAdministration Git administration and force=$force",
async ({ gitAdministration, force, removed }) => {
const { tempDir, repoDir } = createGitRepo();
const paseoHome = path.join(tempDir, ".paseo");
const worktree = await createPaseoOwnedWorktree(repoDir, paseoHome, "zero-records");
@@ -1209,14 +1213,18 @@ describe("archiveByScope", () => {
const result = await archiveByScope(dependencies, {
scope: { kind: "worktree", targetPath: worktree.worktreePath },
requestId: "req-zero-records",
force,
});
assertArchiveResult(result, {
archivedWorkspaceIds: [],
removedDirectory: true,
});
expect(existsSync(worktree.worktreePath)).toBe(false);
expect(invalidateWorktrees).toHaveBeenCalledTimes(1);
expect(result).toMatchObject({ archivedWorkspaceIds: [], removedDirectory: removed });
if (!removed) {
expect(result.directoryLeftBehind).toEqual({
path: worktree.worktreePath,
reason: "Git could not check the worktree for uncommitted changes.",
});
}
expect(existsSync(worktree.worktreePath)).toBe(!removed);
expect(invalidateWorktrees).toHaveBeenCalledTimes(Number(removed));
},
);
@@ -89,14 +89,13 @@ export interface ArchiveResult {
archivedAgentIds: string[];
archivedWorkspaceIds: string[];
removedDirectory: boolean;
// Set when the record archived but its worktree directory was left on
// disk because no ownership proof held for it. The directory is never
// deleted in that case; the path and reason surface here and in the log.
// The path and reason when archive could not safely remove the worktree.
directoryLeftBehind?: { path: string; reason: string };
}
export interface ArchiveByScopeRequest {
scope: ArchiveScope;
force?: boolean;
requestId: string;
// Aborting cancels the archive at its next checkpoint. Removing the worktree directory is the
// point of no return: once it starts the archive completes.
@@ -242,7 +241,7 @@ async function archiveByScopeWithPriority(
if (target.backing !== null) {
const removal = await maybeRemoveDirectory(
dependencies,
{ requestId: request.requestId, checkpoint },
{ requestId: request.requestId, force: request.force ?? false, checkpoint },
target,
archivedWorkspaceIds,
);
@@ -550,7 +549,7 @@ async function archiveTargetRecords(
async function maybeRemoveDirectory(
dependencies: ArchiveDependencies,
request: { requestId: string; checkpoint: () => void },
request: { requestId: string; force: boolean; checkpoint: () => void },
target: ArchiveTarget,
archivedWorkspaceIds: string[],
): Promise<{
@@ -642,6 +641,7 @@ async function maybeRemoveDirectory(
worktreeManagers: dependencies.worktreeManagers,
worktreeManagerPluginId: backing.worktreeManagerPluginId,
removeReason: "archive",
force: request.force,
untrusted: untrustedBacking,
});
dependencies.workspaceGitService.invalidateWorktrees();
@@ -652,7 +652,13 @@ async function maybeRemoveDirectory(
{ err: error, targetPath: backing.path, requestId: request.requestId },
"Worktree disk removal failed during archive; workspace already archived",
);
return { removedDirectory: false };
return {
removedDirectory: false,
directoryLeftBehind: {
path: backing.path,
reason: error instanceof Error ? error.message : String(error),
},
};
}
}
@@ -218,6 +218,7 @@ export async function handlePaseoWorktreeArchiveRequest(
branchName: msg.branchName,
workspaceId: msg.workspaceId,
scope: msg.scope,
force: msg.force,
});
if (!result.ok) {
dependencies.emit({
@@ -240,6 +241,8 @@ export async function handlePaseoWorktreeArchiveRequest(
payload: {
success: true,
removedAgents: result.removedAgents,
removedDirectory: result.removedDirectory,
directoryLeftBehind: result.directoryLeftBehind,
error: null,
requestId,
},
@@ -5,6 +5,7 @@ import {
archiveByScope,
resolveWorkspaceIdAtPath,
type ArchiveDependencies,
type ArchiveResult,
type ArchiveScope,
} from "../workspace-archive-service.js";
import type {
@@ -104,13 +105,14 @@ export interface ArchiveCommandInput {
branchName?: string;
workspaceId?: string;
scope?: ArchiveScope["kind"];
force?: boolean;
}
export type ArchiveCommandResult =
| {
| ({
ok: true;
removedAgents: string[];
}
} & Pick<ArchiveResult, "removedDirectory" | "directoryLeftBehind">)
| {
ok: false;
code: "NOT_ALLOWED";
@@ -141,12 +143,15 @@ export async function archiveCommand(
const result = await archiveByScope(dependencies, {
scope: { kind: "worktree", targetPath },
force: input.force,
requestId: input.requestId,
});
return {
ok: true,
removedAgents: result.archivedAgentIds,
removedDirectory: result.removedDirectory,
directoryLeftBehind: result.directoryLeftBehind,
};
}
@@ -161,17 +166,21 @@ export async function archiveCommand(
return {
ok: true,
removedAgents: [],
removedDirectory: false,
};
}
const result = await archiveByScope(dependencies, {
scope: { kind: "workspace", workspaceId },
force: input.force,
requestId: input.requestId,
});
return {
ok: true,
removedAgents: result.archivedAgentIds,
removedDirectory: result.removedDirectory,
directoryLeftBehind: result.directoryLeftBehind,
};
}
@@ -420,6 +420,56 @@ describe("paseo worktree manager", () => {
]);
});
it.each([false, true])(
"archives a worktree with an initialized submodule (dirty: %s)",
async (dirty) => {
const submoduleRepo = join(tempDir, "submodule-source");
execFileSync("git", ["clone", "--local", repoDir, submoduleRepo], {
stdio: "pipe",
});
execFileSync(
"git",
["-c", "protocol.file.allow=always", "submodule", "add", submoduleRepo, "submodule"],
{
cwd: repoDir,
stdio: "pipe",
},
);
execFileSync("git", ["-c", "commit.gpgsign=false", "commit", "-m", "Add submodule"], {
cwd: repoDir,
stdio: "pipe",
});
const { worktreePath } = await createLegacyWorktreeForTest({
branchName: "with-submodule",
cwd: repoDir,
baseBranch: "main",
worktreeSlug: "with-submodule",
paseoHome,
});
execFileSync("git", ["-c", "protocol.file.allow=always", "submodule", "update", "--init"], {
cwd: worktreePath,
stdio: "pipe",
});
const remove = () =>
deletePaseoWorktree({
cwd: repoDir,
worktreePath,
paseoHome,
force: false,
});
if (dirty) {
const untracked = join(worktreePath, "submodule", "keep.txt");
writeFileSync(untracked, "keep");
await expect(remove()).rejects.toThrow("The worktree has uncommitted changes.");
expect(readFileSync(untracked, "utf8")).toBe("keep");
} else {
await remove();
expect(existsSync(worktreePath)).toBe(false);
}
},
);
it("deletes a worktree whose .git admin dir has already been removed", async () => {
const created = await createLegacyWorktreeForTest({
branchName: "orphan-delete-branch",
+48 -1
View File
@@ -1489,6 +1489,7 @@ export interface DeletePaseoWorktreeOptions {
worktreeManagers?: Pick<PluginWorktreeManagerRuntime, "removeWorktree">;
worktreeManagerPluginId?: string | null;
removeReason?: "archive" | "rollback";
force?: boolean;
untrusted?: boolean;
signal?: AbortSignal;
}
@@ -1554,6 +1555,7 @@ async function deletePaseoWorktreeAtRepositoryRoot({
worktreeManagers,
worktreeManagerPluginId,
removeReason = "archive",
force = true,
untrusted = false,
signal,
}: DeletePaseoWorktreeOptions): Promise<void> {
@@ -1603,6 +1605,7 @@ async function deletePaseoWorktreeAtRepositoryRoot({
worktreeManagers,
worktreeManagerPluginId,
removeReason,
force,
untrusted,
signal,
});
@@ -1612,6 +1615,8 @@ async function deletePaseoWorktreeAtRepositoryRoot({
}
}
if (!force) return removeCleanWorktree(cwd, resolvedWorktree);
if (cwd) {
try {
await runGitCommand(["worktree", "remove", resolvedWorktree, "--force"], {
@@ -1630,6 +1635,44 @@ async function deletePaseoWorktreeAtRepositoryRoot({
await pruneWorktreesBestEffort(cwd);
}
async function assertCleanWorktree(worktreePath: string): Promise<void> {
if (!(await pathExists(join(worktreePath, ".git")))) {
throw new Error("Git could not check the worktree for uncommitted changes.");
}
const status = await runGitCommand(
["status", "--porcelain", "--untracked-files=all", "--ignore-submodules=none"],
{ cwd: worktreePath, envOverlay: READ_ONLY_GIT_ENV },
).catch(() => {
throw new Error("Git could not check the worktree for uncommitted changes.");
});
if (status.stdout.length > 0) {
throw new Error("The worktree has uncommitted changes.");
}
}
async function removeCleanWorktree(cwd: string | null, worktreePath: string): Promise<void> {
if (!(await pathExists(worktreePath))) return;
if (!cwd) throw new Error("The worktree repository could not be located.");
const options = { cwd, timeout: 120_000, envOverlay: { LC_ALL: "C" } };
try {
await runGitCommand(["worktree", "remove", worktreePath], options);
} catch (error) {
if (
!(error instanceof Error) ||
!error.message.endsWith(
"\nfatal: working trees containing submodules cannot be moved or removed",
)
) {
throw error;
}
// Git refuses even a clean initialized submodule. Recheck the contents
// before using Git's submodule removal path, without a recursive fallback.
await assertNoNestedLinkedWorktrees(worktreePath);
await assertCleanWorktree(worktreePath);
await runGitCommand(["worktree", "remove", "--force", worktreePath], options);
}
}
async function assertNoNestedLinkedWorktrees(worktreePath: string): Promise<void> {
const pending = [worktreePath];
for (let directory = pending.pop(); directory !== undefined; directory = pending.pop()) {
@@ -1684,6 +1727,7 @@ async function prepareAndTryPluginWorktreeRemove(options: {
worktreeManagers?: Pick<PluginWorktreeManagerRuntime, "removeWorktree">;
worktreeManagerPluginId?: string | null;
removeReason: "archive" | "rollback";
force: boolean;
untrusted: boolean;
signal?: AbortSignal;
}): Promise<boolean> {
@@ -1694,6 +1738,7 @@ async function prepareAndTryPluginWorktreeRemove(options: {
worktreeManagers,
worktreeManagerPluginId,
removeReason,
force,
untrusted,
signal,
} = options;
@@ -1703,6 +1748,8 @@ async function prepareAndTryPluginWorktreeRemove(options: {
teardownCwd,
});
}
if (!force) await assertCleanWorktree(resolvedWorktree);
const effectiveManagerPluginId =
worktreeManagerPluginId !== undefined
? worktreeManagerPluginId
@@ -1729,7 +1776,7 @@ async function prepareAndTryPluginWorktreeRemove(options: {
path: resolvedWorktree,
branch,
reason: removeReason,
force: true,
force,
untrusted,
},
{ preferredPluginId: effectiveManagerPluginId, signal },
@@ -208,35 +208,6 @@ it.each([
},
);
it("clamps negative remaining counts and percentages when premium quota is exceeded", async () => {
const report = await fetchPremiumQuota({
entitlement: 20000,
remaining: -6,
percent_remaining: -0.03,
unlimited: false,
});
expect(report).toMatchObject({
status: "available",
planLabel: "individual",
windows: [
{
id: "premium_interactions",
label: "Premium requests",
usedPct: 100,
remainingPct: 0,
resetsAt: "2026-12-01T00:00:00.000Z",
},
],
details: expect.arrayContaining([
{
id: "premium_remaining",
label: "Premium requests remaining",
value: "0 / 20000",
},
]),
});
});
it.each([
undefined,
null,
+4 -4
View File
@@ -27,8 +27,8 @@ const CopilotUsageResponseSchema = z.object({
premium_interactions: z
.object({
entitlement: z.number().nonnegative().nullish(),
remaining: z.number().nullish(),
percent_remaining: z.number().nullish(),
remaining: z.number().nonnegative().nullish(),
percent_remaining: z.number().min(0).max(100).nullish(),
unlimited: z.boolean().optional(),
})
.nullish(),
@@ -122,7 +122,7 @@ export async function fetchUsage(
windowFromUsedPct({
id: "premium_interactions",
label: "Premium requests",
utilizationPct: Math.max(0, Math.min(100, 100 - premium.percent_remaining)),
utilizationPct: 100 - premium.percent_remaining,
resetsAt: resp.quota_reset_date_utc || resp.quota_reset_date,
}),
);
@@ -131,7 +131,7 @@ export async function fetchUsage(
details.push({
id: "premium_remaining",
label: "Premium requests remaining",
value: `${Math.max(0, premium.remaining)} / ${premium.entitlement}`,
value: `${premium.remaining} / ${premium.entitlement}`,
});
}
}