Compare commits

...
Author SHA1 Message Date
Mohamed Boudra f694d0eab3 fix(app): return the previous pane to its last active tab when splitting or moving
Detaching a pane's active tab via splitPane or moveTabToPane previously dropped focusedTabId and fell back to the rightmost remaining tab in the strip, so dragging a file tab out after coming from tab A left the previous pane on tab B instead of putting A and the file side by side.

Track per-pane tab focus recency in memory and route both close and relocate focus transitions through one explicit policy table. Closing a tab keeps its existing parent-then-neighbor order, while splitting or moving a focused tab out of a pane returns the source pane to its most recently focused remaining tab (falling back to a same-pane parent tab and then an adjacent neighbor). Keeping the focus history in memory avoids adding a new key to the strict persisted layout schema.
2026-11-24 15:21:33 +01:00
paseo-bot[bot] 7bcd598f09 test(terminal): speed up history setup for pressure recovery (#10683)
Windows timed out while the fixture printed 12,050 rows before signaling readiness. Batch the initial writes and keep the live burst and replay assertions.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-11-24 12:01:34 +00:00
Mohamed Boudra c626bf3707 Skip worktree teardown commands for unapproved cross-repository checkouts (#10694)
* fix(server): skip teardown commands when archiving unapproved checkouts

`archiveByScope` previously treated `assertWorkspaceAutomationAllowed` as optional and did not skip `runWorktreeTeardownCommands` when `untrustedBacking` was already true or when archiving an unrecorded worktree directory. Four callers (`CreateAgentLifecycleDispatch`, `archiveIfSafe`, `paseo-tools` `archive_workspace`, and `handlePaseoWorktreeArchiveRequest`) also omitted `assertWorkspaceAutomationAllowed`, letting `paseo.json` teardown commands run during failed agent creation cleanup, first-turn auto-archive, auto-archive on merge, MCP workspace archive, and worktree archive RPCs.

Make `assertWorkspaceAutomationAllowed` and `isCheckoutUntrusted` required on `ArchiveDependencies`, skip teardown whenever the backing checkout is untrusted, any workspace on the checkout is blocked, or no active workspace record exists, and wire the guard through all archive callers.

* fix(server): scope archive teardown check to active checkout workspaces

`isCheckoutUntrusted` scans all workspace records by path, including previously archived records, so gating teardown on it suppressed `paseo.json` teardown for a fresh approved worktree that reused a previously archived unapproved slug path.

Keep teardown approval scoped to the active workspaces sharing the backing checkout at archive start (the records being archived plus active siblings), drop the null-workspace fallback target for unrecorded worktree-scope archives so they never run teardown or flip `untrustedBacking`, and verify caller wiring reaches `assertWorkspaceAutomationAllowed` directly.

* fix(server): inherit untrustedSource when unarchiving onto an active unapproved checkout

Unarchiving a previously approved workspace onto an existing directory that currently holds an active unapproved checkout left the restored workspace without `untrustedSource`. If the unapproved sibling was archived first, the directory remained on disk and archiving the restored workspace could run teardown commands.

Inherit `untrustedSource` from active workspaces sharing the checkout root in `ensureWorkspaceRecordUnarchived`, while ignoring already-archived historical records so restoring an approved checkout onto a reused path stays approved.

* fix(server): bind automation approval state to checkout worktree metadata

Keeping `untrustedSource` only on workspace records meant a retained unapproved worktree directory could lose its teardown block if its last unapproved workspace was archived and an older approved workspace was unarchived onto that path, while scanning archived records by path blocked fresh worktrees that reused a deleted slug.

Persist `untrustedSource` on the checkout itself in `paseo/worktree.json` when creating or restoring an unapproved worktree, clear it in `clearWorkspaceAutomationBlock` when setup is approved, and read it in both `workspace-archive-service` and `workspace-provisioning-service`. Deleting the worktree removes its metadata automatically, so fresh worktrees reusing the path start clean while retained checkouts keep their block across workspace archives and restores.

* fix(server): backfill worktree metadata when archiving retained unapproved checkouts

Unapproved checkouts created before `paseo/worktree.json` stored `untrustedSource` carry their block only in the workspace record. If archive keeps the directory on disk (such as a retained sibling or nested worktree), backfilling `untrustedSource` into `paseo/worktree.json` before removal ensures the retained checkout keeps its block even after its unapproved workspace record is archived.

* fix(server): never propagate archived untrustedSource onto fresh checkouts

Both archive metadata backfill and directory workspace creation previously consulted already-archived records matching a path, allowing an old archived unapproved record to copy `untrustedSource` onto a fresh approved worktree that reused the same slug path.

Ignore `untrustedSource` on already-archived records during archive target resolution and metadata backfill (only backfill when active workspaces are being archived), and share one `resolveCheckoutUntrustedSource` rule across `createWorkspaceForDirectory` and `ensureWorkspaceRecordUnarchived` that checks `paseo/worktree.json` first and falls back only to active workspaces.

* fix(server): align unarchived workspace approval state with the live checkout

Unarchiving an old unapproved workspace onto a path already owned by an active approved checkout kept the old record's stale `untrustedSource`, causing a later re-archive of that workspace to backfill the block onto the fresh checkout's metadata.

Align `ensureWorkspaceRecordUnarchived` symmetrically with the live checkout: adopt `untrustedSource` from `paseo/worktree.json` or active workspaces on the checkout when present, and drop stale `untrustedSource` when live active workspaces own an approved checkout at that path.

* fix(server): preserve block when opening a pre-upgrade retained checkout

Opening a pre-upgrade retained checkout directory whose last unapproved workspace was already archived before this change has no active workspace on the path and no `untrustedSource` in `paseo/worktree.json`.

In `resolveCheckoutUntrustedSource`, prefer `paseo/worktree.json`, then active workspaces on the checkout when any exist (so a fresh approved worktree at a reused path stays approved), and only when zero active workspaces exist on the directory fall back to the most recently archived record for that path.

* fix(server): share one checkout approval lookup across open and unarchive

* fix(server): resolve checkout approval state only from metadata and active workspaces

* fix(server): keep archive read-only on worktree approval metadata

* fix(server): serialize setup approval with archive checkout lock and backfill retained metadata

* fix(server): fail setup approval before clearing records when worktree metadata write fails
2026-11-24 17:46:23 +07:00
27 changed files with 2219 additions and 236 deletions
@@ -4,12 +4,15 @@
// never swallow entity tabs or lose the user's focus, and
// 2) splitting a tab out of a pane leaves a New tab behind, and the app must stay
// interactive in the [agent | New | explorer] state.
import { writeFileSync } from "node:fs";
import path from "node:path";
import { expect, type Locator, type Page } from "@playwright/test";
import { test } from "../support/fixtures";
import { gotoWorkspace } from "../support/helpers/launcher";
import { seedCorruptedWorkspaceLayout } from "../support/helpers/workspace-layout";
import {
openChangesTreePanel,
openFilesPanel,
waitForWorkspaceTabsVisible,
} from "../support/helpers/workspace-tabs";
@@ -317,3 +320,75 @@ test("reloading a saved hidden generated Explorer recovers a usable workspace",
await gotoWorkspace(page, otherWorkspace.workspaceId);
await expect(draftTabChip(page)).toHaveCount(1);
});
test("dragging a file tab into a split returns the previous pane to the tab you came from", async ({
page,
withWorkspace,
e2eWorkerClient,
}) => {
const workspace = await withWorkspace({ prefix: "split-prev-tab-focus-" });
writeFileSync(path.join(workspace.repoPath, "notes.md"), "# Notes\nhello\n");
const agentA = await e2eWorkerClient.createAgent({
provider: "mock",
cwd: workspace.repoPath,
workspaceId: workspace.workspaceId,
title: "Agent A",
});
const agentB = await e2eWorkerClient.createAgent({
provider: "mock",
cwd: workspace.repoPath,
workspaceId: workspace.workspaceId,
title: "Agent B",
});
await gotoWorkspace(page, workspace.workspaceId);
await waitForWorkspaceTabsVisible(page);
const mainPane = page.getByTestId("workspace-pane-main");
await expect(mainPane.getByTestId(`workspace-tab-agent_${agentA.id}`)).toBeVisible({
timeout: 30_000,
});
await expect(mainPane.getByTestId(`workspace-tab-agent_${agentB.id}`)).toBeVisible({
timeout: 30_000,
});
const initialTabs = await mainPane
.locator('[data-testid^="workspace-tab-"]:not([data-testid^="workspace-tab-context-"])')
.evaluateAll((els) => els.map((el) => el.getAttribute("data-testid")));
const firstTab = mainPane.getByTestId(initialTabs[0]!);
const secondTab = mainPane.getByTestId(initialTabs[1]!);
// Open FILE while on B so B is the birth parent, then navigate A -> FILE before splitting.
await secondTab.click({ position: { x: 12, y: 13 } });
await expect(secondTab).toHaveAttribute("aria-selected", "true");
await openFilesPanel(page);
await page
.getByTestId("file-explorer-tree-scroll")
.getByText("notes.md", { exact: true })
.click();
const fileTab = mainPane
.locator('[data-testid^="workspace-tab-file_"]:not([data-testid^="workspace-tab-context-"])')
.first();
await expect(fileTab).toBeVisible({ timeout: 15_000 });
await firstTab.click({ position: { x: 12, y: 13 } });
await expect(firstTab).toHaveAttribute("aria-selected", "true");
await fileTab.click({ position: { x: 12, y: 13 } });
await expect(fileTab).toHaveAttribute("aria-selected", "true");
const mainBox = await mainPane.boundingBox();
if (!mainBox) throw new Error("mainPane has no bounding box");
await dragChipTo(page, fileTab, {
x: mainBox.x + mainBox.width * 0.92,
y: mainBox.y + mainBox.height * 0.5,
});
await expect(
page.locator('[data-testid^="workspace-pane-"]').filter({ visible: true }),
).toHaveCount(2, { timeout: 10_000 });
await expect(firstTab).toHaveAttribute("aria-selected", "true");
await expect(secondTab).toHaveAttribute("aria-selected", "false");
});
@@ -11,6 +11,10 @@ import {
workspaceTabTargetsEqual,
} from "@/workspace-tabs/identity";
import { createNewWorkspaceTab } from "@/workspace-tabs/new-tab";
import {
resolveTabDepartureSuccessor,
type PaneTabFocusHistory,
} from "@/stores/workspace-tab-focus-policy";
export interface SplitPane {
id: string;
@@ -75,6 +79,7 @@ interface InsertChildIntoGroupInput {
interface DetachTabFromTreeInput {
tabId: string;
preserveEmptyPaneId?: string | null;
replacementFocusedTabId?: string | null;
}
interface DetachTabFromTreeResult {
@@ -96,6 +101,7 @@ interface InsertSplitInternalInput {
tabId: string;
position: "left" | "right" | "top" | "bottom";
createNodeId: (prefix: WorkspaceLayoutNodeIdPrefix) => string;
replacementFocusedTabId?: string | null;
}
interface InsertSplitInternalResult {
@@ -139,6 +145,7 @@ interface OpenTabInLayoutInput {
explorerSidebarPaneId: string | null;
/** Live sheets share the workspace's panel-instance namespace with its tabs. */
reservedTabIds?: ReadonlySet<string>;
paneFocusHistory?: PaneTabFocusHistory;
}
interface CreateTabInLayoutInput extends OpenTabInLayoutInput {
@@ -207,6 +214,7 @@ interface SplitPaneInLayoutInput {
position: "left" | "right" | "top" | "bottom";
createNodeId: (prefix: WorkspaceLayoutNodeIdPrefix) => string;
maxTreeDepth: number;
paneFocusHistory?: PaneTabFocusHistory;
}
interface SplitPaneInLayoutResult {
@@ -233,6 +241,7 @@ interface MoveTabToPaneInLayoutInput {
tabId: string;
toPaneId: string;
explorerSidebarPaneId?: string | null;
paneFocusHistory?: PaneTabFocusHistory;
}
interface FocusTabInLayoutInput {
@@ -815,6 +824,10 @@ function detachTabFromTree(
const nextPane = normalizePaneAfterTabChange({
...paneNode.pane,
tabs: paneNode.pane.tabs.filter((entry) => entry.tabId !== input.tabId),
focusedTabId:
paneNode.pane.focusedTabId === input.tabId
? (input.replacementFocusedTabId ?? paneNode.pane.focusedTabId)
: paneNode.pane.focusedTabId,
});
const nextRoot = replaceNodeAtPath(root, panePath, () => ({ kind: "pane", pane: nextPane }));
@@ -970,6 +983,7 @@ function insertSplitInternal(input: InsertSplitInternalInput): InsertSplitIntern
const detached = detachTabFromTree(input.root, {
tabId: input.tabId,
preserveEmptyPaneId: input.targetPaneId,
replacementFocusedTabId: input.replacementFocusedTabId,
});
invariant(detached.tab, `Tab not found: ${input.tabId}`);
@@ -1165,6 +1179,14 @@ export function collectAllPanes(root: SplitNode): SplitPane[] {
return internalRoot.group.children.flatMap((child) => collectAllPanes(child));
}
export function collectAllPanesIncludingHidden(root: SplitNode): SplitPane[] {
const internalRoot = asInternalNode(root);
if (internalRoot.kind === "pane") {
return [internalRoot.pane];
}
return internalRoot.group.children.flatMap((child) => collectAllPanesIncludingHidden(child));
}
function isEphemeralTab(tab: WorkspaceTab): boolean {
return tab.target.kind === "commit_diff" || tab.target.kind === "new_tab";
}
@@ -1508,6 +1530,7 @@ export function openTabInLayoutFocused(input: OpenTabInLayoutInput): OpenTabInLa
layout: nextLayout,
tabId: existingTab.tabId,
placement: input.placement,
paneFocusHistory: input.paneFocusHistory,
}),
};
}
@@ -1534,6 +1557,7 @@ export function revealTargetInLayout(input: CreateTabInLayoutInput): OpenTabInLa
layout: updateExistingTabTarget(input.layout, existingTab, input.target),
tabId: existingTab.tabId,
placement: input.placement,
paneFocusHistory: input.paneFocusHistory,
}),
};
}
@@ -1551,6 +1575,7 @@ function revealExistingTab(input: {
layout: WorkspaceLayout;
tabId: string;
placement: WorkspaceTabPlacement;
paneFocusHistory?: PaneTabFocusHistory;
}): WorkspaceLayout {
if (input.placement.mode === "pane") {
const currentPane = findPaneContainingTab(asInternalNode(input.layout.root), input.tabId);
@@ -1559,6 +1584,7 @@ function revealExistingTab(input: {
layout: input.layout,
tabId: input.tabId,
toPaneId: input.placement.paneId,
paneFocusHistory: input.paneFocusHistory,
});
if (moved) {
return moved;
@@ -1600,9 +1626,9 @@ export function closeTabInLayout(input: CloseTabInLayoutInput): WorkspaceLayout
? pane.id
: null;
const closeSuccessorTabId = getCloseSuccessorTabId({
const closeSuccessorTabId = resolveTabDepartureSuccessor("close", {
pane,
tabId: input.tabId,
departingTabId: input.tabId,
openTabIds: new Set(collectAllTabs(internalLayout.root).map((tab) => tab.tabId)),
parentTabIdByTabId: input.layout.parentTabIdByTabId,
});
@@ -1986,16 +2012,26 @@ export function splitPaneInLayout(input: SplitPaneInLayoutInput): SplitPaneInLay
if (!findPaneById(layout.root, input.targetPaneId)) {
return null;
}
if (!findPaneContainingTab(layout.root, input.tabId)) {
const sourcePane = findPaneContainingTab(layout.root, input.tabId);
if (!sourcePane) {
return null;
}
const replacementFocusedTabId = resolveTabDepartureSuccessor("relocate", {
pane: sourcePane,
departingTabId: input.tabId,
openTabIds: new Set(collectAllTabs(layout.root).map((tab) => tab.tabId)),
parentTabIdByTabId: input.layout.parentTabIdByTabId,
paneFocusHistory: input.paneFocusHistory,
});
const result = insertSplitInternal({
root: layout.root,
targetPaneId: input.targetPaneId,
tabId: input.tabId,
position: input.position,
createNodeId: input.createNodeId,
replacementFocusedTabId,
});
if (getTreeDepth(result.root) > input.maxTreeDepth) {
return null;
@@ -2115,6 +2151,17 @@ export function moveTabToPaneInLayout(input: MoveTabToPaneInLayoutInput): Worksp
});
}
const replacementFocusedTabId =
sourcePane.id === input.toPaneId
? null
: resolveTabDepartureSuccessor("relocate", {
pane: sourcePane,
departingTabId: input.tabId,
openTabIds: new Set(collectAllTabs(layout.root).map((tab) => tab.tabId)),
parentTabIdByTabId: input.layout.parentTabIdByTabId,
paneFocusHistory: input.paneFocusHistory,
});
const detached = detachTabFromTree(layout.root, {
tabId: input.tabId,
// Crossing into or out of Explorer cannot remove either host shell.
@@ -2124,6 +2171,7 @@ export function moveTabToPaneInLayout(input: MoveTabToPaneInLayoutInput): Worksp
input.toPaneId === input.explorerSidebarPaneId
? sourcePane.id
: null,
replacementFocusedTabId,
});
if (!detached.tab) {
return null;
@@ -2280,29 +2328,6 @@ function withNormalizedParentTabMap(layout: WorkspaceLayout): WorkspaceLayout {
: { root: layout.root, focusedPaneId: layout.focusedPaneId };
}
function getCloseSuccessorTabId(input: {
pane: SplitPane;
tabId: string;
openTabIds: ReadonlySet<string>;
parentTabIdByTabId?: Record<string, string>;
}): string | null {
if (input.pane.focusedTabId !== input.tabId) {
return null;
}
const tabIndex = input.pane.tabIds.indexOf(input.tabId);
const parentTabId = input.parentTabIdByTabId?.[input.tabId] ?? null;
if (parentTabId && input.openTabIds.has(parentTabId)) {
return parentTabId;
}
return (
input.pane.tabIds[tabIndex + 1] ??
(tabIndex > 0 ? input.pane.tabIds[tabIndex - 1] : null) ??
null
);
}
function getFocusedPaneIdAfterTabClose(input: {
root: SplitNode;
focusedPaneId: string | null;
@@ -5496,3 +5496,245 @@ it("reentering a workspace restores its suspended pane without choosing another
expect(store.getState().layoutByWorkspace[workspaceKey]!.focusedPaneId).toBe(paneId);
expect(store.getState().focusRequest).toEqual({ workspaceKey, tabId });
});
describe("tab departure focus policy", () => {
it("splitPane returns the source pane to the most recently focused tab instead of the rightmost tab", () => {
const store = createWorkspaceLayoutStore(workspaceLayoutIds);
const workspaceKey = "server:split-recency";
const tabA = store.getState().openTab({
workspaceKey,
target: { kind: "agent", agentId: "agent-a" },
intent: "reveal",
})!;
const tabB = store.getState().openTab({
workspaceKey,
target: { kind: "agent", agentId: "agent-b" },
intent: "reveal",
})!;
// Open FILE while B is active (parentTabId = B) to prove focus recency wins over birth parent.
const tabFile = store.getState().openTab({
workspaceKey,
target: { kind: "file", path: "/repo/notes.md" },
intent: "reveal",
parentTabId: tabB,
})!;
store.getState().focusTab(workspaceKey, tabA);
store.getState().focusTab(workspaceKey, tabFile);
const newPaneId = store.getState().splitPane(workspaceKey, {
tabId: tabFile,
targetPaneId: "main",
position: "right",
});
const layout = store.getState().layoutByWorkspace[workspaceKey]!;
expect(newPaneId).toBeTruthy();
expect(layout.focusedPaneId).toBe(newPaneId);
expect(findPaneById(layout.root, newPaneId)?.focusedTabId).toBe(tabFile);
expect(findPaneById(layout.root, "main")?.tabIds).toEqual([tabA, tabB]);
expect(findPaneById(layout.root, "main")?.focusedTabId).toBe(tabA);
});
it("moveTabToPane returns the source pane to the most recently focused remaining tab", () => {
const store = createWorkspaceLayoutStore(workspaceLayoutIds);
const workspaceKey = "server:move-recency";
const tabA = store.getState().openTab({
workspaceKey,
target: { kind: "agent", agentId: "agent-a" },
intent: "reveal",
})!;
const tabB = store.getState().openTab({
workspaceKey,
target: { kind: "agent", agentId: "agent-b" },
intent: "reveal",
})!;
const tabFile = store.getState().openTab({
workspaceKey,
target: { kind: "file", path: "/repo/notes.md" },
intent: "reveal",
})!;
const sidePaneId = store.getState().splitPaneEmpty(workspaceKey, {
targetPaneId: "main",
position: "right",
})!;
store.getState().focusTab(workspaceKey, tabA);
store.getState().focusTab(workspaceKey, tabFile);
store.getState().moveTabToPane(workspaceKey, tabFile, sidePaneId);
const layout = store.getState().layoutByWorkspace[workspaceKey]!;
expect(layout.focusedPaneId).toBe(sidePaneId);
expect(findPaneById(layout.root, sidePaneId)?.focusedTabId).toBe(tabFile);
expect(findPaneById(layout.root, "main")?.tabIds).toEqual([tabA, tabB]);
expect(findPaneById(layout.root, "main")?.focusedTabId).toBe(tabA);
});
it("explicit pane-local reveal returns the source pane to its most recently focused tab", () => {
const store = createWorkspaceLayoutStore(workspaceLayoutIds);
const workspaceKey = "server:pane-reveal-recency";
const tabA = store.getState().openTab({
workspaceKey,
target: { kind: "agent", agentId: "agent-a" },
intent: "reveal",
})!;
store.getState().openTab({
workspaceKey,
target: { kind: "agent", agentId: "agent-b" },
intent: "reveal",
});
const fileTarget = { kind: "file", path: "/repo/notes.md" } as const;
const tabFile = store.getState().openTab({
workspaceKey,
target: fileTarget,
intent: "reveal",
})!;
const sidePaneId = store.getState().ensureSidePane(workspaceKey, { focus: false })!;
store.getState().focusTab(workspaceKey, tabA);
store.getState().focusTab(workspaceKey, tabFile);
store.getState().openTab({
workspaceKey,
target: fileTarget,
intent: "reveal",
placement: { mode: "pane", paneId: sidePaneId },
});
const layout = store.getState().layoutByWorkspace[workspaceKey]!;
expect(findPaneById(layout.root, "main")?.focusedTabId).toBe(tabA);
expect(findPaneById(layout.root, sidePaneId)?.focusedTabId).toBe(tabFile);
});
it("seeds focus recency from a hydrated layout on the first tab switch", () => {
const store = createWorkspaceLayoutStore(workspaceLayoutIds);
const workspaceKey = "server:hydrated-recency";
store.setState((state) => ({
...state,
layoutByWorkspace: {
...state.layoutByWorkspace,
[workspaceKey]: {
root: createPane({
id: "main",
tabIds: ["agent_a", "agent_b", "file_/repo/notes.md"],
focusedTabId: "agent_a",
}),
focusedPaneId: "main",
},
},
}));
store.getState().focusTab(workspaceKey, "file_/repo/notes.md");
store.getState().splitPane(workspaceKey, {
tabId: "file_/repo/notes.md",
targetPaneId: "main",
position: "right",
});
const layout = store.getState().layoutByWorkspace[workspaceKey]!;
expect(findPaneById(layout.root, "main")?.focusedTabId).toBe("agent_a");
});
it("falls back to a same-pane parent tab when relocating immediately after hydration", () => {
const store = createWorkspaceLayoutStore(workspaceLayoutIds);
const workspaceKey = "server:hydrated-parent-fallback";
store.setState((state) => ({
...state,
layoutByWorkspace: {
...state.layoutByWorkspace,
[workspaceKey]: {
root: createPane({
id: "main",
tabIds: ["agent_a", "agent_b", "file_/repo/notes.md"],
focusedTabId: "file_/repo/notes.md",
}),
focusedPaneId: "main",
parentTabIdByTabId: { "file_/repo/notes.md": "agent_a" },
},
},
}));
store.getState().splitPane(workspaceKey, {
tabId: "file_/repo/notes.md",
targetPaneId: "main",
position: "right",
});
const layout = store.getState().layoutByWorkspace[workspaceKey]!;
expect(findPaneById(layout.root, "main")?.focusedTabId).toBe("agent_a");
});
it("tracks multi-step recency and preserves history across convertDraftToAgent", () => {
const store = createWorkspaceLayoutStore(workspaceLayoutIds);
const workspaceKey = "server:multi-step-recency";
const tabA = store.getState().openTab({
workspaceKey,
target: { kind: "draft", draftId: "draft-a" },
intent: "reveal",
})!;
const tabB = store.getState().openTab({
workspaceKey,
target: { kind: "agent", agentId: "agent-b" },
intent: "reveal",
})!;
const tabFile = store.getState().openTab({
workspaceKey,
target: { kind: "file", path: "/repo/notes.md" },
intent: "reveal",
})!;
store.getState().focusTab(workspaceKey, tabB);
store.getState().focusTab(workspaceKey, tabA);
store.getState().focusTab(workspaceKey, tabFile);
const convertedA = store.getState().convertDraftToAgent(workspaceKey, tabA, "agent-a")!;
store.getState().splitPane(workspaceKey, {
tabId: tabFile,
targetPaneId: "main",
position: "right",
});
expect(
findPaneById(store.getState().layoutByWorkspace[workspaceKey]!.root, "main")?.focusedTabId,
).toBe(convertedA);
store.getState().focusTab(workspaceKey, convertedA);
store.getState().splitPane(workspaceKey, {
tabId: convertedA,
targetPaneId: "main",
position: "bottom",
});
expect(
findPaneById(store.getState().layoutByWorkspace[workspaceKey]!.root, "main")?.focusedTabId,
).toBe(tabB);
});
it("keeps the source pane focused tab unchanged when dragging an unfocused tab", () => {
const store = createWorkspaceLayoutStore(workspaceLayoutIds);
const workspaceKey = "server:unfocused-drag";
const tabA = store.getState().openTab({
workspaceKey,
target: { kind: "agent", agentId: "agent-a" },
intent: "reveal",
})!;
store.getState().openTab({
workspaceKey,
target: { kind: "agent", agentId: "agent-b" },
intent: "reveal",
});
const tabFile = store.getState().openTab({
workspaceKey,
target: { kind: "file", path: "/repo/notes.md" },
intent: "reveal",
})!;
store.getState().focusTab(workspaceKey, tabA);
store.getState().splitPane(workspaceKey, {
tabId: tabFile,
targetPaneId: "main",
position: "right",
});
expect(
findPaneById(store.getState().layoutByWorkspace[workspaceKey]!.root, "main")?.focusedTabId,
).toBe(tabA);
});
});
+103 -105
View File
@@ -18,6 +18,7 @@ import {
closePaneInLayout,
closeTabInLayout,
collectAllPanes,
collectAllPanesIncludingHidden,
collectAllTabs,
convertDraftToAgentInLayout,
createTabInLayout,
@@ -69,6 +70,10 @@ import { isSheetTabModified, resolveCompactSheetPolicy } from "@/workspace-tabs/
import { panelResourceKey, type CompactSheetPolicy } from "@/panels/panel-manifest";
import { createValidatedPersistStorage } from "@/storage/validated-persist-storage";
import { panelTargetSupportsHostForWorkspaceKey } from "@/plugins/workspace-panels/locations";
import {
syncPaneTabFocusHistory,
type PaneTabFocusHistory,
} from "@/stores/workspace-tab-focus-policy";
export {
AMBIENT_PLACEMENT,
@@ -153,6 +158,7 @@ interface WorkspaceLayoutStore {
pinnedAgentIdsByWorkspace: Record<string, Set<string>>;
hiddenAgentIdsByWorkspace: Record<string, Set<string>>;
focusRestorationByWorkspace: Record<string, WorkspaceFocusRestorationState>;
paneTabFocusHistoryByWorkspace: Record<string, PaneTabFocusHistory>;
explorerSidebarPaneIdByWorkspace: Record<string, string | null>;
sidePaneIdByWorkspace: Record<string, string | null>;
/** Workspaces where PR detection already added its tab once; a closed tab never returns. */
@@ -689,6 +695,35 @@ function withoutFocusRestoration(
return { focusRestorationByWorkspace };
}
function withUpdatedWorkspaceLayout(
state: Pick<WorkspaceLayoutStore, "layoutByWorkspace" | "paneTabFocusHistoryByWorkspace">,
workspaceKey: string,
nextLayout: WorkspaceLayout,
renamedTab?: { from: string; to: string } | null,
): Pick<WorkspaceLayoutStore, "layoutByWorkspace" | "paneTabFocusHistoryByWorkspace"> {
const previousLayout = state.layoutByWorkspace[workspaceKey] ?? null;
const previousHistory = state.paneTabFocusHistoryByWorkspace[workspaceKey];
const nextHistory = syncPaneTabFocusHistory({
previousHistory,
previousPanes: previousLayout ? collectAllPanesIncludingHidden(previousLayout.root) : [],
nextPanes: collectAllPanesIncludingHidden(nextLayout.root),
renamedTab,
});
return {
layoutByWorkspace: {
...state.layoutByWorkspace,
[workspaceKey]: nextLayout,
},
paneTabFocusHistoryByWorkspace:
nextHistory === previousHistory
? state.paneTabFocusHistoryByWorkspace
: {
...state.paneTabFocusHistoryByWorkspace,
[workspaceKey]: nextHistory,
},
};
}
function reconcileRememberedSidePane(
state: WorkspaceLayoutStore,
workspaceKey: string,
@@ -873,6 +908,7 @@ function promoteSheetToTab(
now: tab.createdAt,
createTabId: () => tab.tabId,
state: tab.state,
paneFocusHistory: state.paneTabFocusHistoryByWorkspace[workspaceKey],
};
const result = isTargetOpenAsTab(placement.layout, tab.target)
? revealTargetInLayout(input)
@@ -900,7 +936,7 @@ function promoteSheetToTab(
tab.target.agentId,
)
: state.hiddenAgentIdsByWorkspace,
layoutByWorkspace: { ...state.layoutByWorkspace, [workspaceKey]: nextLayout },
...withUpdatedWorkspaceLayout(state, workspaceKey, nextLayout),
},
};
}
@@ -1109,6 +1145,7 @@ export function createWorkspaceLayoutStore(
pinnedAgentIdsByWorkspace: {},
hiddenAgentIdsByWorkspace: {},
focusRestorationByWorkspace: {},
paneTabFocusHistoryByWorkspace: {},
explorerSidebarPaneIdByWorkspace: {},
sidePaneIdByWorkspace: {},
pullRequestTabAutoOpenedByWorkspace: {},
@@ -1199,6 +1236,7 @@ export function createWorkspaceLayoutStore(
target: normalizedTarget,
now: Date.now(),
createTabId: createWorkspaceTabInstanceId,
paneFocusHistory: get().paneTabFocusHistoryByWorkspace[normalizedWorkspaceKey],
});
}
if (!result) {
@@ -1220,6 +1258,13 @@ export function createWorkspaceLayoutStore(
placement.layout.focusedPaneId,
);
const shouldPinAgent = input.pin === true && normalizedTarget.kind === "agent";
const finalLayout = parentTabId
? attachParentTab({
layout: nextLayout,
childTabId: result.tabId,
parentTabId,
})
: nextLayout;
set((state) => ({
...withoutFocusRestoration(state, normalizedWorkspaceKey),
...advancePanelRevision(state, normalizedWorkspaceKey, result.tabId, normalizedTarget),
@@ -1243,16 +1288,7 @@ export function createWorkspaceLayoutStore(
normalizedTarget.agentId,
)
: state.pinnedAgentIdsByWorkspace,
layoutByWorkspace: {
...state.layoutByWorkspace,
[normalizedWorkspaceKey]: parentTabId
? attachParentTab({
layout: nextLayout,
childTabId: result.tabId,
parentTabId,
})
: nextLayout,
},
...withUpdatedWorkspaceLayout(state, normalizedWorkspaceKey, finalLayout),
}));
return result.tabId;
},
@@ -1304,14 +1340,15 @@ export function createWorkspaceLayoutStore(
normalizedWorkspaceKey,
);
return {
layoutByWorkspace: {
...state.layoutByWorkspace,
[normalizedWorkspaceKey]: keepWorkspaceFocusOutOfExplorerSidebar(
...withUpdatedWorkspaceLayout(
state,
normalizedWorkspaceKey,
keepWorkspaceFocusOutOfExplorerSidebar(
currentLayout,
paneId,
currentLayout.focusedPaneId,
),
},
),
explorerSidebarPaneIdByWorkspace: {
...state.explorerSidebarPaneIdByWorkspace,
[normalizedWorkspaceKey]: paneId,
@@ -1326,9 +1363,7 @@ export function createWorkspaceLayoutStore(
set((state) => {
const layout = state.layoutByWorkspace[workspaceKey];
const next = setPaneHiddenInLayout({ layout, paneId, hidden: false });
return next
? { layoutByWorkspace: { ...state.layoutByWorkspace, [workspaceKey]: next } }
: state;
return next ? withUpdatedWorkspaceLayout(state, workspaceKey, next) : state;
});
return paneId;
},
@@ -1351,12 +1386,7 @@ export function createWorkspaceLayoutStore(
return state;
}
return {
layoutByWorkspace: {
...state.layoutByWorkspace,
[normalizedWorkspaceKey]: nextLayout,
},
};
return withUpdatedWorkspaceLayout(state, normalizedWorkspaceKey, nextLayout);
});
},
ensureSidePane: (workspaceKey, options) => {
@@ -1388,13 +1418,13 @@ export function createWorkspaceLayoutStore(
}
set((state) => ({
...withoutFocusRestoration(state, normalizedWorkspaceKey),
layoutByWorkspace: {
...state.layoutByWorkspace,
[normalizedWorkspaceKey]:
options?.focus === false
? { ...result.layout, focusedPaneId: layout.focusedPaneId }
: result.layout,
},
...withUpdatedWorkspaceLayout(
state,
normalizedWorkspaceKey,
options?.focus === false
? { ...result.layout, focusedPaneId: layout.focusedPaneId }
: result.layout,
),
sidePaneIdByWorkspace: {
...state.sidePaneIdByWorkspace,
[normalizedWorkspaceKey]: result.paneId,
@@ -1441,10 +1471,7 @@ export function createWorkspaceLayoutStore(
return {
...withoutFocusRestoration(state, normalizedWorkspaceKey),
...reconcileRememberedSidePane(state, normalizedWorkspaceKey, nextLayout),
layoutByWorkspace: {
...state.layoutByWorkspace,
[normalizedWorkspaceKey]: nextLayout,
},
...withUpdatedWorkspaceLayout(state, normalizedWorkspaceKey, nextLayout),
};
}
const closedLayout = closeTabInLayout({
@@ -1476,10 +1503,7 @@ export function createWorkspaceLayoutStore(
return {
...withoutFocusRestoration(state, normalizedWorkspaceKey),
...reconcileRememberedSidePane(state, normalizedWorkspaceKey, nextLayout),
layoutByWorkspace: {
...state.layoutByWorkspace,
[normalizedWorkspaceKey]: nextLayout,
},
...withUpdatedWorkspaceLayout(state, normalizedWorkspaceKey, nextLayout),
};
});
},
@@ -1541,9 +1565,9 @@ export function createWorkspaceLayoutStore(
...withoutFocusRestoration(state, normalizedWorkspaceKey),
// Choosing a tab dismisses the sheets that cover it.
...dismissSheets(state, normalizedWorkspaceKey),
layoutByWorkspace: nextLayout
? { ...state.layoutByWorkspace, [normalizedWorkspaceKey]: nextLayout }
: state.layoutByWorkspace,
...(nextLayout
? withUpdatedWorkspaceLayout(state, normalizedWorkspaceKey, nextLayout)
: {}),
};
});
},
@@ -1567,10 +1591,11 @@ export function createWorkspaceLayoutStore(
focusRequest: { workspaceKey: normalizedWorkspaceKey, tabId: normalizedTabId },
// Choosing a tab dismisses the sheets that cover it.
...dismissSheets(state, normalizedWorkspaceKey),
layoutByWorkspace: {
...state.layoutByWorkspace,
[normalizedWorkspaceKey]: nextLayout ?? layout,
},
...withUpdatedWorkspaceLayout(
state,
normalizedWorkspaceKey,
nextLayout ?? layout,
),
}
: state;
});
@@ -1622,6 +1647,8 @@ export function createWorkspaceLayoutStore(
state: tabState,
});
if (!result) return null;
const renamedTab =
result.tabId !== normalizedTabId ? { from: normalizedTabId, to: result.tabId } : null;
set((state) => ({
...withoutFocusRestoration(state, normalizedWorkspaceKey),
...advancePanelRevision(state, normalizedWorkspaceKey, result.tabId, normalizedTarget),
@@ -1633,10 +1660,7 @@ export function createWorkspaceLayoutStore(
normalizedWorkspaceKey,
normalizedTarget.agentId,
),
layoutByWorkspace: {
...state.layoutByWorkspace,
[normalizedWorkspaceKey]: result.layout,
},
...withUpdatedWorkspaceLayout(state, normalizedWorkspaceKey, result.layout, renamedTab),
}));
return result.tabId;
},
@@ -1660,12 +1684,7 @@ export function createWorkspaceLayoutStore(
state: tabState,
});
if (!layout) return state;
return {
layoutByWorkspace: {
...state.layoutByWorkspace,
[normalizedWorkspaceKey]: layout,
},
};
return withUpdatedWorkspaceLayout(state, normalizedWorkspaceKey, layout);
});
},
convertDraftToAgent: (workspaceKey, tabId, agentId) => {
@@ -1690,6 +1709,8 @@ export function createWorkspaceLayoutStore(
return null;
}
const renamedTab =
result.tabId !== normalizedTabId ? { from: normalizedTabId, to: result.tabId } : null;
set((state) => ({
...(result.layout.focusedPaneId !== null
? (withoutFocusRestoration(state, normalizedWorkspaceKey) ?? {})
@@ -1699,10 +1720,7 @@ export function createWorkspaceLayoutStore(
normalizedWorkspaceKey,
normalizedAgentId,
),
layoutByWorkspace: {
...state.layoutByWorkspace,
[normalizedWorkspaceKey]: result.layout,
},
...withUpdatedWorkspaceLayout(state, normalizedWorkspaceKey, result.layout, renamedTab),
}));
return result.tabId;
@@ -1766,10 +1784,7 @@ export function createWorkspaceLayoutStore(
return {
...(sheetAgentGone ? withSheets(state, normalizedWorkspaceKey, fittingSheets) : {}),
pinnedAgentIdsByWorkspace,
layoutByWorkspace: {
...state.layoutByWorkspace,
[normalizedWorkspaceKey]: nextLayout,
},
...withUpdatedWorkspaceLayout(state, normalizedWorkspaceKey, nextLayout),
};
});
},
@@ -1788,12 +1803,7 @@ export function createWorkspaceLayoutStore(
return state;
}
return {
layoutByWorkspace: {
...state.layoutByWorkspace,
[normalizedWorkspaceKey]: nextLayout,
},
};
return withUpdatedWorkspaceLayout(state, normalizedWorkspaceKey, nextLayout);
});
},
getWorkspaceTabs: (workspaceKey) => {
@@ -1842,6 +1852,7 @@ export function createWorkspaceLayoutStore(
position: input.position,
maxTreeDepth: MAX_TREE_DEPTH,
createNodeId: ids.createNodeId,
paneFocusHistory: get().paneTabFocusHistoryByWorkspace[normalizedWorkspaceKey],
});
if (!result) {
return null;
@@ -1849,10 +1860,7 @@ export function createWorkspaceLayoutStore(
set((state) => ({
...withoutFocusRestoration(state, normalizedWorkspaceKey),
layoutByWorkspace: {
...state.layoutByWorkspace,
[normalizedWorkspaceKey]: result.layout,
},
...withUpdatedWorkspaceLayout(state, normalizedWorkspaceKey, result.layout),
}));
return result.paneId;
@@ -1886,10 +1894,7 @@ export function createWorkspaceLayoutStore(
set((state) => ({
...withoutFocusRestoration(state, normalizedWorkspaceKey),
layoutByWorkspace: {
...state.layoutByWorkspace,
[normalizedWorkspaceKey]: result.layout,
},
...withUpdatedWorkspaceLayout(state, normalizedWorkspaceKey, result.layout),
}));
return result.paneId;
@@ -1928,6 +1933,7 @@ export function createWorkspaceLayoutStore(
tabId: normalizedTabId,
toPaneId: normalizedToPaneId,
explorerSidebarPaneId,
paneFocusHistory: state.paneTabFocusHistoryByWorkspace[normalizedWorkspaceKey],
});
if (!nextLayout) {
return state;
@@ -1945,10 +1951,7 @@ export function createWorkspaceLayoutStore(
return {
...withoutFocusRestoration(state, normalizedWorkspaceKey),
layoutByWorkspace: {
...state.layoutByWorkspace,
[normalizedWorkspaceKey]: normalizedNextLayout,
},
...withUpdatedWorkspaceLayout(state, normalizedWorkspaceKey, normalizedNextLayout),
sidePaneIdByWorkspace:
rememberedSidePaneId &&
!findPaneById(normalizedNextLayout.root, rememberedSidePaneId)
@@ -1986,10 +1989,7 @@ export function createWorkspaceLayoutStore(
return {
...withoutFocusRestoration(state, normalizedWorkspaceKey),
layoutByWorkspace: {
...state.layoutByWorkspace,
[normalizedWorkspaceKey]: nextLayout,
},
...withUpdatedWorkspaceLayout(state, normalizedWorkspaceKey, nextLayout),
sidePaneIdByWorkspace:
state.sidePaneIdByWorkspace[normalizedWorkspaceKey] === normalizedPaneId
? {
@@ -2035,9 +2035,9 @@ export function createWorkspaceLayoutStore(
? { workspaceKey: normalizedWorkspaceKey, tabId: pane.focusedTabId }
: null,
...withoutFocusRestoration(state, normalizedWorkspaceKey),
layoutByWorkspace: nextLayout
? { ...state.layoutByWorkspace, [normalizedWorkspaceKey]: nextLayout }
: state.layoutByWorkspace,
...(nextLayout
? withUpdatedWorkspaceLayout(state, normalizedWorkspaceKey, nextLayout)
: {}),
};
});
},
@@ -2061,11 +2061,11 @@ export function createWorkspaceLayoutStore(
tokens: [...(currentRestoration?.tokens ?? []), token],
},
},
layoutByWorkspace: {
...state.layoutByWorkspace,
[normalizedWorkspaceKey]:
layout.focusedPaneId === null ? layout : { ...layout, focusedPaneId: null },
},
...withUpdatedWorkspaceLayout(
state,
normalizedWorkspaceKey,
layout.focusedPaneId === null ? layout : { ...layout, focusedPaneId: null },
),
};
});
return token;
@@ -2116,13 +2116,10 @@ export function createWorkspaceLayoutStore(
return {
focusRestorationByWorkspace: remainingRestorations,
layoutByWorkspace: {
...state.layoutByWorkspace,
[normalizedWorkspaceKey]: {
...layout,
focusedPaneId: restorePaneId,
},
},
...withUpdatedWorkspaceLayout(state, normalizedWorkspaceKey, {
...layout,
focusedPaneId: restorePaneId,
}),
};
});
},
@@ -2175,10 +2172,7 @@ export function createWorkspaceLayoutStore(
return {
...withoutFocusRestoration(state, normalizedWorkspaceKey),
layoutByWorkspace: {
...state.layoutByWorkspace,
[normalizedWorkspaceKey]: nextLayout,
},
...withUpdatedWorkspaceLayout(state, normalizedWorkspaceKey, nextLayout),
};
});
},
@@ -2276,6 +2270,7 @@ export function createWorkspaceLayoutStore(
normalizedWorkspaceKey in state.pinnedAgentIdsByWorkspace ||
normalizedWorkspaceKey in state.hiddenAgentIdsByWorkspace ||
normalizedWorkspaceKey in state.focusRestorationByWorkspace ||
normalizedWorkspaceKey in state.paneTabFocusHistoryByWorkspace ||
normalizedWorkspaceKey in state.explorerSidebarPaneIdByWorkspace ||
normalizedWorkspaceKey in state.sidePaneIdByWorkspace ||
normalizedWorkspaceKey in state.pullRequestTabAutoOpenedByWorkspace ||
@@ -2303,6 +2298,8 @@ export function createWorkspaceLayoutStore(
state.hiddenAgentIdsByWorkspace;
const { [normalizedWorkspaceKey]: _restoration, ...focusRestorationByWorkspace } =
state.focusRestorationByWorkspace;
const { [normalizedWorkspaceKey]: _focusHistory, ...paneTabFocusHistoryByWorkspace } =
state.paneTabFocusHistoryByWorkspace;
const {
[normalizedWorkspaceKey]: _explorerSidebarPane,
...explorerSidebarPaneIdByWorkspace
@@ -2319,6 +2316,7 @@ export function createWorkspaceLayoutStore(
pinnedAgentIdsByWorkspace,
hiddenAgentIdsByWorkspace,
focusRestorationByWorkspace,
paneTabFocusHistoryByWorkspace,
explorerSidebarPaneIdByWorkspace,
sidePaneIdByWorkspace,
};
@@ -0,0 +1,115 @@
import { describe, expect, it } from "vitest";
import {
resolveTabDepartureSuccessor,
syncPaneTabFocusHistory,
} from "./workspace-tab-focus-policy";
describe("workspace tab departure focus policy", () => {
it("relocate prefers most recently focused remaining tab over parent and neighbor", () => {
const successor = resolveTabDepartureSuccessor("relocate", {
pane: { id: "main", tabIds: ["a", "b", "file"], focusedTabId: "file" },
departingTabId: "file",
openTabIds: new Set(["a", "b", "file"]),
parentTabIdByTabId: { file: "b" },
paneFocusHistory: { main: ["file", "a", "b"] },
});
expect(successor).toBe("a");
});
it("relocate falls back to same-pane parent when focus history has no remaining tab", () => {
const successor = resolveTabDepartureSuccessor("relocate", {
pane: { id: "main", tabIds: ["a", "b", "file"], focusedTabId: "file" },
departingTabId: "file",
openTabIds: new Set(["a", "b", "file"]),
parentTabIdByTabId: { file: "a" },
});
expect(successor).toBe("a");
});
it("relocate ignores a parent tab in another pane and falls back to source-pane neighbor", () => {
const successor = resolveTabDepartureSuccessor("relocate", {
pane: { id: "main", tabIds: ["a", "b", "file"], focusedTabId: "file" },
departingTabId: "file",
openTabIds: new Set(["other-pane-parent", "a", "b", "file"]),
parentTabIdByTabId: { file: "other-pane-parent" },
});
expect(successor).toBe("b");
});
it("close prefers open parent tab anywhere, then right neighbor, then left neighbor", () => {
expect(
resolveTabDepartureSuccessor("close", {
pane: { id: "main", tabIds: ["a", "file", "b"], focusedTabId: "file" },
departingTabId: "file",
openTabIds: new Set(["other-parent", "a", "file", "b"]),
parentTabIdByTabId: { file: "other-parent" },
paneFocusHistory: { main: ["file", "a", "b"] },
}),
).toBe("other-parent");
expect(
resolveTabDepartureSuccessor("close", {
pane: { id: "main", tabIds: ["a", "file", "b"], focusedTabId: "file" },
departingTabId: "file",
openTabIds: new Set(["a", "file", "b"]),
paneFocusHistory: { main: ["file", "a", "b"] },
}),
).toBe("b");
expect(
resolveTabDepartureSuccessor("close", {
pane: { id: "main", tabIds: ["a", "b", "file"], focusedTabId: "file" },
departingTabId: "file",
openTabIds: new Set(["a", "b", "file"]),
paneFocusHistory: { main: ["file", "a", "b"] },
}),
).toBe("b");
});
it("returns null when the departing tab is not focused", () => {
expect(
resolveTabDepartureSuccessor("relocate", {
pane: { id: "main", tabIds: ["a", "b", "file"], focusedTabId: "a" },
departingTabId: "file",
openTabIds: new Set(["a", "b", "file"]),
}),
).toBeNull();
});
it("syncPaneTabFocusHistory seeds from prior focused tab, renames tabs, prunes closed tabs, and preserves identity when unchanged", () => {
const initial = syncPaneTabFocusHistory({
previousHistory: undefined,
previousPanes: [{ id: "main", tabIds: ["a", "b", "file"], focusedTabId: "a" }],
nextPanes: [{ id: "main", tabIds: ["a", "b", "file"], focusedTabId: "file" }],
});
expect(initial).toEqual({ main: ["file", "a"] });
const unchanged = syncPaneTabFocusHistory({
previousHistory: initial,
previousPanes: [{ id: "main", tabIds: ["a", "b", "file"], focusedTabId: "file" }],
nextPanes: [{ id: "main", tabIds: ["a", "b", "file"], focusedTabId: "file" }],
});
expect(unchanged).toBe(initial);
const renamed = syncPaneTabFocusHistory({
previousHistory: initial,
previousPanes: [{ id: "main", tabIds: ["a", "b", "file"], focusedTabId: "file" }],
nextPanes: [{ id: "main", tabIds: ["agent-a", "b", "file"], focusedTabId: "file" }],
renamedTab: { from: "a", to: "agent-a" },
});
expect(renamed).toEqual({ main: ["file", "agent-a"] });
const pruned = syncPaneTabFocusHistory({
previousHistory: renamed,
previousPanes: [{ id: "main", tabIds: ["agent-a", "b", "file"], focusedTabId: "file" }],
nextPanes: [
{ id: "main", tabIds: ["agent-a", "b"], focusedTabId: "agent-a" },
{ id: "split", tabIds: ["file"], focusedTabId: "file" },
],
});
expect(pruned).toEqual({ main: ["agent-a"], split: ["file"] });
});
});
@@ -0,0 +1,145 @@
/**
* Per-pane tab focus recency, ordered most-recently-focused first.
* Kept in memory rather than persisted so strict layout storage stays unchanged.
*/
export type PaneTabFocusHistory = Record<string, readonly string[]>;
/**
* Why a pane is losing its currently focused tab:
* - "close": browser-style close returns to the tab's parent (if still open anywhere),
* otherwise steps to the adjacent neighbor (right, then left).
* - "relocate": split or move keeps the user's working context visible in the source pane
* by returning to the most recently focused remaining tab in that pane, then a same-pane
* parent tab (for example immediately after reload), then the adjacent neighbor.
*/
export type TabDepartureReason = "close" | "relocate";
export interface PaneFocusSnapshot {
id: string;
tabIds: readonly string[];
focusedTabId: string | null;
}
export interface TabDepartureContext {
pane: PaneFocusSnapshot;
departingTabId: string;
openTabIds: ReadonlySet<string>;
parentTabIdByTabId?: Record<string, string>;
paneFocusHistory?: PaneTabFocusHistory;
}
type TabSuccessorRule = (context: TabDepartureContext) => string | null;
function isRemainingInSourcePane(context: TabDepartureContext, tabId: string | null): boolean {
return Boolean(tabId && tabId !== context.departingTabId && context.pane.tabIds.includes(tabId));
}
const mostRecentlyFocusedInSourcePane: TabSuccessorRule = (context) => {
const recent = context.paneFocusHistory?.[context.pane.id];
return recent?.find((tabId) => isRemainingInSourcePane(context, tabId)) ?? null;
};
const openParentTabAnywhere: TabSuccessorRule = (context) => {
const parentTabId = context.parentTabIdByTabId?.[context.departingTabId] ?? null;
return parentTabId &&
parentTabId !== context.departingTabId &&
context.openTabIds.has(parentTabId)
? parentTabId
: null;
};
const parentTabInSourcePane: TabSuccessorRule = (context) => {
const parentTabId = context.parentTabIdByTabId?.[context.departingTabId] ?? null;
return isRemainingInSourcePane(context, parentTabId) ? parentTabId : null;
};
const adjacentNeighborInSourcePane: TabSuccessorRule = (context) => {
const tabIndex = context.pane.tabIds.indexOf(context.departingTabId);
if (tabIndex < 0) {
return null;
}
return (
context.pane.tabIds[tabIndex + 1] ??
(tabIndex > 0 ? context.pane.tabIds[tabIndex - 1] : null) ??
null
);
};
export const TAB_DEPARTURE_POLICIES: Record<TabDepartureReason, readonly TabSuccessorRule[]> = {
close: [openParentTabAnywhere, adjacentNeighborInSourcePane],
relocate: [mostRecentlyFocusedInSourcePane, parentTabInSourcePane, adjacentNeighborInSourcePane],
};
export function resolveTabDepartureSuccessor(
reason: TabDepartureReason,
context: TabDepartureContext,
): string | null {
if (context.pane.focusedTabId !== context.departingTabId) {
return null;
}
for (const rule of TAB_DEPARTURE_POLICIES[reason]) {
const candidate = rule(context);
if (candidate) {
return candidate;
}
}
return null;
}
function mapRenamedTabId(
tabId: string | null | undefined,
renamedTab: { from: string; to: string } | null | undefined,
): string | null {
if (!tabId) {
return null;
}
return renamedTab && tabId === renamedTab.from ? renamedTab.to : tabId;
}
export function syncPaneTabFocusHistory(input: {
previousHistory: PaneTabFocusHistory | undefined;
previousPanes: readonly PaneFocusSnapshot[];
nextPanes: readonly PaneFocusSnapshot[];
renamedTab?: { from: string; to: string } | null;
}): PaneTabFocusHistory {
const previous = input.previousHistory ?? {};
const previousFocusedByPaneId = new Map(
input.previousPanes.map((pane) => [pane.id, pane.focusedTabId]),
);
const next: Record<string, readonly string[]> = {};
let changed = Object.keys(previous).length !== input.nextPanes.length;
for (const pane of input.nextPanes) {
const openInPane = new Set(pane.tabIds);
const priorEntries = previous[pane.id] ?? [];
const updated: string[] = [];
const seen = new Set<string>();
const pushIfOpen = (tabId: string | null | undefined) => {
if (!tabId || seen.has(tabId) || !openInPane.has(tabId)) {
return;
}
seen.add(tabId);
updated.push(tabId);
};
pushIfOpen(pane.focusedTabId);
// Seed from the pane's prior focused tab so the first switch after hydration remembers it.
pushIfOpen(mapRenamedTabId(previousFocusedByPaneId.get(pane.id), input.renamedTab));
for (const entry of priorEntries) {
pushIfOpen(mapRenamedTabId(entry, input.renamedTab));
}
if (
!changed &&
(priorEntries.length !== updated.length ||
priorEntries.some((entry, index) => entry !== updated[index]))
) {
changed = true;
}
next[pane.id] = updated;
}
return changed ? next : previous;
}
@@ -1,7 +1,29 @@
import { expect, test } from "vitest";
import { execFileSync } from "node:child_process";
import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import pino from "pino";
import { afterEach, expect, test, vi } from "vitest";
import type { AgentManagerEvent, AgentSubscriber } from "./agent-manager.js";
import { registerAgentAutoArchive } from "./create-agent-lifecycle-dispatch.js";
import type { ForgeService } from "../../services/forge-service.js";
import { createWorktree } from "../../utils/worktree.js";
import { WorkspaceAutomationBlockedError } from "../workspace-automation-gate.js";
import type { WorkspaceGitService } from "../workspace-git-service.js";
import type { PersistedWorkspaceRecord } from "../workspace-registry.js";
import type { AgentManager, AgentManagerEvent, AgentSubscriber } from "./agent-manager.js";
import type { AgentStorage } from "./agent-storage.js";
import {
CreateAgentLifecycleDispatch,
registerAgentAutoArchive,
} from "./create-agent-lifecycle-dispatch.js";
const cleanupPaths: string[] = [];
afterEach(() => {
for (const target of cleanupPaths.splice(0)) {
rmSync(target, { recursive: true, force: true });
}
});
class AgentLifecycleEvents {
private readonly listeners = new Set<AgentSubscriber>();
@@ -25,6 +47,109 @@ class AgentLifecycleEvents {
}
}
async function createUntrustedWorktreeFixture(slug: string, markerName: string) {
const tempDir = mkdtempSync(path.join(tmpdir(), "lifecycle-dispatch-"));
cleanupPaths.push(tempDir);
const repoDir = path.join(tempDir, "repo");
const paseoHome = path.join(tempDir, ".paseo");
mkdirSync(repoDir, { recursive: true });
execFileSync("git", ["init", "-b", "main"], { cwd: repoDir, stdio: "pipe" });
execFileSync("git", ["config", "user.email", "test@getpaseo.local"], {
cwd: repoDir,
stdio: "pipe",
});
execFileSync("git", ["config", "user.name", "Paseo Test"], { cwd: repoDir, stdio: "pipe" });
writeFileSync(
path.join(repoDir, "paseo.json"),
JSON.stringify({
worktree: {
teardown: [
`node -e "require('fs').writeFileSync(process.env.PASEO_SOURCE_CHECKOUT_PATH + '/${markerName}', 'ran')"`,
],
},
}),
);
execFileSync("git", ["add", "."], { cwd: repoDir, stdio: "pipe" });
execFileSync("git", ["-c", "commit.gpgsign=false", "commit", "-m", "init"], {
cwd: repoDir,
stdio: "pipe",
});
const worktree = await createWorktree({
cwd: repoDir,
worktreeSlug: slug,
source: { kind: "branch-off", baseBranch: "main", branchName: slug },
paseoHome,
});
const workspace: PersistedWorkspaceRecord = {
workspaceId: `ws-${slug}`,
projectId: "proj-1",
cwd: worktree.worktreePath,
kind: "worktree",
worktreeRoot: worktree.worktreePath,
isPaseoOwnedWorktree: true,
mainRepoRoot: repoDir,
createdAt: "2026-11-24T00:00:00.000Z",
updatedAt: "2026-11-24T00:00:00.000Z",
};
const blockedSource = {
kind: "change_request" as const,
forge: "github",
number: 99,
headRepository: "contributor/paseo",
};
const assertWorkspaceAutomationAllowed = vi.fn(async (id: string) => {
if (id === workspace.workspaceId) {
throw new WorkspaceAutomationBlockedError(blockedSource);
}
});
const activeWorkspaces = [workspace];
const archived = new Set<string>();
const events = new AgentLifecycleEvents();
const agentManager = {
subscribe: (cb: AgentSubscriber) => events.subscribe(cb),
listAgents: () => [],
getAgent: () => null,
archiveAgent: vi.fn(async () => ({ archivedAt: new Date().toISOString() })),
archiveSnapshot: vi.fn(async () => ({})),
} as unknown as AgentManager;
const dispatch = new CreateAgentLifecycleDispatch({
paseoHome,
getWorkspace: async (id) => (id === workspace.workspaceId ? workspace : null),
assertWorkspaceAutomationAllowed,
isCheckoutUntrusted: async () => false,
agentManager,
agentStorage: { listByWorkspace: async () => [] } as unknown as AgentStorage,
github: { invalidate: () => {} } as unknown as ForgeService,
workspaceGitService: {
getSnapshot: vi.fn(async () => null),
invalidateWorktrees: () => {},
} as unknown as WorkspaceGitService,
createPaseoWorktreeWorkflow: vi.fn(),
archiveAgentForClose: vi.fn(async () => undefined),
findWorkspaceIdForCwd: async () => workspace.workspaceId,
listActiveWorkspaces: async () => activeWorkspaces.filter((w) => !archived.has(w.workspaceId)),
archiveWorkspaceRecord: async (id) => {
archived.add(id);
},
emit: vi.fn(),
emitAgentRemove: vi.fn(async () => undefined),
emitWorkspaceUpdatesForWorkspaceIds: vi.fn(async () => undefined),
markWorkspaceArchiving: vi.fn(),
clearWorkspaceArchiving: vi.fn(),
killTerminalsForWorkspace: vi.fn(async () => undefined),
logger: pino({ level: "silent" }),
});
return {
dispatch,
events,
marker: path.join(repoDir, markerName),
createdWorktree: { worktree, workspace },
archived,
assertWorkspaceAutomationAllowed,
};
}
test("auto-archive self-releases once and later cancellation waits harmlessly", async () => {
const agentId = "4a7e2521-286d-4ad5-af35-e091c55302e3";
const agents = new AgentLifecycleEvents();
@@ -45,3 +170,41 @@ test("auto-archive self-releases once and later cancellation waits harmlessly",
expect(archiveCount).toBe(1);
expect(agents.listenerCount()).toBe(0);
});
test("failed create cleanup skips teardown commands for an unapproved cross-repository checkout", async () => {
const { dispatch, marker, createdWorktree, archived, assertWorkspaceAutomationAllowed } =
await createUntrustedWorktreeFixture("failed-create-untrusted", "failed-create-teardown.log");
await dispatch.cleanupCreatedWorktreeAfterFailedAgentCreate({
createdWorktree,
createdAgentId: null,
});
expect(assertWorkspaceAutomationAllowed).toHaveBeenCalledWith(
createdWorktree.workspace.workspaceId,
);
expect(archived.has(createdWorktree.workspace.workspaceId)).toBe(true);
expect(existsSync(createdWorktree.worktree.worktreePath)).toBe(false);
expect(existsSync(marker)).toBe(false);
});
test("first-turn auto-archive skips teardown commands for an unapproved cross-repository checkout", async () => {
const { dispatch, events, marker, createdWorktree, archived, assertWorkspaceAutomationAllowed } =
await createUntrustedWorktreeFixture("auto-archive-untrusted", "auto-archive-teardown.log");
const agentId = "agent-auto-archive-untrusted";
const registration = dispatch.registerAutoArchiveIfRequested({
autoArchive: true,
agentId,
createdWorktree,
});
events.completeTurn(agentId);
await registration.cancel();
expect(assertWorkspaceAutomationAllowed).toHaveBeenCalledWith(
createdWorktree.workspace.workspaceId,
);
expect(archived.has(createdWorktree.workspace.workspaceId)).toBe(true);
expect(existsSync(createdWorktree.worktree.worktreePath)).toBe(false);
expect(existsSync(marker)).toBe(false);
});
@@ -29,7 +29,8 @@ interface CreateAgentLifecycleDispatchDependencies {
worktreeManagers?: Pick<PluginWorktreeManagerRuntime, "removeWorktree">;
workspaceArchiveOperations?: ArchiveDependencies["workspaceArchiveOperations"];
getWorkspace?: ArchiveDependencies["getWorkspace"];
isCheckoutUntrusted?: ArchiveDependencies["isCheckoutUntrusted"];
assertWorkspaceAutomationAllowed: ArchiveDependencies["assertWorkspaceAutomationAllowed"];
isCheckoutUntrusted: ArchiveDependencies["isCheckoutUntrusted"];
agentManager: AgentManager;
agentStorage: AgentStorage;
github: ForgeService;
@@ -201,6 +202,7 @@ export class CreateAgentLifecycleDispatch {
agentStorage: this.dependencies.agentStorage,
findWorkspaceIdForCwd: this.dependencies.findWorkspaceIdForCwd,
getWorkspace: this.dependencies.getWorkspace,
assertWorkspaceAutomationAllowed: this.dependencies.assertWorkspaceAutomationAllowed,
isCheckoutUntrusted: this.dependencies.isCheckoutUntrusted,
listActiveWorkspaces: this.dependencies.listActiveWorkspaces,
archiveWorkspaceRecord: this.dependencies.archiveWorkspaceRecord,
@@ -2527,6 +2527,8 @@ describe("create_agent MCP tool", () => {
emitWorkspaceUpdatesForWorkspaceIds,
markWorkspaceArchiving,
clearWorkspaceArchiving,
assertWorkspaceAutomationAllowed: async () => {},
isCheckoutUntrusted: async () => false,
github: createGitHubServiceStub(),
logger,
});
@@ -2643,6 +2645,8 @@ describe("create_agent MCP tool", () => {
emitWorkspaceUpdatesForWorkspaceIds: vi.fn(async () => undefined),
markWorkspaceArchiving: vi.fn(),
clearWorkspaceArchiving: vi.fn(),
assertWorkspaceAutomationAllowed: async () => {},
isCheckoutUntrusted: async () => false,
github: createGitHubServiceStub(),
logger,
});
@@ -2675,6 +2679,117 @@ describe("create_agent MCP tool", () => {
}
});
it("skips teardown commands when archiving a worktree with blocked repository automation", async () => {
const { agentManager, agentStorage } = createTestDeps();
const tempDir = realpathSync.native(
await mkdtemp(join(tmpdir(), "paseo-mcp-archive-worktree-blocked-")),
);
const repoDir = join(tempDir, "repo");
const paseoHome = join(tempDir, ".paseo");
const markerName = "mcp-blocked-teardown.log";
const markerPath = join(repoDir, markerName);
try {
execFileSync("git", ["init", repoDir], { stdio: "pipe" });
execFileSync("git", ["config", "user.email", "test@example.com"], {
cwd: repoDir,
stdio: "pipe",
});
execFileSync("git", ["config", "user.name", "Test"], { cwd: repoDir, stdio: "pipe" });
execFileSync("git", ["config", "commit.gpgsign", "false"], {
cwd: repoDir,
stdio: "pipe",
});
await writeFile(
join(repoDir, "paseo.json"),
JSON.stringify({
worktree: {
teardown: [
`node -e "require('fs').writeFileSync(process.env.PASEO_SOURCE_CHECKOUT_PATH + '/${markerName}', 'ran')"`,
],
},
}),
);
execFileSync("git", ["add", "paseo.json"], { cwd: repoDir, stdio: "pipe" });
execFileSync("git", ["commit", "-m", "init"], { cwd: repoDir, stdio: "pipe" });
execFileSync("git", ["branch", "-M", "main"], { cwd: repoDir, stdio: "pipe" });
const workspaceGitService = {
getSnapshot: vi.fn(async () => null),
listWorktrees: vi.fn(async () => []),
resolveRepoRoot: vi.fn(async () => repoDir),
invalidateWorktrees: vi.fn(),
};
const archivedWorkspaceIds: string[] = [];
const activeWorkspaces: Array<{
workspaceId: string;
cwd: string;
kind: "worktree" | "local_checkout" | "directory";
}> = [];
const listActiveWorkspaces = vi.fn(async () => activeWorkspaces);
const archiveWorkspaceRecord = createArchiveWorkspaceRecordMutator(
activeWorkspaces,
archivedWorkspaceIds,
);
const { WorkspaceAutomationBlockedError } = await import("../workspace-automation-gate.js");
const server = await createAgentMcpServer({
agentManager,
agentStorage,
providerSnapshotManager: createOpenCodeManager().manager,
paseoHome,
createPaseoWorktree: createPaseoWorktreeForMcpTest({ paseoHome, broadcasts: [] }),
workspaceGitService: workspaceGitService as unknown as Pick<
WorkspaceGitService,
"getSnapshot" | "listWorktrees" | "resolveRepoRoot" | "invalidateWorktrees"
>,
findWorkspaceIdForCwd: vi.fn(async () => "ws-mcp-blocked"),
listActiveWorkspaces,
archiveWorkspaceRecord,
emitWorkspaceUpdatesForWorkspaceIds: vi.fn(async () => undefined),
markWorkspaceArchiving: vi.fn(),
clearWorkspaceArchiving: vi.fn(),
assertWorkspaceAutomationAllowed: async () => {
throw new WorkspaceAutomationBlockedError({
kind: "change_request",
forge: "github",
number: 77,
headRepository: "contributor/repo",
});
},
isCheckoutUntrusted: async () => false,
github: createGitHubServiceStub(),
logger,
});
const createTool = registeredTool(server, "create_workspace");
const archiveTool = registeredTool(server, "archive_workspace");
const created = await createTool.handler({
isolation: "worktree",
path: repoDir,
worktreeSlug: "archive-blocked-worktree",
baseBranch: "main",
});
const worktreePath = z.string().parse(created.structuredContent.cwd);
activeWorkspaces.push({
workspaceId: "ws-mcp-blocked",
cwd: worktreePath,
kind: "worktree",
});
const archived = await archiveTool.handler({
workspaceId: "ws-mcp-blocked",
});
expect(archived.structuredContent).toMatchObject({
workspaceId: "ws-mcp-blocked",
removedDirectory: true,
});
await expect(access(worktreePath)).rejects.toThrow();
await expect(access(markerPath)).rejects.toThrow();
} finally {
await removeTempDir(tempDir);
}
});
it("does not expose worktree path or slug operations", async () => {
const { agentManager, agentStorage } = createTestDeps();
const tempDir = realpathSync.native(
@@ -145,6 +145,7 @@ export interface PaseoToolHostDependencies {
findWorkspaceIdForCwd?: ArchiveDependencies["findWorkspaceIdForCwd"];
worktreeManagers?: ArchiveDependencies["worktreeManagers"];
workspaceArchiveOperations?: ArchiveDependencies["workspaceArchiveOperations"];
assertWorkspaceAutomationAllowed?: ArchiveDependencies["assertWorkspaceAutomationAllowed"];
isCheckoutUntrusted?: ArchiveDependencies["isCheckoutUntrusted"];
listActiveWorkspaces?: ArchiveDependencies["listActiveWorkspaces"];
archiveWorkspaceRecord?: ArchiveDependencies["archiveWorkspaceRecord"];
@@ -3427,11 +3428,18 @@ function archiveWorktreeDependencies(
if (!options.clearWorkspaceArchiving) {
throw new Error("Workspace archiving clearer is required to archive worktrees");
}
if (!options.assertWorkspaceAutomationAllowed) {
throw new Error("Workspace automation gate is required to archive worktrees");
}
if (!options.isCheckoutUntrusted) {
throw new Error("Checkout trust lookup is required to archive worktrees");
}
return {
paseoHome: options.paseoHome,
paseoWorktreesBaseRoot: options.worktreesRoot,
worktreeManagers: options.worktreeManagers,
workspaceArchiveOperations: options.workspaceArchiveOperations,
assertWorkspaceAutomationAllowed: options.assertWorkspaceAutomationAllowed,
isCheckoutUntrusted: options.isCheckoutUntrusted,
github: options.github,
workspaceGitService: options.workspaceGitService,
@@ -111,6 +111,8 @@ function createHarness(overrides?: {
markWorkspaceArchiving: vi.fn(),
clearWorkspaceArchiving: vi.fn(),
emitWorkspaceUpdatesForWorkspaceIds: vi.fn(),
assertWorkspaceAutomationAllowed: vi.fn(async () => undefined),
isCheckoutUntrusted: vi.fn(async () => false),
};
const archiveByScope = vi.fn(
overrides?.archiveByScope ??
@@ -328,6 +330,8 @@ function createRealOutcomeHarness(input: {
},
markWorkspaceArchiving: () => {},
clearWorkspaceArchiving: () => {},
assertWorkspaceAutomationAllowed: async () => {},
isCheckoutUntrusted: async () => false,
emitWorkspaceUpdatesForWorkspaceIds: vi.fn(),
};
@@ -628,4 +632,68 @@ describe("archiveIfSafe", () => {
expect(archivedWorkspaceIds.has(workspace.workspaceId)).toBe(false);
expect(existsSync(worktree.worktreePath)).toBe(true);
});
test("real outcome: skips teardown commands for an unapproved cross-repository checkout", async () => {
const { tempDir, repoDir } = createGitRepo();
const markerName = "auto-archive-merge-teardown.log";
const marker = path.join(repoDir, markerName);
const fs = await import("node:fs");
fs.writeFileSync(
path.join(repoDir, "paseo.json"),
JSON.stringify({
worktree: {
teardown: [
`node -e "require('fs').writeFileSync(process.env.PASEO_SOURCE_CHECKOUT_PATH + '/${markerName}', 'ran')"`,
],
},
}),
);
execFileSync("git", ["add", "."], { cwd: repoDir, stdio: "pipe" });
execFileSync("git", ["-c", "commit.gpgsign=false", "commit", "-m", "teardown"], {
cwd: repoDir,
stdio: "pipe",
});
const paseoHome = path.join(tempDir, ".paseo");
const worktree = await createPaseoOwnedWorktree(repoDir, paseoHome, "merged-untrusted");
const workspaceId = "ws-merged-untrusted";
const archivedWorkspaceIds = new Set<string>();
const harness = createRealOutcomeHarness({
paseoHome,
repoDir,
worktreePath: worktree.worktreePath,
activeWorkspaces: [
{
workspaceId,
cwd: worktree.worktreePath,
kind: "worktree",
worktreeRoot: worktree.worktreePath,
isPaseoOwnedWorktree: true,
mainRepoRoot: repoDir,
},
],
archivedWorkspaceIds,
});
const { WorkspaceAutomationBlockedError } = await import("../workspace-automation-gate.js");
const assertWorkspaceAutomationAllowed = vi.fn(async () => {
throw new WorkspaceAutomationBlockedError({
kind: "change_request",
forge: "github",
number: 123,
headRepository: "contributor/repo",
});
});
harness.options.assertWorkspaceAutomationAllowed = assertWorkspaceAutomationAllowed;
await archiveIfSafe({
workspaceId,
snapshot: { ...createSnapshot(), cwd: worktree.worktreePath },
options: harness.options,
log: harness.log,
});
expect(assertWorkspaceAutomationAllowed).toHaveBeenCalledWith(workspaceId);
expect(archivedWorkspaceIds.has(workspaceId)).toBe(true);
expect(existsSync(worktree.worktreePath)).toBe(false);
expect(existsSync(marker)).toBe(false);
});
});
@@ -25,7 +25,8 @@ export interface AutoArchiveArchiveOptions {
worktreeManagers?: Pick<PluginWorktreeManagerRuntime, "removeWorktree">;
workspaceArchiveOperations?: ArchiveDependencies["workspaceArchiveOperations"];
getWorkspace?: ArchiveDependencies["getWorkspace"];
isCheckoutUntrusted?: ArchiveDependencies["isCheckoutUntrusted"];
assertWorkspaceAutomationAllowed: ArchiveDependencies["assertWorkspaceAutomationAllowed"];
isCheckoutUntrusted: ArchiveDependencies["isCheckoutUntrusted"];
daemonConfigStore: DaemonConfigStore;
workspaceGitService: WorkspaceGitServiceImpl;
github: ForgeService;
@@ -113,6 +114,7 @@ export async function archiveIfSafe(input: {
agentStorage: options.agentStorage,
findWorkspaceIdForCwd: options.findWorkspaceIdForCwd,
getWorkspace: options.getWorkspace,
assertWorkspaceAutomationAllowed: options.assertWorkspaceAutomationAllowed,
isCheckoutUntrusted: options.isCheckoutUntrusted,
listActiveWorkspaces: options.listActiveWorkspaces,
archiveWorkspaceRecord: (workspaceIdToArchive, archivedAt) =>
+6
View File
@@ -1246,6 +1246,8 @@ export async function createPaseoDaemon(
logger,
findWorkspaceIdForCwd: findWorkspaceIdForCwdExternal,
getWorkspace: (workspaceId) => workspaceRegistry.get(workspaceId),
assertWorkspaceAutomationAllowed: (guardedWorkspaceId) =>
assertWorkspaceAutomationAllowedForWorkspace(workspaceRegistry, guardedWorkspaceId),
isCheckoutUntrusted: (checkoutPath) => isCheckoutUntrusted(workspaceRegistry, checkoutPath),
listActiveWorkspaces: listActiveWorkspacesExternal,
getAutoArchivedChangeRequestUrl: async (workspaceId) =>
@@ -1358,6 +1360,8 @@ export async function createPaseoDaemon(
worktreeManagers: pluginRuntime,
workspaceArchiveOperations,
getWorkspace: (workspaceId) => workspaceRegistry.get(workspaceId),
assertWorkspaceAutomationAllowed: (guardedWorkspaceId) =>
assertWorkspaceAutomationAllowedForWorkspace(workspaceRegistry, guardedWorkspaceId),
isCheckoutUntrusted: (checkoutPath) => isCheckoutUntrusted(workspaceRegistry, checkoutPath),
agentManager,
agentStorage,
@@ -1611,6 +1615,8 @@ export async function createPaseoDaemon(
workspaceGitService,
worktreeManagers: pluginRuntime,
workspaceArchiveOperations,
assertWorkspaceAutomationAllowed: (guardedWorkspaceId) =>
assertWorkspaceAutomationAllowedForWorkspace(workspaceRegistry, guardedWorkspaceId),
isCheckoutUntrusted: (checkoutPath) => isCheckoutUntrusted(workspaceRegistry, checkoutPath),
findWorkspaceIdForCwd: findWorkspaceIdForCwdExternal,
listActiveWorkspaces: listActiveWorkspacesExternal,
@@ -171,6 +171,8 @@ function createScheduleService(options: TestScheduleServiceOptions): ScheduleSer
markWorkspaceArchiving: () => {},
clearWorkspaceArchiving: () => {},
killTerminalsForWorkspace: async () => {},
assertWorkspaceAutomationAllowed: async () => {},
isCheckoutUntrusted: async () => false,
sessionLogger: options.logger,
},
{
@@ -276,6 +278,8 @@ async function createRegistryBackedScheduleWorkspaceDeps(rootDir: string): Promi
markWorkspaceArchiving: () => {},
clearWorkspaceArchiving: () => {},
killTerminalsForWorkspace: async () => {},
assertWorkspaceAutomationAllowed: async () => {},
isCheckoutUntrusted: async () => false,
sessionLogger: logger,
},
{
+19 -4
View File
@@ -1301,6 +1301,8 @@ export class Session {
worktreeManagers: this.pluginRuntime,
workspaceArchiveOperations: this.workspaceArchiveOperations,
getWorkspace: (workspaceId) => this.workspaceRegistry.get(workspaceId),
assertWorkspaceAutomationAllowed: (workspaceId) =>
assertWorkspaceAutomationAllowedForWorkspace(this.workspaceRegistry, workspaceId),
isCheckoutUntrusted: (checkoutPath) =>
isCheckoutUntrusted(this.workspaceRegistry, checkoutPath),
agentManager: this.agentManager,
@@ -5850,6 +5852,8 @@ export class Session {
clearWorkspaceArchiving: (workspaceIds) => this.clearWorkspaceArchiving(workspaceIds),
killTerminalsForWorkspace: (workspaceId) =>
this.terminalController.killTerminalsForWorkspace(workspaceId),
assertWorkspaceAutomationAllowed: (workspaceId) =>
assertWorkspaceAutomationAllowedForWorkspace(this.workspaceRegistry, workspaceId),
isCheckoutUntrusted: (checkoutPath) =>
isCheckoutUntrusted(this.workspaceRegistry, checkoutPath),
sessionLogger: this.sessionLogger,
@@ -6557,16 +6561,19 @@ export class Session {
};
}
private async withWorkspaceCheckout<T>(workspaceId: string, run: () => Promise<T>): Promise<T> {
private async withWorkspaceCheckout<T>(
workspaceId: string,
run: (checkoutPath: string | null) => Promise<T>,
): Promise<T> {
const workspace = await this.workspaceRegistry.get(workspaceId);
if (!workspace) {
return run();
return run(null);
}
const checkoutPath = await resolveWorkspaceBackingPath(workspace, {
paseoHome: this.paseoHome,
paseoWorktreesBaseRoot: this.worktreesRoot,
});
return this.workspaceArchiveOperations.withCheckout(checkoutPath, run);
return this.workspaceArchiveOperations.withCheckout(checkoutPath, () => run(checkoutPath));
}
private async withCheckoutForDirectory<T>(cwd: string, run: () => Promise<T>): Promise<T> {
@@ -8209,7 +8216,15 @@ export class Session {
{
getWorkspace: (workspaceId) => this.workspaceRegistry.get(workspaceId),
clearAutomationBlock: (workspaceId) =>
clearWorkspaceAutomationBlock(this.workspaceRegistry, workspaceId),
this.withWorkspaceCheckout(workspaceId, async (checkoutPath) => {
const current = await this.workspaceRegistry.get(workspaceId);
if (!current || current.archivedAt) {
throw new Error(`Workspace not found: ${workspaceId}`);
}
return clearWorkspaceAutomationBlock(this.workspaceRegistry, workspaceId, {
checkoutPath,
});
}),
startWorkspaceSetup: (workspaceId, operation) =>
this.workspaceSetupRuntime.start(workspaceId, operation),
paseoHome: this.paseoHome,
@@ -1,8 +1,9 @@
import { execFileSync } from "node:child_process";
import os from "node:os";
import path from "node:path";
import { mkdirSync, mkdtempSync, rmSync, statSync, symlinkSync } from "node:fs";
import { afterEach, beforeEach, expect, test } from "vitest";
import { afterEach, beforeEach, describe, expect, test } from "vitest";
import { getCheckoutStatus } from "../../../utils/checkout-git.js";
import {
@@ -1168,3 +1169,149 @@ test("a failed workspace unarchive write keeps agents archived and permits retry
expect((await registry.get(workspace.workspaceId))?.archivedAt).toBeNull();
expect(agentArchived).toBe(false);
});
describe("checkout approval state on open and unarchive", () => {
const sampleUntrustedSource = (number: number) => ({
kind: "change_request" as const,
forge: "github",
number,
headRepository: "contributor/repo",
});
function createCheckoutDirs(name: string) {
const sourceCwd = path.join(tmpDir, `repo-${name}`);
const worktreePath = path.join(tmpDir, `worktree-${name}`);
mkdirSync(sourceCwd, { recursive: true });
mkdirSync(worktreePath, { recursive: true });
gitRoots.add(sourceCwd);
gitRoots.add(worktreePath);
return { sourceCwd, worktreePath };
}
function addWorktreeRecord(
dirs: { sourceCwd: string; worktreePath: string },
branch: string,
untrustedSource?: ReturnType<typeof sampleUntrustedSource>,
) {
return provisioning.createWorkspaceForWorktree({
sourceCwd: dirs.sourceCwd,
repoRoot: dirs.sourceCwd,
cwd: dirs.worktreePath,
worktreeRoot: dirs.worktreePath,
branch,
baseBranch: "main",
title: null,
...(untrustedSource ? { untrustedSource } : {}),
});
}
test("unarchiving an approved workspace onto an active unapproved checkout inherits untrustedSource", async () => {
const dirs = createCheckoutDirs("unarchive-inherit");
const original = await addWorktreeRecord(dirs, "feature/approved");
await workspaceRegistry.archive(original.workspaceId, ARCHIVED_AT);
const archivedOriginal = (await workspaceRegistry.get(original.workspaceId))!;
const untrustedSource = sampleUntrustedSource(55);
await addWorktreeRecord(dirs, "contributor/pr-55", untrustedSource);
const restored = await provisioning.ensureWorkspaceRecordUnarchived(archivedOriginal);
expect(restored.archivedAt).toBeNull();
expect(restored.untrustedSource).toEqual(untrustedSource);
expect((await workspaceRegistry.get(original.workspaceId))?.untrustedSource).toEqual(
untrustedSource,
);
});
test("unarchiving an approved workspace ignores archived unapproved records on the same path", async () => {
const dirs = createCheckoutDirs("unarchive-historical");
const oldUntrusted = await addWorktreeRecord(
dirs,
"contributor/pr-56",
sampleUntrustedSource(56),
);
await workspaceRegistry.archive(oldUntrusted.workspaceId, "2026-04-01T00:00:00.000Z");
const approved = await addWorktreeRecord(dirs, "feature/fresh");
await workspaceRegistry.archive(approved.workspaceId, "2026-04-02T00:00:00.000Z");
const restored = await provisioning.ensureWorkspaceRecordUnarchived(
(await workspaceRegistry.get(approved.workspaceId))!,
);
expect(restored.archivedAt).toBeNull();
expect(restored.untrustedSource).toBeUndefined();
});
test("unarchiving an approved workspace onto a retained unapproved checkout inherits untrustedSource from checkout metadata", async () => {
const sourceCwd = path.join(tmpDir, "repo-retained-metadata");
mkdirSync(sourceCwd, { recursive: true });
execFileSync("git", ["init", "-b", "main"], { cwd: sourceCwd, stdio: "pipe" });
execFileSync("git", ["config", "user.email", "test@getpaseo.local"], {
cwd: sourceCwd,
stdio: "pipe",
});
execFileSync("git", ["config", "user.name", "Paseo Test"], { cwd: sourceCwd, stdio: "pipe" });
execFileSync("git", ["-c", "commit.gpgsign=false", "commit", "--allow-empty", "-m", "init"], {
cwd: sourceCwd,
stdio: "pipe",
});
const worktreePath = path.join(tmpDir, "worktree-retained-metadata");
execFileSync("git", ["worktree", "add", "-b", "retained-pr", worktreePath, "main"], {
cwd: sourceCwd,
stdio: "pipe",
});
const untrustedSource = sampleUntrustedSource(57);
await writePaseoWorktreeMetadata(worktreePath, {
baseRefName: "main",
untrustedSource,
});
gitRoots.add(sourceCwd);
gitRoots.add(worktreePath);
const approved = await addWorktreeRecord({ sourceCwd, worktreePath }, "feature/approved");
await workspaceRegistry.archive(approved.workspaceId, ARCHIVED_AT);
const restored = await provisioning.ensureWorkspaceRecordUnarchived(
(await workspaceRegistry.get(approved.workspaceId))!,
);
expect(restored.archivedAt).toBeNull();
expect(restored.untrustedSource).toEqual(untrustedSource);
});
test("creating a directory workspace ignores archived unapproved records on the same path", async () => {
const dirs = createCheckoutDirs("dir-reused-path");
const oldUntrusted = await addWorktreeRecord(
dirs,
"contributor/pr-58",
sampleUntrustedSource(58),
);
await workspaceRegistry.archive(oldUntrusted.workspaceId, ARCHIVED_AT);
const opened = await provisioning.createWorkspaceForDirectory(dirs.worktreePath);
expect(opened.untrustedSource).toBeUndefined();
});
test("unarchiving an old unapproved workspace onto a live approved checkout drops its stale untrustedSource", async () => {
const dirs = createCheckoutDirs("unarchive-stale-block");
const oldUntrusted = await addWorktreeRecord(
dirs,
"contributor/pr-59",
sampleUntrustedSource(59),
);
await workspaceRegistry.archive(oldUntrusted.workspaceId, ARCHIVED_AT);
const archivedOldUntrusted = (await workspaceRegistry.get(oldUntrusted.workspaceId))!;
await addWorktreeRecord(dirs, "feature/fresh-approved");
const unarchived = await provisioning.ensureWorkspaceRecordUnarchived(archivedOldUntrusted);
expect(unarchived.archivedAt).toBeNull();
expect(unarchived.untrustedSource).toBeUndefined();
expect(
(await workspaceRegistry.get(oldUntrusted.workspaceId))?.untrustedSource,
).toBeUndefined();
});
});
@@ -275,12 +275,10 @@ export function createWorkspaceProvisioningService(deps: {
? await readPaseoWorktreeMetadata(checkout.worktreeRoot ?? normalizedCwd)
: null;
const checkoutRoot = checkout.worktreeRoot ?? normalizedCwd;
const matchesCheckout = createRealpathAwarePathMatcher(checkoutRoot);
const inheritedUntrustedSource = (await workspaceRegistry.listAll()).find(
(candidate) =>
Boolean(candidate.untrustedSource) &&
matchesCheckout(candidate.worktreeRoot ?? candidate.cwd),
)?.untrustedSource;
const { untrustedSource: inheritedUntrustedSource } = await resolveCheckoutUntrustedSource(
checkoutRoot,
baseMetadata?.untrustedSource,
);
const timestamp = new Date().toISOString();
const workspace = createPersistedWorkspaceRecord({
workspaceId: context?.workspaceId ?? generateWorkspaceId(),
@@ -429,6 +427,49 @@ export function createWorkspaceProvisioningService(deps: {
).workspaceId;
}
async function resolveCheckoutUntrustedSource(
checkoutRoot: string,
knownMetadataUntrustedSource?: UntrustedWorkspaceSource,
): Promise<{ hasEvidence: boolean; untrustedSource: UntrustedWorkspaceSource | undefined }> {
const metadataUntrustedSource =
knownMetadataUntrustedSource ??
(await readPaseoWorktreeMetadata(checkoutRoot).catch(() => null))?.untrustedSource;
if (metadataUntrustedSource) {
return { hasEvidence: true, untrustedSource: metadataUntrustedSource };
}
const matchesCheckout = createRealpathAwarePathMatcher(checkoutRoot);
const active = (await workspaceRegistry.listActive()).filter((candidate) =>
matchesCheckout(candidate.worktreeRoot ?? candidate.cwd),
);
if (active.length === 0) {
return { hasEvidence: false, untrustedSource: undefined };
}
return {
hasEvidence: true,
untrustedSource: active.find((candidate) => Boolean(candidate.untrustedSource))
?.untrustedSource,
};
}
async function syncUnarchivedCheckoutUntrustedSource(
workspace: PersistedWorkspaceRecord,
): Promise<PersistedWorkspaceRecord> {
const resolved = await resolveCheckoutUntrustedSource(workspace.worktreeRoot ?? workspace.cwd);
if (!resolved.hasEvidence) {
return workspace;
}
if (resolved.untrustedSource) {
return workspace.untrustedSource
? workspace
: { ...workspace, untrustedSource: resolved.untrustedSource };
}
if (!workspace.untrustedSource) {
return workspace;
}
const { untrustedSource: _stale, ...approved } = workspace;
return approved;
}
async function resolveRestoredAutoArchiveChangeRequestUrl(
workspace: PersistedWorkspaceRecord,
): Promise<string | null> {
@@ -466,7 +507,7 @@ export function createWorkspaceProvisioningService(deps: {
updatedAt: timestamp,
});
next = {
...(placementUpdate?.workspace ?? workspace),
...(await syncUnarchivedCheckoutUntrustedSource(placementUpdate?.workspace ?? workspace)),
archivedAt: null,
autoArchivedChangeRequestUrl,
updatedAt: timestamp,
@@ -23,12 +23,14 @@ import {
} from "../../../utils/worktree-metadata.js";
import { createWorktree, deletePaseoWorktree } from "../../../utils/worktree.js";
import {
FileBackedProjectRegistry,
FileBackedWorkspaceRegistry,
createPersistedProjectRecord,
createPersistedWorkspaceRecord,
type PersistedProjectRecord,
type PersistedWorkspaceRecord,
} from "../../workspace-registry.js";
import { createWorkspaceProvisioningService } from "../workspace-provisioning/workspace-provisioning-service.js";
import { createWorkspaceRecoveryService } from "./workspace-recovery-service.js";
const NOW = "2026-07-11T10:12:30.752Z";
@@ -719,3 +721,134 @@ test("restores a user-created worktree at its recorded path outside Paseo's root
).toBe("external-feature");
expect(unarchived).toEqual([workspace.workspaceId]);
});
describe("recovery approval ownership for shared archived history", () => {
async function setupSlugReuseHistory(options: { keepLatestCheckoutOnDisk: boolean }) {
const { tempDir, repoDir } = createGitRepository();
const paseoHome = join(tempDir, "paseo-home");
const workspaceRegistry = new FileBackedWorkspaceRegistry(
join(paseoHome, "workspaces.json"),
pino({ level: "silent" }),
);
const projectRegistry = new FileBackedProjectRegistry(
join(paseoHome, "projects.json"),
pino({ level: "silent" }),
);
const provisioning = createWorkspaceProvisioningService({
unarchiveWorkspaceAgents: async () => {},
workspaceRegistry,
projectRegistry,
workspaceGitService: {
getCheckout: async (cwd) => getCheckoutStatus(cwd),
getSnapshot: async () => ({
checkout: null,
forge: { pullRequest: null, checkedAt: null, error: null },
}),
},
isDirectory: async (target) => existsSync(target) && statSync(target).isDirectory(),
logger: pino({ level: "silent" }),
});
const firstWorktree = await createWorktree({
cwd: repoDir,
worktreeSlug: "shared-slug",
source: { kind: "branch-off", branchName: "feature/older-approved", baseBranch: "main" },
paseoHome,
});
const olderApproved = await provisioning.createWorkspaceForWorktree({
sourceCwd: repoDir,
repoRoot: repoDir,
cwd: firstWorktree.worktreePath,
worktreeRoot: firstWorktree.worktreePath,
branch: firstWorktree.branchName,
baseBranch: firstWorktree.baseRef,
title: null,
isPaseoOwnedWorktree: true,
});
await workspaceRegistry.archive(olderApproved.workspaceId, "2026-04-01T00:00:00.000Z");
await deletePaseoWorktree({
cwd: repoDir,
worktreePath: firstWorktree.worktreePath,
paseoHome,
});
const untrustedSource = {
kind: "change_request" as const,
forge: "github",
number: 72,
headRepository: "contributor/repo",
};
const secondWorktree = await createWorktree({
cwd: repoDir,
worktreeSlug: "shared-slug",
source: { kind: "branch-off", branchName: "contributor/pr-72", baseBranch: "main" },
paseoHome,
});
await writePaseoWorktreeMetadata(secondWorktree.worktreePath, {
baseRefName: "main",
untrustedSource,
});
const laterUntrusted = await provisioning.createWorkspaceForWorktree({
sourceCwd: repoDir,
repoRoot: repoDir,
cwd: secondWorktree.worktreePath,
worktreeRoot: secondWorktree.worktreePath,
branch: secondWorktree.branchName,
baseBranch: secondWorktree.baseRef,
title: null,
isPaseoOwnedWorktree: true,
untrustedSource,
});
await workspaceRegistry.archive(laterUntrusted.workspaceId, "2026-04-02T00:00:00.000Z");
if (!options.keepLatestCheckoutOnDisk) {
await deletePaseoWorktree({
cwd: repoDir,
worktreePath: secondWorktree.worktreePath,
paseoHome,
});
}
const recovery = createWorkspaceRecoveryService({
paseoHome,
getWorkspace: (id) => workspaceRegistry.get(id),
getProject: (id) => projectRegistry.get(id),
isDirectory: async (target) => existsSync(target) && statSync(target).isDirectory(),
unarchiveWorkspace: async (workspace) => {
await provisioning.ensureWorkspaceRecordUnarchived(workspace);
},
});
return {
olderApproved,
untrustedSource,
worktreePath: firstWorktree.worktreePath,
workspaceRegistry,
recovery,
};
}
test("restoring a deleted approved workspace after slug reuse keeps the recreated worktree approved", async () => {
const { olderApproved, worktreePath, workspaceRegistry, recovery } =
await setupSlugReuseHistory({ keepLatestCheckoutOnDisk: false });
const result = await recovery.restore(olderApproved.workspaceId);
expect(result).toEqual({ workspaceId: olderApproved.workspaceId, action: "restore" });
const restored = await workspaceRegistry.get(olderApproved.workspaceId);
expect(restored?.archivedAt).toBeNull();
expect(restored?.untrustedSource).toBeUndefined();
expect((await readPaseoWorktreeMetadata(worktreePath))?.untrustedSource).toBeUndefined();
});
test("unarchiving onto a retained unapproved checkout inherits untrustedSource from worktree metadata", async () => {
const { olderApproved, untrustedSource, workspaceRegistry, recovery } =
await setupSlugReuseHistory({ keepLatestCheckoutOnDisk: true });
const result = await recovery.restore(olderApproved.workspaceId);
expect(result).toEqual({ workspaceId: olderApproved.workspaceId, action: "unarchive" });
const restored = await workspaceRegistry.get(olderApproved.workspaceId);
expect(restored?.archivedAt).toBeNull();
expect(restored?.untrustedSource).toEqual(untrustedSource);
});
});
@@ -5,6 +5,7 @@ import { resolveRepositoryDefaultBranch } from "../../../utils/checkout-git.js";
import { runWithRepositoryRoot } from "../../../utils/git-repository-discovery.js";
import { createRealpathAwarePathMatcher } from "../../../utils/path.js";
import { runGitCommand } from "../../../utils/run-git-command.js";
import { setPaseoWorktreeUntrustedSource } from "../../../utils/worktree-metadata.js";
import {
createWorktree,
isPaseoOwnedWorktreeCwd,
@@ -280,6 +281,9 @@ export function createWorkspaceRecoveryService(deps: {
error,
);
}
if (workspace.untrustedSource) {
await setPaseoWorktreeUntrustedSource(recreatedWorktreePath, workspace.untrustedSource);
}
return { worktreePath: recreatedWorktreePath, pluginId: restoredByPluginId };
}
@@ -7,12 +7,17 @@ import { afterEach, describe, expect, test, vi } from "vitest";
import type { ForgeService } from "../services/forge-service.js";
import { createRealpathAwarePathMatcher } from "../utils/path.js";
import { getPaseoWorktreeMetadataPath } from "../utils/worktree-metadata.js";
import {
getPaseoWorktreeMetadataPath,
readPaseoWorktreeMetadata,
setPaseoWorktreeUntrustedSource,
} from "../utils/worktree-metadata.js";
import { archiveCommand } from "./worktree/commands.js";
import { createWorktree, listPaseoWorktrees, type WorktreeConfig } from "../utils/worktree.js";
import type { ManagedAgent } from "./agent/agent-manager.js";
import type { AgentStorage, StoredAgentRecord } from "./agent/agent-storage.js";
import type { WorkspaceGitService } from "./workspace-git-service.js";
import { WorkspaceArchiveOperations } from "./workspace-archive-operations.js";
import {
archiveByScope,
unarchiveWorkspaceAgents,
@@ -22,7 +27,16 @@ import {
resolveWorkspaceIdAtPath,
WorkspaceArchiveCanceledError,
} from "./workspace-archive-service.js";
import { WorkspaceAutomationBlockedError } from "./workspace-automation-gate.js";
import {
assertWorkspaceAutomationAllowedForWorkspace,
clearWorkspaceAutomationBlock,
isCheckoutUntrusted,
WorkspaceAutomationBlockedError,
} from "./workspace-automation-gate.js";
import {
createPersistedWorkspaceRecord,
FileBackedWorkspaceRegistry,
} from "./workspace-registry.js";
const cleanupPaths: string[] = [];
@@ -175,6 +189,8 @@ function createArchiveDeps(input: ArchiveDepsInput): ArchiveTestDependencies {
markWorkspaceArchiving: vi.fn(),
clearWorkspaceArchiving: vi.fn(),
killTerminalsForWorkspace: vi.fn(async () => {}),
assertWorkspaceAutomationAllowed: async () => {},
isCheckoutUntrusted: async () => false,
sessionLogger: createLogger(),
activeWorkspaces: active,
archivedAgentIds,
@@ -480,6 +496,394 @@ describe("archiveByScope", () => {
expect(existsSync(marker)).toBe(false);
});
describe("teardown approval gating", () => {
const sampleBlockedSource = (number = 42) => ({
kind: "change_request" as const,
forge: "github",
number,
headRepository: "contributor/paseo",
});
async function createTeardownWorktree(slug: string, options?: { nestedRelative?: string }) {
const { tempDir, repoDir } = createGitRepo();
const markerName = `${slug}-teardown.log`;
const marker = path.join(repoDir, markerName);
const configDir = options?.nestedRelative
? path.join(repoDir, options.nestedRelative)
: repoDir;
mkdirSync(configDir, { recursive: true });
writeFileSync(
path.join(configDir, "paseo.json"),
JSON.stringify({
worktree: {
teardown: [
`node -e "require('fs').writeFileSync(process.env.PASEO_SOURCE_CHECKOUT_PATH + '/${markerName}', 'ran')"`,
],
},
}),
);
execFileSync("git", ["add", "."], { cwd: repoDir, stdio: "pipe" });
execFileSync("git", ["-c", "commit.gpgsign=false", "commit", "-m", `teardown ${slug}`], {
cwd: repoDir,
stdio: "pipe",
});
const paseoHome = path.join(tempDir, ".paseo");
const worktree = await createPaseoOwnedWorktree(repoDir, paseoHome, slug);
return { repoDir, paseoHome, worktreePath: worktree.worktreePath, marker };
}
function makeWorktreeWorkspace(
workspaceId: string,
fixture: { repoDir: string; worktreePath: string },
overrides: Partial<ActiveWorkspaceRef> = {},
): ActiveWorkspaceRef {
return {
workspaceId,
cwd: fixture.worktreePath,
kind: "worktree",
worktreeRoot: fixture.worktreePath,
isPaseoOwnedWorktree: true,
mainRepoRoot: fixture.repoDir,
...overrides,
};
}
test("workspace scope skips teardown when the workspace record carries untrustedSource", async () => {
const fixture = await createTeardownWorktree("untrusted-record");
const workspaceId = "ws-untrusted-record";
const deps = createArchiveDeps({
paseoHome: fixture.paseoHome,
activeWorkspaces: [
makeWorktreeWorkspace(workspaceId, fixture, { untrustedSource: sampleBlockedSource() }),
],
});
const result = await archiveByScope(deps, {
scope: { kind: "workspace", workspaceId },
requestId: "req-untrusted-record",
});
expect(result.archivedWorkspaceIds).toEqual([workspaceId]);
expect(result.removedDirectory).toBe(true);
expect(existsSync(fixture.worktreePath)).toBe(false);
expect(existsSync(fixture.marker)).toBe(false);
});
test("workspace scope runs teardown for a fresh worktree reusing the path of an archived unapproved checkout", async () => {
const fixture = await createTeardownWorktree("reused-slug");
const workspaceId = "ws-fresh-reused-slug";
const deps = createArchiveDeps({
paseoHome: fixture.paseoHome,
activeWorkspaces: [makeWorktreeWorkspace(workspaceId, fixture)],
});
// Simulates an earlier archived unapproved workspace that previously used the same path.
deps.isCheckoutUntrusted = async () => true;
const result = await archiveByScope(deps, {
scope: { kind: "workspace", workspaceId },
requestId: "req-fresh-reused-slug",
});
expect(result.archivedWorkspaceIds).toEqual([workspaceId]);
expect(result.removedDirectory).toBe(true);
expect(existsSync(fixture.worktreePath)).toBe(false);
expect(readFileSync(fixture.marker, "utf8")).toBe("ran");
});
test("retrying archive on an already-archived unapproved workspace does not mark a fresh worktree at the same path", async () => {
const fixture = await createTeardownWorktree("reused-after-retry");
const oldArchivedId = "ws-old-archived-unapproved";
const freshWorkspaceId = "ws-fresh-approved";
const deps = createArchiveDeps({
paseoHome: fixture.paseoHome,
activeWorkspaces: [makeWorktreeWorkspace(freshWorkspaceId, fixture)],
});
deps.getWorkspace = async (workspaceId) =>
workspaceId === oldArchivedId
? {
...makeWorktreeWorkspace(oldArchivedId, fixture, {
untrustedSource: sampleBlockedSource(),
}),
projectId: "proj-1",
archivedAt: "2026-11-24T00:00:00.000Z",
createdAt: "2026-11-24T00:00:00.000Z",
updatedAt: "2026-11-24T00:00:00.000Z",
}
: null;
deps.isCheckoutUntrusted = async () => true;
const retry = await archiveByScope(deps, {
scope: { kind: "workspace", workspaceId: oldArchivedId },
requestId: "req-retry-archived",
});
expect(retry.archivedWorkspaceIds).toEqual([]);
expect(retry.removedDirectory).toBe(false);
expect(
(await readPaseoWorktreeMetadata(fixture.worktreePath))?.untrustedSource,
).toBeUndefined();
const fresh = await archiveByScope(deps, {
scope: { kind: "workspace", workspaceId: freshWorkspaceId },
requestId: "req-archive-fresh",
});
expect(fresh.archivedWorkspaceIds).toEqual([freshWorkspaceId]);
expect(fresh.removedDirectory).toBe(true);
expect(existsSync(fixture.worktreePath)).toBe(false);
expect(readFileSync(fixture.marker, "utf8")).toBe("ran");
});
test("workspace scope skips teardown when retained checkout metadata carries untrustedSource", async () => {
const fixture = await createTeardownWorktree("retained-metadata");
await setPaseoWorktreeUntrustedSource(fixture.worktreePath, sampleBlockedSource(88));
const workspaceId = "ws-reopened-on-retained";
const deps = createArchiveDeps({
paseoHome: fixture.paseoHome,
activeWorkspaces: [makeWorktreeWorkspace(workspaceId, fixture)],
});
const result = await archiveByScope(deps, {
scope: { kind: "workspace", workspaceId },
requestId: "req-retained-metadata",
});
expect(result.archivedWorkspaceIds).toEqual([workspaceId]);
expect(result.removedDirectory).toBe(true);
expect(existsSync(fixture.worktreePath)).toBe(false);
expect(existsSync(fixture.marker)).toBe(false);
});
test("workspace scope backfills checkout metadata when archiving a pre-upgrade unapproved worktree whose directory stays on disk", async () => {
const fixture = await createTeardownWorktree("pre-upgrade-retained");
expect(
(await readPaseoWorktreeMetadata(fixture.worktreePath))?.untrustedSource,
).toBeUndefined();
const untrustedSource = sampleBlockedSource(91);
const blockedWorkspaceId = "ws-pre-upgrade-blocked";
const keptSiblingId = "ws-pre-upgrade-sibling";
const deps = createArchiveDeps({
paseoHome: fixture.paseoHome,
activeWorkspaces: [
makeWorktreeWorkspace(blockedWorkspaceId, fixture, { untrustedSource }),
makeWorktreeWorkspace(keptSiblingId, fixture),
],
});
const first = await archiveByScope(deps, {
scope: { kind: "workspace", workspaceId: blockedWorkspaceId },
requestId: "req-pre-upgrade-first",
});
expect(first.removedDirectory).toBe(false);
expect(existsSync(fixture.marker)).toBe(false);
expect((await readPaseoWorktreeMetadata(fixture.worktreePath))?.untrustedSource).toEqual(
untrustedSource,
);
const second = await archiveByScope(deps, {
scope: { kind: "workspace", workspaceId: keptSiblingId },
requestId: "req-pre-upgrade-second",
});
expect(second.removedDirectory).toBe(true);
expect(existsSync(fixture.worktreePath)).toBe(false);
expect(existsSync(fixture.marker)).toBe(false);
});
test.each(["approval-first", "archive-first"] as const)(
"serializing archive and setup approval through withCheckout preserves completed approval (%s)",
async (order) => {
const fixture = await createTeardownWorktree(`serialized-${order}`);
const untrustedSource = sampleBlockedSource(92);
const registry = new FileBackedWorkspaceRegistry(
path.join(fixture.paseoHome, "workspaces.json"),
createLogger(),
);
const operations = new WorkspaceArchiveOperations();
const now = "2026-11-24T00:00:00.000Z";
const ws1 = createPersistedWorkspaceRecord({
workspaceId: "ws-archive-target",
projectId: "proj-1",
displayName: "ws-archive-target",
cwd: fixture.worktreePath,
kind: "worktree",
worktreeRoot: fixture.worktreePath,
isPaseoOwnedWorktree: true,
mainRepoRoot: fixture.repoDir,
untrustedSource,
createdAt: now,
updatedAt: now,
});
const ws2 = createPersistedWorkspaceRecord({
workspaceId: "ws-approve-sibling",
projectId: "proj-1",
displayName: "ws-approve-sibling",
cwd: fixture.worktreePath,
kind: "worktree",
worktreeRoot: fixture.worktreePath,
isPaseoOwnedWorktree: true,
mainRepoRoot: fixture.repoDir,
untrustedSource,
createdAt: now,
updatedAt: now,
});
await registry.upsert(ws1);
await registry.upsert(ws2);
const deps = createArchiveDeps({
paseoHome: fixture.paseoHome,
activeWorkspaces: [],
});
deps.workspaceArchiveOperations = operations;
deps.getWorkspace = (id) => registry.get(id);
deps.listActiveWorkspaces = () => registry.listActive();
deps.archiveWorkspaceRecord = async (id, archivedAt) => {
await registry.archive(id, archivedAt);
};
deps.assertWorkspaceAutomationAllowed = (id) =>
assertWorkspaceAutomationAllowedForWorkspace(registry, id);
deps.isCheckoutUntrusted = (checkoutPath) => isCheckoutUntrusted(registry, checkoutPath);
async function clearInsideCheckoutLock() {
return clearWorkspaceAutomationBlock(registry, ws2.workspaceId, {
checkoutPath: fixture.worktreePath,
});
}
if (order === "approval-first") {
const [cleared, archived] = await Promise.all([
operations.withCheckout(fixture.worktreePath, clearInsideCheckoutLock),
archiveByScope(deps, {
scope: { kind: "workspace", workspaceId: ws1.workspaceId },
requestId: `req-${order}-ws1`,
}),
]);
expect(cleared).toBe(true);
expect(archived.removedDirectory).toBe(false);
} else {
// Pause archive mid-flight (after resolving targets, before backfill) while Run setup
// queues on the same checkout lock, ensuring approval runs after backfill and wins.
let enteredStop!: () => void;
let releaseStop!: () => void;
const stopEntered = new Promise<void>((resolve) => {
enteredStop = resolve;
});
const stopGate = new Promise<void>((resolve) => {
releaseStop = resolve;
});
deps.stopWorkspaceSetup = async () => {
enteredStop();
await stopGate;
};
const archivePromise = archiveByScope(deps, {
scope: { kind: "workspace", workspaceId: ws1.workspaceId },
requestId: `req-${order}-ws1`,
});
await stopEntered;
const approvalPromise = operations.withCheckout(
fixture.worktreePath,
clearInsideCheckoutLock,
);
releaseStop();
const [archived, cleared] = await Promise.all([archivePromise, approvalPromise]);
expect(archived.removedDirectory).toBe(false);
expect(cleared).toBe(true);
deps.stopWorkspaceSetup = undefined;
}
expect(
(await readPaseoWorktreeMetadata(fixture.worktreePath))?.untrustedSource,
).toBeUndefined();
expect((await registry.get(ws2.workspaceId))?.untrustedSource).toBeUndefined();
const finalArchive = await archiveByScope(deps, {
scope: { kind: "workspace", workspaceId: ws2.workspaceId },
requestId: `req-${order}-ws2`,
});
expect(finalArchive.removedDirectory).toBe(true);
expect(readFileSync(fixture.marker, "utf8")).toBe("ran");
},
);
test("workspace scope skips teardown when an active sibling on the same checkout is blocked", async () => {
const nestedRelative = path.join("packages", "app");
const fixture = await createTeardownWorktree("shared-blocked-sibling", { nestedRelative });
const blockedRootId = "ws-shared-blocked-root";
const nestedWorkspaceId = "ws-shared-nested";
const deps = createArchiveDeps({
paseoHome: fixture.paseoHome,
activeWorkspaces: [
makeWorktreeWorkspace(blockedRootId, fixture),
makeWorktreeWorkspace(nestedWorkspaceId, fixture, {
cwd: path.join(fixture.worktreePath, nestedRelative),
}),
],
});
deps.assertWorkspaceAutomationAllowed = async (workspaceId) => {
if (workspaceId === blockedRootId) {
throw new WorkspaceAutomationBlockedError(sampleBlockedSource());
}
};
const result = await archiveByScope(deps, {
scope: { kind: "workspace", workspaceId: nestedWorkspaceId },
requestId: "req-shared-blocked-sibling",
});
expect(result.archivedWorkspaceIds).toEqual([nestedWorkspaceId]);
expect(result.removedDirectory).toBe(false);
expect(existsSync(fixture.worktreePath)).toBe(true);
expect(existsSync(fixture.marker)).toBe(false);
});
test("worktree scope skips teardown when archiving an unrecorded worktree directory", async () => {
const fixture = await createTeardownWorktree("unrecorded-worktree");
const deps = createArchiveDeps({
paseoHome: fixture.paseoHome,
activeWorkspaces: [],
});
const result = await archiveByScope(deps, {
scope: { kind: "worktree", targetPath: fixture.worktreePath },
requestId: "req-unrecorded-worktree",
});
expect(result.removedDirectory).toBe(true);
expect(existsSync(fixture.worktreePath)).toBe(false);
expect(existsSync(fixture.marker)).toBe(false);
});
test("worktree scope skips teardown for nested siblings when any workspace on the checkout is blocked", async () => {
const nestedRelative = path.join("packages", "app");
const fixture = await createTeardownWorktree("blocked-sibling", { nestedRelative });
const rootWorkspaceId = "ws-blocked-root";
const nestedWorkspaceId = "ws-nested-sibling";
const deps = createArchiveDeps({
paseoHome: fixture.paseoHome,
activeWorkspaces: [
makeWorktreeWorkspace(rootWorkspaceId, fixture),
makeWorktreeWorkspace(nestedWorkspaceId, fixture, {
cwd: path.join(fixture.worktreePath, nestedRelative),
}),
],
});
deps.assertWorkspaceAutomationAllowed = async (workspaceId) => {
if (workspaceId === rootWorkspaceId) {
throw new WorkspaceAutomationBlockedError(sampleBlockedSource());
}
};
const result = await archiveByScope(deps, {
scope: { kind: "worktree", targetPath: fixture.worktreePath },
requestId: "req-blocked-sibling",
});
expect(result.archivedWorkspaceIds).toEqual(
expect.arrayContaining([rootWorkspaceId, nestedWorkspaceId]),
);
expect(result.removedDirectory).toBe(true);
expect(existsSync(fixture.worktreePath)).toBe(false);
expect(existsSync(fixture.marker)).toBe(false);
});
});
test("workspace scope keeps a worktree for an active workspace in a subdirectory", async () => {
const { tempDir, repoDir } = createGitRepo();
const paseoHome = path.join(tempDir, ".paseo");
@@ -21,7 +21,14 @@ import type {
} from "./workspace-registry.js";
import { createRealpathAwarePathMatcher, isRealpathInsideRoot } from "../utils/path.js";
import { runWithGitCommandPriority } from "../utils/run-git-command.js";
import { WorkspaceAutomationBlockedError } from "./workspace-automation-gate.js";
import {
readPaseoWorktreeMetadata,
setPaseoWorktreeUntrustedSource,
} from "../utils/worktree-metadata.js";
import {
WorkspaceAutomationBlockedError,
type UntrustedWorkspaceSource,
} from "./workspace-automation-gate.js";
import type { PluginWorktreeManagerRuntime } from "./plugins/runtime.js";
import type { WorkspaceArchiveOperations } from "./workspace-archive-operations.js";
@@ -59,8 +66,8 @@ export interface ArchiveDependencies {
clearWorkspaceArchiving: (workspaceIds: Iterable<string>) => void;
killTerminalsForWorkspace: (workspaceId: string) => Promise<void>;
stopWorkspaceSetup?: (workspaceId: string) => Promise<void>;
assertWorkspaceAutomationAllowed?: (workspaceId: string) => Promise<void>;
isCheckoutUntrusted?: (checkoutPath: string) => Promise<boolean>;
assertWorkspaceAutomationAllowed: (workspaceId: string) => Promise<void>;
isCheckoutUntrusted: (checkoutPath: string) => Promise<boolean>;
sessionLogger?: Logger;
}
@@ -128,12 +135,17 @@ interface BackingDirectory {
mainRepoRoot: string | null;
paseoWorktreesRoot: string | null;
worktreeManagerPluginId: string | null;
untrusted: boolean;
untrustedSource: UntrustedWorkspaceSource | null;
}
interface ArchiveTarget {
backing: BackingDirectory | null;
teardownTargets: Array<{ workspaceId: string | null; cwd: string }>;
teardownTargets: Array<{ workspaceId: string; cwd: string }>;
// Active workspaces sharing the resolved backing checkout when archive starts
// (including the records being archived and any active siblings). Keeps
// teardown approval scoped to the live checkout rather than historical
// archived records that previously occupied the same path.
checkoutWorkspaceIds: string[];
setupWorkspaceIds: string[];
workspaceIds: string[];
}
@@ -275,6 +287,33 @@ async function resolveArchiveCheckoutPath(
return (await resolveBackingDirectory(scope.targetPath, dependencies)).path;
}
async function listActiveWorkspacesOnBacking(
activeWorkspaces: ActiveWorkspaceRef[],
backingPath: string,
dependencies: Pick<ArchiveDependencies, "paseoHome" | "paseoWorktreesBaseRoot">,
): Promise<ActiveWorkspaceRef[]> {
const matchesBackingDirectory = createRealpathAwarePathMatcher(backingPath);
return (
await Promise.all(
activeWorkspaces.map(async (workspace) => {
const backingDirectory = await resolveWorkspaceBackingDirectory(workspace, dependencies);
return matchesBackingDirectory(backingDirectory.path) ? workspace : null;
}),
)
).filter((workspace): workspace is ActiveWorkspaceRef => workspace !== null);
}
function firstUntrustedSource(
primary: UntrustedWorkspaceSource | null,
workspaces: ActiveWorkspaceRef[],
): UntrustedWorkspaceSource | null {
return (
primary ??
workspaces.find((workspace) => Boolean(workspace.untrustedSource))?.untrustedSource ??
null
);
}
async function resolveArchiveTarget(
dependencies: ArchiveDependencies,
scope: ArchiveScope,
@@ -291,12 +330,37 @@ async function resolveArchiveTarget(
{ workspaceId },
"Workspace not found for archive-by-scope; skipping",
);
return { backing: null, teardownTargets: [], setupWorkspaceIds: [], workspaceIds: [] };
return {
backing: null,
teardownTargets: [],
checkoutWorkspaceIds: [],
setupWorkspaceIds: [],
workspaceIds: [],
};
}
const isArchived = "archivedAt" in record && Boolean(record.archivedAt);
const backing = await resolveWorkspaceBackingDirectory(record, dependencies);
const activeOnCheckout = await listActiveWorkspacesOnBacking(
activeWorkspaces,
backing.path,
dependencies,
);
const checkoutWorkspaceIds = Array.from(
new Set([
...(isArchived ? [] : [workspaceId]),
...activeOnCheckout.map((workspace) => workspace.workspaceId),
]),
);
return {
backing: await resolveWorkspaceBackingDirectory(record, dependencies),
backing: {
...backing,
untrustedSource: firstUntrustedSource(
isArchived ? null : backing.untrustedSource,
activeOnCheckout,
),
},
teardownTargets: isArchived ? [] : [{ workspaceId, cwd: record.cwd }],
checkoutWorkspaceIds,
setupWorkspaceIds: [workspaceId],
workspaceIds: isArchived ? [] : [workspaceId],
};
@@ -304,14 +368,11 @@ async function resolveArchiveTarget(
const backing = await resolveBackingDirectory(scope.targetPath, dependencies);
const matchesBackingDirectory = createRealpathAwarePathMatcher(backing.path);
const targetWorkspaces = (
await Promise.all(
activeWorkspaces.map(async (workspace) => {
const backingDirectory = await resolveWorkspaceBackingDirectory(workspace, dependencies);
return matchesBackingDirectory(backingDirectory.path) ? workspace : null;
}),
)
).filter((workspace): workspace is ActiveWorkspaceRef => workspace !== null);
const targetWorkspaces = await listActiveWorkspacesOnBacking(
activeWorkspaces,
backing.path,
dependencies,
);
const recordedId = await dependencies.findWorkspaceIdForCwd(backing.path);
const recorded = recordedId ? await dependencies.getWorkspace?.(recordedId) : null;
const record =
@@ -320,15 +381,19 @@ async function resolveArchiveTarget(
? recorded
: null) ??
targetWorkspaces[0];
const resolvedBacking = record
? await resolveWorkspaceBackingDirectory(record, dependencies)
: backing;
return {
backing: record ? await resolveWorkspaceBackingDirectory(record, dependencies) : backing,
teardownTargets:
targetWorkspaces.length > 0
? targetWorkspaces.map((workspace) => ({
workspaceId: workspace.workspaceId,
cwd: workspace.cwd,
}))
: [{ workspaceId: null, cwd: scope.targetPath }],
backing: {
...resolvedBacking,
untrustedSource: firstUntrustedSource(null, targetWorkspaces),
},
teardownTargets: targetWorkspaces.map((workspace) => ({
workspaceId: workspace.workspaceId,
cwd: workspace.cwd,
})),
checkoutWorkspaceIds: targetWorkspaces.map((workspace) => workspace.workspaceId),
setupWorkspaceIds: targetWorkspaces.map((workspace) => workspace.workspaceId),
workspaceIds: targetWorkspaces.map((workspace) => workspace.workspaceId),
};
@@ -360,7 +425,7 @@ async function resolveWorkspaceBackingDirectory(
dependencies: Pick<ArchiveDependencies, "paseoHome" | "paseoWorktreesBaseRoot">,
): Promise<BackingDirectory> {
const worktreeManagerPluginId = workspace.worktreeManagerPluginId ?? null;
const untrusted = Boolean(workspace.untrustedSource);
const untrustedSource = workspace.untrustedSource ?? null;
if (workspace.isPaseoOwnedWorktree === false) {
return {
path: resolve(workspace.worktreeRoot ?? workspace.cwd),
@@ -370,7 +435,7 @@ async function resolveWorkspaceBackingDirectory(
mainRepoRoot: workspace.mainRepoRoot ?? null,
paseoWorktreesRoot: null,
worktreeManagerPluginId,
untrusted,
untrustedSource,
};
}
if (workspace.isPaseoOwnedWorktree && workspace.worktreeRoot && workspace.mainRepoRoot) {
@@ -382,7 +447,7 @@ async function resolveWorkspaceBackingDirectory(
mainRepoRoot: workspace.mainRepoRoot,
paseoWorktreesRoot: null,
worktreeManagerPluginId,
untrusted,
untrustedSource,
};
}
if (workspace.kind !== "worktree") {
@@ -394,7 +459,7 @@ async function resolveWorkspaceBackingDirectory(
mainRepoRoot: workspace.mainRepoRoot ?? null,
paseoWorktreesRoot: null,
worktreeManagerPluginId,
untrusted,
untrustedSource,
};
}
@@ -408,7 +473,7 @@ async function resolveWorkspaceBackingDirectory(
...backing,
mainRepoRoot: workspace.mainRepoRoot ?? backing.mainRepoRoot,
worktreeManagerPluginId: worktreeManagerPluginId ?? backing.worktreeManagerPluginId,
untrusted: untrusted || backing.untrusted,
untrustedSource: untrustedSource ?? backing.untrustedSource,
};
}
@@ -429,7 +494,7 @@ async function resolveBackingDirectory(
mainRepoRoot: ownership.repoRoot ?? null,
paseoWorktreesRoot: ownership.worktreeRoot ?? null,
worktreeManagerPluginId: null,
untrusted: false,
untrustedSource: null,
};
}
@@ -509,22 +574,20 @@ async function maybeRemoveDirectory(
}
const archivedWorkspaceIdSet = new Set(archivedWorkspaceIds);
const teardownTargets = target.teardownTargets.filter(
(teardownTarget) =>
teardownTarget.workspaceId === null || archivedWorkspaceIdSet.has(teardownTarget.workspaceId),
const teardownTargets = target.teardownTargets.filter((teardownTarget) =>
archivedWorkspaceIdSet.has(teardownTarget.workspaceId),
);
const teardownPlan = await resolveCheckoutTeardownPlan(
dependencies,
backing,
teardownTargets,
target.checkoutWorkspaceIds,
);
let untrustedBacking =
backing.untrusted || Boolean(await dependencies.isCheckoutUntrusted?.(backing.path));
teardownPlan.untrustedBacking || Boolean(await dependencies.isCheckoutUntrusted(backing.path));
try {
const allowedTeardownTargets = await filterAllowedTeardownTargets(
dependencies,
teardownTargets,
);
if (allowedTeardownTargets.length < teardownTargets.length) {
untrustedBacking = true;
}
for (const teardownTarget of uniqueTeardownTargets(allowedTeardownTargets)) {
for (const teardownTarget of uniqueTeardownTargets(teardownPlan.allowedTargets)) {
request.checkpoint();
await runWorktreeTeardownCommands({
worktreePath: backing.path,
@@ -584,25 +647,66 @@ async function maybeRemoveDirectory(
}
}
async function resolveCheckoutTeardownPlan(
dependencies: ArchiveDependencies,
backing: BackingDirectory,
teardownTargets: Array<{ workspaceId: string; cwd: string }>,
checkoutWorkspaceIds: string[],
): Promise<{
allowedTargets: Array<{ workspaceId: string; cwd: string }>;
untrustedBacking: boolean;
}> {
const metadataUntrustedSource =
(await readPaseoWorktreeMetadata(backing.path).catch(() => null))?.untrustedSource ?? null;
const checkoutUntrusted = Boolean(backing.untrustedSource || metadataUntrustedSource);
const teardownGate = checkoutUntrusted
? { allowed: [] as Array<{ workspaceId: string; cwd: string }>, blockedSource: null }
: await filterAllowedTeardownTargets(dependencies, teardownTargets, checkoutWorkspaceIds);
const untrustedSourceToPersist =
teardownTargets.length === 0 || metadataUntrustedSource
? null
: (backing.untrustedSource ?? teardownGate.blockedSource);
if (untrustedSourceToPersist) {
// Runs inside workspaceArchiveOperations.withCheckout alongside Run setup approval,
// so retained pre-upgrade checkouts keep their block without racing approval clears.
await setPaseoWorktreeUntrustedSource(backing.path, untrustedSourceToPersist).catch(
() => false,
);
}
return {
allowedTargets: teardownGate.allowed,
untrustedBacking: checkoutUntrusted || teardownGate.allowed.length < teardownTargets.length,
};
}
async function filterAllowedTeardownTargets(
dependencies: ArchiveDependencies,
targets: Array<{ workspaceId: string | null; cwd: string }>,
): Promise<Array<{ workspaceId: string | null; cwd: string }>> {
const allowed: Array<{ workspaceId: string | null; cwd: string }> = [];
const blockedCwds: string[] = [];
for (const target of targets) {
targets: Array<{ workspaceId: string; cwd: string }>,
checkoutWorkspaceIds: string[],
): Promise<{
allowed: Array<{ workspaceId: string; cwd: string }>;
blockedSource: UntrustedWorkspaceSource | null;
}> {
if (targets.length === 0) {
return { allowed: [], blockedSource: null };
}
if (typeof dependencies.assertWorkspaceAutomationAllowed !== "function") {
return { allowed: [], blockedSource: null };
}
const workspaceIdsToCheck = Array.from(
new Set([...targets.map((target) => target.workspaceId), ...checkoutWorkspaceIds]),
);
for (const workspaceId of workspaceIdsToCheck) {
try {
if (target.workspaceId)
await dependencies.assertWorkspaceAutomationAllowed?.(target.workspaceId);
allowed.push(target);
await dependencies.assertWorkspaceAutomationAllowed(workspaceId);
} catch (error) {
if (!(error instanceof WorkspaceAutomationBlockedError)) throw error;
blockedCwds.push(target.cwd);
// Every workspace in checkoutWorkspaceIds shares the same backing checkout;
// if any active workspace on it is blocked, skip teardown for the checkout.
return { allowed: [], blockedSource: error.source };
}
}
return allowed.filter(
(target) => !blockedCwds.some((cwd) => createRealpathAwarePathMatcher(cwd)(target.cwd)),
);
return { allowed: targets, blockedSource: null };
}
function uniqueTeardownTargets<T extends { cwd: string }>(targets: T[]): T[] {
@@ -1,9 +1,28 @@
import { describe, expect, it } from "vitest";
import { execFileSync } from "node:child_process";
import { chmodSync, mkdirSync, mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import {
getPaseoWorktreeMetadataPath,
readPaseoWorktreeMetadata,
writePaseoWorktreeMetadata,
} from "../utils/worktree-metadata.js";
import {
WorkspaceAutomationBlockedError,
assertWorkspaceAutomationAllowed,
clearWorkspaceAutomationBlock,
formatWorkspaceAutomationBlockedMessage,
} from "./workspace-automation-gate.js";
import type { PersistedWorkspaceRecord } from "./workspace-registry.js";
const cleanupPaths: string[] = [];
afterEach(() => {
for (const target of cleanupPaths.splice(0)) {
rmSync(target, { recursive: true, force: true });
}
});
describe("workspace automation gate", () => {
it("refuses executable repository automation for a cross-repository change request", () => {
@@ -43,4 +62,96 @@ describe("workspace automation gate", () => {
}),
).toBe(`Scripts are blocked for ${noun} #42 from contributor/paseo. Run setup to allow them.`);
});
async function createUntrustedWorktreeFixture(number: number) {
const tempDir = mkdtempSync(path.join(tmpdir(), `automation-gate-${number}-`));
cleanupPaths.push(tempDir);
const repoDir = path.join(tempDir, "repo");
const worktreeDir = path.join(tempDir, "wt");
mkdirSync(repoDir, { recursive: true });
execFileSync("git", ["init", "-b", "main"], { cwd: repoDir, stdio: "pipe" });
execFileSync("git", ["config", "user.email", "test@getpaseo.local"], {
cwd: repoDir,
stdio: "pipe",
});
execFileSync("git", ["config", "user.name", "Paseo Test"], { cwd: repoDir, stdio: "pipe" });
execFileSync("git", ["-c", "commit.gpgsign=false", "commit", "--allow-empty", "-m", "init"], {
cwd: repoDir,
stdio: "pipe",
});
execFileSync("git", ["worktree", "add", "-b", `pr-${number}`, worktreeDir, "main"], {
cwd: repoDir,
stdio: "pipe",
});
const source = {
kind: "change_request" as const,
forge: "github",
number,
headRepository: "contributor/paseo",
};
await writePaseoWorktreeMetadata(worktreeDir, { baseRefName: "main", untrustedSource: source });
const records = new Map<string, PersistedWorkspaceRecord>([
[
"ws-1",
{
workspaceId: "ws-1",
projectId: "proj-1",
cwd: worktreeDir,
kind: "worktree",
worktreeRoot: worktreeDir,
isPaseoOwnedWorktree: true,
mainRepoRoot: repoDir,
untrustedSource: source,
createdAt: "2026-11-24T00:00:00.000Z",
updatedAt: "2026-11-24T00:00:00.000Z",
},
],
]);
const registry = {
listAll: async () => Array.from(records.values()),
update: async (
id: string,
updater: (record: PersistedWorkspaceRecord) => PersistedWorkspaceRecord,
) => {
const current = records.get(id);
if (!current) return null;
const next = updater(current);
records.set(id, next);
return next;
},
};
return { worktreeDir, source, records, registry };
}
it("clears untrustedSource from both workspace records and worktree metadata", async () => {
const { worktreeDir, records, registry } = await createUntrustedWorktreeFixture(42);
const cleared = await clearWorkspaceAutomationBlock(registry, "ws-1");
expect(cleared).toBe(true);
expect(records.get("ws-1")?.untrustedSource).toBeUndefined();
expect((await readPaseoWorktreeMetadata(worktreeDir))?.untrustedSource).toBeUndefined();
});
it.skipIf(process.platform === "win32" || process.getuid?.() === 0)(
"fails without clearing workspace records when worktree metadata cannot be written",
async () => {
const { worktreeDir, source, records, registry } = await createUntrustedWorktreeFixture(43);
const metadataDir = path.dirname(await getPaseoWorktreeMetadataPath(worktreeDir));
chmodSync(metadataDir, 0o555);
try {
await expect(clearWorkspaceAutomationBlock(registry, "ws-1")).rejects.toThrow();
expect(records.get("ws-1")?.untrustedSource).toEqual(source);
expect((await readPaseoWorktreeMetadata(worktreeDir))?.untrustedSource).toEqual(source);
} finally {
chmodSync(metadataDir, 0o755);
}
const retried = await clearWorkspaceAutomationBlock(registry, "ws-1");
expect(retried).toBe(true);
expect(records.get("ws-1")?.untrustedSource).toBeUndefined();
expect((await readPaseoWorktreeMetadata(worktreeDir))?.untrustedSource).toBeUndefined();
},
);
});
@@ -1,4 +1,5 @@
import { createRealpathAwarePathMatcher } from "../utils/path.js";
import { setPaseoWorktreeUntrustedSource } from "../utils/worktree-metadata.js";
import type { WorkspaceRegistry } from "./workspace-registry.js";
export interface UntrustedWorkspaceSource {
@@ -51,23 +52,26 @@ export async function isCheckoutUntrusted(
export async function clearWorkspaceAutomationBlock(
registry: Pick<WorkspaceRegistry, "update" | "listAll">,
workspaceId: string,
options?: { checkoutPath?: string | null },
): Promise<boolean> {
let cleared = false;
const allWorkspaces = await registry.listAll();
const target = allWorkspaces.find((record) => record.workspaceId === workspaceId);
if (!target) throw new Error(`Workspace not found: ${workspaceId}`);
const checkoutPath = options?.checkoutPath ?? target.worktreeRoot ?? target.cwd;
// Clear checkout metadata before mutating workspace records so a failed metadata
// write surfaces an error and leaves workspace records intact to retry approval.
let cleared = await setPaseoWorktreeUntrustedSource(checkoutPath, null);
const timestamp = new Date().toISOString();
const workspace = await registry.update(workspaceId, (record) => {
if (!record.untrustedSource) return record;
cleared = true;
const { untrustedSource: _removed, ...trusted } = record;
return { ...trusted, updatedAt: timestamp };
});
if (!workspace) throw new Error(`Workspace not found: ${workspaceId}`);
const checkoutPath = workspace.worktreeRoot ?? workspace.cwd;
const matchesCheckout = createRealpathAwarePathMatcher(checkoutPath);
const siblings = await registry.listAll();
for (const sibling of siblings) {
if (sibling.workspaceId === workspaceId || !sibling.untrustedSource) continue;
if (!matchesCheckout(sibling.worktreeRoot ?? sibling.cwd)) continue;
await registry.update(sibling.workspaceId, (record) => {
for (const candidate of allWorkspaces) {
if (!candidate.untrustedSource) continue;
if (
candidate.workspaceId !== workspaceId &&
!matchesCheckout(candidate.worktreeRoot ?? candidate.cwd)
) {
continue;
}
await registry.update(candidate.workspaceId, (record) => {
if (!record.untrustedSource) return record;
cleared = true;
const { untrustedSource: _removed, ...trusted } = record;
+10 -13
View File
@@ -29,6 +29,7 @@ import type { ChangeRequestCheckoutSource, FirstAgentContext } from "@getpaseo/p
import type { WorkspaceGitService } from "./workspace-git-service.js";
import { runWithRepositoryRoot } from "../utils/git-repository-discovery.js";
import { runGitCommand, runWithGitCommandPriority } from "../utils/run-git-command.js";
import { setPaseoWorktreeUntrustedSource } from "../utils/worktree-metadata.js";
import type { UntrustedWorkspaceSource } from "./workspace-automation-gate.js";
@@ -185,18 +186,9 @@ async function createWorktreeAtRepositoryRoot(
input,
deps,
});
if (managedWorktree) {
return {
worktree: managedWorktree,
intent,
untrustedSource,
repoRoot,
created: true,
};
}
return {
worktree: await createWorktree({
const createdWorktree =
managedWorktree ??
(await createWorktree({
cwd: repoRoot,
worktreeSlug: normalizedSlug,
worktreePath: transformed.path,
@@ -204,7 +196,12 @@ async function createWorktreeAtRepositoryRoot(
preparedBranchOff,
paseoHome: input.paseoHome,
worktreesRoot: input.worktreesRoot,
}),
}));
if (untrustedSource) {
await setPaseoWorktreeUntrustedSource(createdWorktree.worktreePath, untrustedSource);
}
return {
worktree: createdWorktree,
intent,
untrustedSource,
repoRoot,
@@ -1756,6 +1756,8 @@ describe("handlePaseoWorktreeArchiveRequest worktree scope", () => {
markWorkspaceArchiving: vi.fn(),
clearWorkspaceArchiving: vi.fn(),
killTerminalsForWorkspace: vi.fn(async () => {}),
assertWorkspaceAutomationAllowed: async () => {},
isCheckoutUntrusted: async () => false,
sessionLogger: createLogger(),
},
{
@@ -1832,6 +1834,8 @@ describe("handlePaseoWorktreeArchiveRequest worktree scope", () => {
markWorkspaceArchiving: vi.fn(),
clearWorkspaceArchiving: vi.fn(),
killTerminalsForWorkspace: vi.fn(async () => {}),
assertWorkspaceAutomationAllowed: async () => {},
isCheckoutUntrusted: async () => false,
sessionLogger: createLogger(),
},
{
@@ -1909,6 +1913,8 @@ describe("handlePaseoWorktreeArchiveRequest worktree scope", () => {
markWorkspaceArchiving: vi.fn(),
clearWorkspaceArchiving: vi.fn(),
killTerminalsForWorkspace: vi.fn(async () => {}),
assertWorkspaceAutomationAllowed: async () => {},
isCheckoutUntrusted: async () => false,
sessionLogger: createLogger(),
},
{
@@ -1982,6 +1988,8 @@ describe("handlePaseoWorktreeArchiveRequest worktree scope", () => {
markWorkspaceArchiving: vi.fn(),
clearWorkspaceArchiving: vi.fn(),
killTerminalsForWorkspace: vi.fn(async () => {}),
assertWorkspaceAutomationAllowed: async () => {},
isCheckoutUntrusted: async () => false,
sessionLogger: createLogger(),
};
@@ -2594,14 +2594,20 @@ it.each([false, true])(
...nodeTerminalCommand(`
process.stdin.setRawMode(true);
let row = 0;
function print(count) {
for(let i=0;i<count;i++,row++) process.stdout.write("\\x1b[31mrow-" + String(row).padStart(5,"0") + " 界é🙂 " + "log ".repeat(20) + "\\x1b[0m\\r\\n");
function nextRow() {
return "\\x1b[31mrow-" + String(row++).padStart(5,"0") + " 界é🙂 " + "log ".repeat(20) + "\\x1b[0m\\r\\n";
}
// Fill the initial history in batches to avoid a TTY write for every row.
for (let start = 0; start < 12050; start += 256) {
const count = Math.min(256, 12050 - start);
process.stdout.write(Array.from({ length: count }, nextRow).join(""));
}
print(12050);
process.stdout.write("READY\\r\\n");
process.stdin.on("data", data => {
if(data.toString().includes("BURST")) { print(4000); process.stdout.write("BURST-DONE\\r\\n"); }
else process.stdout.write("ECHO:" + data.toString() + "\\r\\n");
if(data.toString().includes("BURST")) {
for (let i = 0; i < 4000; i++) process.stdout.write(nextRow());
process.stdout.write("BURST-DONE\\r\\n");
} else process.stdout.write("ECHO:" + data.toString() + "\\r\\n");
});
setInterval(()=>{},1000);
`),
@@ -14,6 +14,13 @@ const ChangeRequestLookupTargetSchema = z.object({
localBranchName: z.string().min(1).optional(),
});
const UntrustedWorktreeSourceSchema = z.object({
kind: z.literal("change_request"),
forge: z.string().min(1),
number: z.number().int().positive(),
headRepository: z.string().min(1),
});
// baseRefName is the display name; baseRef is the checkout's current exact base
// ("refs/remotes/upstream/main"). baseRef is optional because worktrees written before it
// existed only have the name — there are no migrations, so readers fall back.
@@ -23,6 +30,7 @@ const PaseoWorktreeMetadataV1Schema = z.object({
baseRef: z.string().min(1).optional(),
changeRequestLookupTarget: ChangeRequestLookupTargetSchema.optional(),
worktreeManagerPluginId: z.string().min(1).optional(),
untrustedSource: UntrustedWorktreeSourceSchema.optional(),
});
const PaseoWorktreeMetadataV2Schema = z.object({
@@ -31,6 +39,7 @@ const PaseoWorktreeMetadataV2Schema = z.object({
baseRef: z.string().min(1).optional(),
changeRequestLookupTarget: ChangeRequestLookupTargetSchema.optional(),
worktreeManagerPluginId: z.string().min(1).optional(),
untrustedSource: UntrustedWorktreeSourceSchema.optional(),
firstAgentBranchAutoName: z
.discriminatedUnion("status", [
z.object({
@@ -58,6 +67,7 @@ const PaseoWorktreeMetadataSchema = z.union([
export type PaseoWorktreeMetadata = z.infer<typeof PaseoWorktreeMetadataSchema>;
export type PaseoWorktreeChangeRequestHint = z.infer<typeof ChangeRequestLookupTargetSchema>;
export type PaseoWorktreeUntrustedSource = z.infer<typeof UntrustedWorktreeSourceSchema>;
export function createPaseoWorktreeChangeRequestHint(
input: PaseoWorktreeChangeRequestHint,
@@ -230,6 +240,7 @@ export async function writePaseoWorktreeMetadata(
baseRef?: string;
changeRequestLookupTarget?: PaseoWorktreeChangeRequestHint;
worktreeManagerPluginId?: string;
untrustedSource?: PaseoWorktreeUntrustedSource;
},
): Promise<void> {
return mutateMetadata(worktreeRoot, async (root) => {
@@ -250,11 +261,41 @@ export async function writePaseoWorktreeMetadata(
...(options.worktreeManagerPluginId
? { worktreeManagerPluginId: options.worktreeManagerPluginId }
: {}),
...(options.untrustedSource ? { untrustedSource: options.untrustedSource } : {}),
};
await writePaseoWorktreeMetadataFile(root, metadata);
});
}
export async function setPaseoWorktreeUntrustedSource(
worktreeRoot: string,
untrustedSource: PaseoWorktreeUntrustedSource | null,
): Promise<boolean> {
return mutateMetadata(worktreeRoot, async (root) => {
let current: PaseoWorktreeMetadata | null;
try {
current = await readMetadataFile(root);
} catch (error) {
const cause = (error as { cause?: NodeJS.ErrnoException }).cause;
if ((error as NodeJS.ErrnoException).code === "ENOENT" || cause?.code === "ENOENT") {
return false;
}
throw error;
}
if (!current) {
return false;
}
const hadUntrustedSource = Boolean(current.untrustedSource);
if (!untrustedSource && !hadUntrustedSource) {
return false;
}
const { untrustedSource: _previous, ...rest } = current;
const next: PaseoWorktreeMetadata = untrustedSource ? { ...rest, untrustedSource } : rest;
await writePaseoWorktreeMetadataFile(root, next);
return untrustedSource ? true : hadUntrustedSource;
});
}
export async function setPaseoWorktreeBaseRef(input: {
worktreeRoot: string;
baseRef: string;