Compare commits

..
Author SHA1 Message Date
paseo-bot[bot]andClaude Opus 5.5 94f2df6263 Keep the Import Session list in place when Load more fetches the next page (#9974)
Tapping Load more emptied the list until the larger page arrived: the sheet
showed "Loading sessions...", unmounted the virtualized list, and brought it
back scrolled to the top. The sessions queries set keepPreviousData, but
useQueries gives a changed key a new observer with no previous data, so the
placeholder was always empty. The placeholder is now the cached page that
Load more grew from, for the same scope, search, and provider.

The compact import-session journey flaked on this in CI: its scroll helper
resolved a row, the list was replaced before the helper ran, and the walk
up from the detached row found no scroller. The helper now scrolls the list
itself, and the journey checks that Load more keeps the reader down the
list.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 12:00:55 +00:00
26 changed files with 146 additions and 851 deletions
-16
View File
@@ -281,22 +281,6 @@ hides the row by the latest local intent, so a late remove or upsert from a supe
does not flip it back. Tabs and layout are purged only once the undo window closes with the
archive committed.
Archiving a workspace in a Paseo-owned worktree saves the worktree's HEAD for that workspace at
that moment, whether or not the directory is deleted:
`refs/paseo/archived/<hash of the workspace ID>/<name>`, whose value is HEAD's commit and whose
`<name>` is `git rev-parse --abbrev-ref HEAD` (`feature`, or `HEAD` when detached). The ref keeps
git's cleanup from deleting commits only that HEAD held. Recovery checks out the saved name when it
still resolves to the saved commit and the saved commit otherwise, so git decides whether the
worktree comes back on its branch or detached; restore never creates, moves, or deletes a branch.
Paseo does not sort HEAD into kinds: the only place it reads the name is that check in
`archived-head.ts`. The ref belongs to the workspace record: only its own archive writes it, so
a later worktree on the same directory, archived later, saves its own ref and leaves this one alone.
Unarchiving the record (Undo, Restore, or reopening the directory) deletes it,
and the unarchive fails if git cannot. Nothing else deletes it: a workspace that stays archived,
including one whose project was removed, keeps its ref for the life of the repository. With no
saved HEAD (archived before saved HEADs existed, or the directory was already gone), recovery
checks out the record's `branch`, or a new `restored/…` branch from the base.
History navigation opens the selected agent without changing either archive state. Workspace
**Unarchive**, **Restore**, Undo, and reopening the directory recover the agents closed by that
workspace archive, including
@@ -1,6 +1,3 @@
import { execFileSync } from "node:child_process";
import { writeFileSync } from "node:fs";
import path from "node:path";
import type { Page } from "@playwright/test";
import { expect, test } from "../support/fixtures";
import { gotoAppShell } from "../support/helpers/app";
@@ -241,38 +238,6 @@ test.describe("Workspace archive undo", () => {
await expectHostWorkspaceSettledActive(client, worktree.workspaceId);
});
test("Undo brings back a worktree archived on a detached HEAD with its commit", async ({
page,
}) => {
const worktree = await seedWorktree(page, "archive-undo-detached");
const git = (args: string[]) =>
execFileSync("git", args, { cwd: worktree.workspaceDirectory, encoding: "utf8" }).trim();
git(["checkout", "--detach"]);
writeFileSync(path.join(worktree.workspaceDirectory, "detached.txt"), "detached work\n");
git(["add", "detached.txt"]);
git([
"-c",
"user.name=Paseo Test",
"-c",
"user.email=test@getpaseo.local",
"-c",
"commit.gpgsign=false",
"commit",
"-m",
"detached work",
]);
const detachedCommit = git(["rev-parse", "HEAD"]);
await archiveFromRowButton(page, worktree.workspaceId);
await undoButton(page).hover();
await expectDirectoryPresence(worktree.workspaceDirectory, false);
await undoButton(page).click();
await expect(workspaceRow(page, worktree.workspaceId)).toBeVisible({ timeout: 30_000 });
await expectHostWorkspaceSettledActive(client, worktree.workspaceId);
expect(git(["rev-parse", "HEAD"])).toBe(detachedCommit);
});
test("hovering Undo keeps the toast open past its deadline, and its close ends the undo", async ({
page,
}) => {
@@ -389,7 +389,10 @@ test.describe("Worktree restore", () => {
await page.getByTestId(`agent-row-${getServerId()}-${agent.id}`).click();
await expect(page.getByText("Workspace archived", { exact: true })).toBeVisible();
await expect(
page.getByText("Restore Sample workspace to return to its agents.", { exact: true }),
page.getByText(
"Restore Sample workspace to return to its agents. A new branch will start from the saved base or the repository default.",
{ exact: true },
),
).toBeVisible();
await captureBranchlessRestoreStep(page, "01-restore-workspace.png");
@@ -416,7 +419,7 @@ test.describe("Worktree restore", () => {
cwd: backingWorktree.workspaceDirectory,
encoding: "utf8",
}).trim(),
).toBe("");
).toMatch(/^restored\//);
});
test("restore failure stays visible and permits a successful retry", async ({ page }) => {
@@ -97,18 +97,15 @@ export class ImportSessionFlow {
await target.scrollIntoViewIfNeeded();
await expect(target).toBeInViewport();
}
/**
* Scrolls the virtualized list, the only one that leaves rows unmounted. A row handle is no way
* in: the list unmounts rows as it scrolls, and a detached row has no scroller above it.
*/
private async scrollList(forward: boolean) {
await this.page
.locator('[data-testid^="import-session-session-"]')
.first()
.evaluate((row, advance) => {
let element = row.parentElement;
while (element && !["auto", "scroll"].includes(getComputedStyle(element).overflowY))
element = element.parentElement;
if (!element) throw new Error("Import list has no scroll owner");
element.scrollTop = advance ? element.scrollTop + element.clientHeight * 0.8 : 0;
element.dispatchEvent(new Event("scroll"));
}, forward);
await this.page.getByTestId("import-session-list").evaluate((list, advance) => {
list.scrollTop = advance ? list.scrollTop + list.clientHeight * 0.8 : 0;
list.dispatchEvent(new Event("scroll"));
}, forward);
}
async search(query: string) {
await this.page.getByTestId("import-session-search").fill(query);
@@ -120,11 +117,18 @@ export class ImportSessionFlow {
await this.page.getByTestId("import-session-search").fill("");
await expect(this.page.getByTestId("import-session-load-more")).toBeVisible();
}
/** Load more keeps the reader down the list instead of sending them back to the top. */
async loadMore() {
await this.page.getByTestId("import-session-load-more").click();
const loadMore = this.page.getByTestId("import-session-load-more");
const topRow = this.page.getByTestId((await this.rowIds())[0]!);
await expect(topRow).toBeInViewport();
await loadMore.click();
// The next page is the last and short, so the button leaves once it lands.
await expect(loadMore).toHaveCount(0);
await expect(this.page.getByText("Loading sessions...", { exact: true })).toHaveCount(0);
await expect(topRow).not.toBeInViewport();
await this.revealSession("fixture-root-20");
await expect(this.page.getByText("Root session 20", { exact: true })).toBeInViewport();
await expect(this.page.getByTestId("import-session-load-more")).toHaveCount(0);
}
async retryProvider(provider: string, label: string) {
await this.expectProviderError(label);
@@ -17,6 +17,11 @@ export function nextPageLimit(limit: number): number {
return PAGE_LIMITS.find((candidate) => candidate > limit) ?? limit;
}
/** The page Load more grew this limit from, or null for the first page. */
export function previousPageLimit(limit: number): number | null {
return PAGE_LIMITS.findLast((candidate) => candidate < limit) ?? null;
}
export function requiresImportSessionsHostUpgrade(input: {
supportsSnapshot: boolean;
workspaceId?: string | null;
@@ -1172,6 +1172,44 @@ describe("ImportSessionSheet", () => {
});
});
it("keeps the loaded list in place while Load more fetches the next page", async () => {
let releaseNextPage: () => void = () => undefined;
const nextPage = new Promise<void>((resolve) => {
releaseNextPage = resolve;
});
const fetchRecentProviderSessions = vi.fn(async (options: { limit?: number } | undefined) => {
if (options?.limit !== 15) await nextPage;
return {
requestId: "recent-provider-sessions",
entries: createPageOfEntries(options?.limit === 15 ? 15 : 20),
};
});
renderSheet(createRecentSessionsClient(fetchRecentProviderSessions, vi.fn()), {
cwd: null,
snapshot: { supportsSnapshot: true, entries: [createSnapshotEntry("claude")] },
});
fireEvent.click(await screen.findByTestId("import-session-load-more"));
// The list the user scrolled to Load more is the one they keep: replacing it would drop
// them back at the top, behind a loading state, until the larger page lands.
const list = screen.getByTestId("import-session-list");
await waitFor(() => {
expect(fetchRecentProviderSessions).toHaveBeenCalledWith({
providers: ["claude"],
limit: 45,
});
});
expect(screen.getByTestId("import-session-list")).toBe(list);
expect(screen.queryByText("Loading sessions...")).toBeNull();
releaseNextPage();
await waitFor(() => {
expect(screen.queryByTestId("import-session-load-more")).toBeNull();
});
expect(screen.getByTestId("import-session-list")).toBe(list);
});
it("stops the refresh spinner and retries only the failed provider", async () => {
const fetchRecentProviderSessions = vi.fn(
async (options: { providers?: string[] } | undefined) => {
@@ -1,6 +1,6 @@
import React, { type ReactNode, useCallback, useEffect, useMemo, useRef, useState } from "react";
import { Pressable, type PressableStateCallbackType, Text, View } from "react-native";
import { keepPreviousData, useMutation, useQueries, useQueryClient } from "@tanstack/react-query";
import { useMutation, useQueries, useQueryClient, type QueryClient } from "@tanstack/react-query";
import { useTranslation } from "react-i18next";
import type {
DaemonClient,
@@ -40,6 +40,7 @@ import {
resolveDirectoryLabel,
nextPageLimit,
PER_PROVIDER_LIMIT,
previousPageLimit,
type ProviderErrorRow,
resolveImportTarget,
resolveProvidersToFetch,
@@ -100,11 +101,12 @@ interface SessionsQueryConfig {
// Query's default retry would keep the header spinner turning and pile up
// in-flight daemon requests behind a dead provider (#2512).
retry: false;
placeholderData: typeof keepPreviousData;
placeholderData: () => RecentSessionsResponse | undefined;
queryFn: () => Promise<RecentSessionsResponse>;
}
function buildSessionsQueriesConfig(args: {
queryClient: QueryClient;
providersToFetch: AgentProvider[] | null;
visible: boolean;
client: RecentProviderSessionsClient | null;
@@ -113,14 +115,24 @@ function buildSessionsQueriesConfig(args: {
limit: number;
hostDisconnectedMessage?: string;
}): SessionsQueryConfig[] {
const { providersToFetch, visible, client, cwd, query, limit, hostDisconnectedMessage } = args;
const { queryClient, providersToFetch, visible, client, cwd, query, limit } = args;
const { hostDisconnectedMessage } = args;
if (providersToFetch === null) return [];
const enabled = visible && Boolean(client);
const previousLimit = previousPageLimit(limit);
return providersToFetch.map((provider) => ({
queryKey: buildSessionsQueryKey({ cwd, query, limit, provider }),
enabled,
retry: false as const,
placeholderData: keepPreviousData,
// While Load more fetches the next page, keep showing the page it grew from. React Query's
// keepPreviousData cannot do this here: useQueries gives a changed key a new observer, which
// has no previous data, so the rows would vanish and the list would remount at the top.
placeholderData: () =>
previousLimit === null
? undefined
: queryClient.getQueryData<RecentSessionsResponse>(
buildSessionsQueryKey({ cwd, query, limit: previousLimit, provider }),
),
queryFn: async () => {
if (!client) {
throw new Error(hostDisconnectedMessage ?? i18n.t("workspace.terminal.hostDisconnected"));
@@ -522,6 +534,7 @@ export function ImportSessionSheet({
const queriesConfig = useMemo(
() =>
buildSessionsQueriesConfig({
queryClient,
providersToFetch,
visible,
client,
@@ -530,7 +543,7 @@ export function ImportSessionSheet({
limit: pageLimit,
hostDisconnectedMessage: t("workspace.terminal.hostDisconnected"),
}),
[providersToFetch, visible, client, scopeCwd, query, pageLimit, t],
[queryClient, providersToFetch, visible, client, scopeCwd, query, pageLimit, t],
);
const queries = useQueries({ queries: queriesConfig });
+2 -1
View File
@@ -484,7 +484,8 @@ export const ar: TranslationResources = {
archivedTitle: "مساحة العمل مؤرشفة",
restoreDescription:
"استعد {{workspaceName}} للعودة إلى وكلائها. ستستخدم شجرة العمل الفرع {{branch}}.",
restoreWithoutBranchDescription: "استعد {{workspaceName}} للعودة إلى وكلائها.",
restoreWithoutBranchDescription:
"استعد {{workspaceName}} للعودة إلى وكلائها. سيبدأ فرع جديد من الفرع الأساسي المحفوظ أو الفرع الافتراضي للمستودع.",
unarchiveDescription: "{{workspaceName}} مؤرشفة. ألغِ أرشفتها لفتحها مجددًا.",
restoreAction: "استعادة",
unarchiveAction: "إلغاء الأرشفة",
+2 -1
View File
@@ -483,7 +483,8 @@ export const en = {
archivedTitle: "Workspace archived",
restoreDescription:
"Restore {{workspaceName}} to return to its agents. Its worktree will use branch {{branch}}.",
restoreWithoutBranchDescription: "Restore {{workspaceName}} to return to its agents.",
restoreWithoutBranchDescription:
"Restore {{workspaceName}} to return to its agents. A new branch will start from the saved base or the repository default.",
unarchiveDescription: "{{workspaceName}} is archived. Unarchive it to open it again.",
restoreAction: "Restore",
unarchiveAction: "Unarchive",
+2 -1
View File
@@ -489,7 +489,8 @@ export const es: TranslationResources = {
archivedTitle: "Espacio de trabajo archivado",
restoreDescription:
"Restaura {{workspaceName}} para volver a sus agentes. Su worktree usará la rama {{branch}}.",
restoreWithoutBranchDescription: "Restaura {{workspaceName}} para volver a sus agentes.",
restoreWithoutBranchDescription:
"Restaura {{workspaceName}} para volver a sus agentes. Se creará una rama nueva desde la base guardada o la rama predeterminada del repositorio.",
unarchiveDescription:
"{{workspaceName}} está archivado. Desarchívalo para volver a abrirlo.",
restoreAction: "Restaurar",
+2 -1
View File
@@ -489,7 +489,8 @@ export const fr: TranslationResources = {
archivedTitle: "Espace de travail archivé",
restoreDescription:
"Restaurez {{workspaceName}} pour retrouver ses agents. Son worktree utilisera la branche {{branch}}.",
restoreWithoutBranchDescription: "Restaurez {{workspaceName}} pour retrouver ses agents.",
restoreWithoutBranchDescription:
"Restaurez {{workspaceName}} pour retrouver ses agents. Une nouvelle branche partira de la base enregistrée ou de la branche par défaut du dépôt.",
unarchiveDescription: "{{workspaceName}} est archivé. Désarchivez-le pour le rouvrir.",
restoreAction: "Restaurer",
unarchiveAction: "Désarchiver",
+2 -1
View File
@@ -489,7 +489,8 @@ export const ja: TranslationResources = {
archivedTitle: "ワークスペースはアーカイブ済みです",
restoreDescription:
"{{workspaceName}} を復元してエージェントに戻ります。worktree ではブランチ {{branch}} を使用します。",
restoreWithoutBranchDescription: "{{workspaceName}} を復元してエージェントに戻ります。",
restoreWithoutBranchDescription:
"{{workspaceName}} を復元してエージェントに戻ります。保存されたベース、またはリポジトリのデフォルトブランチから新しいブランチを作成します。",
unarchiveDescription:
"{{workspaceName}} はアーカイブされています。再度開くにはアーカイブを解除してください。",
restoreAction: "復元",
+2 -1
View File
@@ -485,7 +485,8 @@ export const ko: TranslationResources = {
archivedTitle: "워크스페이스가 보관되었습니다",
restoreDescription:
"{{workspaceName}}를 복원하여 에이전트로 돌아갑니다. 워크트리는 {{branch}} 브랜치를 사용합니다.",
restoreWithoutBranchDescription: "{{workspaceName}}를 복원하여 에이전트로 돌아갑니다.",
restoreWithoutBranchDescription:
"{{workspaceName}}를 복원하여 에이전트로 돌아갑니다. 저장된 기반 브랜치 또는 저장소 기본 브랜치에서 새 브랜치를 만듭니다.",
unarchiveDescription: "{{workspaceName}}가 보관되었습니다. 다시 열려면 보관을 취소하세요.",
restoreAction: "복원",
unarchiveAction: "보관 취소",
+2 -1
View File
@@ -488,7 +488,8 @@ export const ptBR: TranslationResources = {
archivedTitle: "Workspace arquivado",
restoreDescription:
"Restaure {{workspaceName}} para voltar aos seus agentes. A worktree usará a branch {{branch}}.",
restoreWithoutBranchDescription: "Restaure {{workspaceName}} para voltar aos seus agentes.",
restoreWithoutBranchDescription:
"Restaure {{workspaceName}} para voltar aos seus agentes. Uma nova branch partirá da base salva ou da branch padrão do repositório.",
unarchiveDescription:
"{{workspaceName}} está arquivado. Desarquive-o para abri-lo novamente.",
restoreAction: "Restaurar",
+1 -1
View File
@@ -489,7 +489,7 @@ export const ru: TranslationResources = {
restoreDescription:
"Восстановите «{{workspaceName}}», чтобы вернуться к его агентам. Worktree будет использовать ветку {{branch}}.",
restoreWithoutBranchDescription:
"Восстановите «{{workspaceName}}», чтобы вернуться к его агентам.",
"Восстановите «{{workspaceName}}», чтобы вернуться к его агентам. Новая ветка будет создана от сохранённой базовой или ветки репозитория по умолчанию.",
unarchiveDescription:
"Рабочее пространство «{{workspaceName}}» находится в архиве. Разархивируйте его, чтобы снова открыть.",
restoreAction: "Восстановить",
+2 -1
View File
@@ -484,7 +484,8 @@ export const zhCN: TranslationResources = {
archivedTitle: "Workspace 已归档",
restoreDescription:
"恢复 {{workspaceName}} 以返回其中的代理。worktree 将使用分支 {{branch}}。",
restoreWithoutBranchDescription: "恢复 {{workspaceName}} 以返回其中的代理。",
restoreWithoutBranchDescription:
"恢复 {{workspaceName}} 以返回其中的代理。新分支将从保存的基准分支或仓库默认分支创建。",
unarchiveDescription: "{{workspaceName}} 已归档。取消归档以重新打开。",
restoreAction: "恢复",
unarchiveAction: "取消归档",
@@ -3,7 +3,7 @@ import type { WorktreeSource } from "../utils/worktree.js";
export type WorktreeCreationIntent = Exclude<
WorktreeSource,
{ kind: "restore" | "restore-from-base" | "restore-archived-head" }
{ kind: "restore" | "restore-from-base" }
>;
export interface ResolveWorktreeCreationIntentInput {
@@ -1,7 +1,6 @@
import { execFileSync } from "node:child_process";
import os from "node:os";
import path from "node:path";
import { mkdirSync, mkdtempSync, rmSync, statSync, symlinkSync, writeFileSync } from "node:fs";
import { mkdirSync, mkdtempSync, rmSync, statSync, symlinkSync } from "node:fs";
import { afterEach, beforeEach, expect, test } from "vitest";
@@ -26,7 +25,6 @@ import {
} from "../../workspace-registry.js";
import { checkoutLiteFromGitSnapshot } from "../../workspace-registry-model.js";
import type { CreatePaseoWorktreeWorkflowResult } from "../../worktree-session.js";
import { saveArchivedHead } from "../workspace-recovery/archived-head.js";
import {
createWorkspaceProvisioningService,
WorkspaceProvisioningError,
@@ -588,106 +586,6 @@ test("ensureWorkspaceRecordUnarchived restores the owning archived project with
expect((await projectRegistry.get(created.projectId))?.archivedAt).toBeNull();
});
test.each([
["a current", "ws-detached-worktree"],
["a pre-v0.1.95 path-shaped", "worktree-path"],
])(
"ensureWorkspaceRecordUnarchived deletes the HEAD the archive saved, for %s ID",
async (_label, idShape) => {
const repo = path.join(tmpDir, "repo");
const worktree = path.join(tmpDir, "worktree");
const git = (cwd: string, args: string[]) =>
execFileSync("git", args, { cwd, encoding: "utf8" }).trim();
mkdirSync(repo);
git(repo, ["init", "-b", "main"]);
git(repo, [
"-c",
"user.name=Test",
"-c",
"user.email=test@example.com",
"commit",
"--allow-empty",
"-m",
"base",
]);
git(repo, ["worktree", "add", "--detach", worktree]);
gitRoots.add(repo);
const project = await provisioning.findOrCreateWorkspaceForDirectory(repo);
const workspace = createPersistedWorkspaceRecord({
workspaceId: idShape === "worktree-path" ? worktree : idShape,
projectId: project.projectId,
cwd: worktree,
kind: "worktree",
displayName: "detached",
worktreeRoot: worktree,
isPaseoOwnedWorktree: true,
mainRepoRoot: repo,
createdAt: ARCHIVED_AT,
updatedAt: ARCHIVED_AT,
archivedAt: ARCHIVED_AT,
});
await workspaceRegistry.upsert(workspace);
// The archive saved HEAD, then failed to remove the folder.
await saveArchivedHead({ worktreePath: worktree, workspaceIds: [workspace.workspaceId] });
expect(git(repo, ["for-each-ref", "--format=%(objectname)", "refs/paseo"])).toBe(
git(worktree, ["rev-parse", "HEAD"]),
);
const unarchived = await provisioning.ensureWorkspaceRecordUnarchived(workspace);
expect(unarchived.archivedAt).toBeNull();
expect(git(repo, ["for-each-ref", "refs/paseo"])).toBe("");
},
);
test("ensureWorkspaceRecordUnarchived keeps the workspace archived when git cannot delete the saved HEAD", async () => {
const repo = path.join(tmpDir, "repo");
const worktree = path.join(tmpDir, "worktree");
const git = (cwd: string, args: string[]) =>
execFileSync("git", args, { cwd, encoding: "utf8" }).trim();
mkdirSync(repo);
git(repo, ["init", "-b", "main"]);
git(repo, [
"-c",
"user.name=Test",
"-c",
"user.email=test@example.com",
"commit",
"--allow-empty",
"-m",
"base",
]);
git(repo, ["worktree", "add", "--detach", worktree]);
gitRoots.add(repo);
const project = await provisioning.findOrCreateWorkspaceForDirectory(repo);
const workspace = createPersistedWorkspaceRecord({
workspaceId: "ws-detached-worktree",
projectId: project.projectId,
cwd: worktree,
kind: "worktree",
displayName: "detached",
worktreeRoot: worktree,
isPaseoOwnedWorktree: true,
mainRepoRoot: repo,
createdAt: ARCHIVED_AT,
updatedAt: ARCHIVED_AT,
archivedAt: ARCHIVED_AT,
});
await workspaceRegistry.upsert(workspace);
// The archive saved HEAD, then failed to remove the folder.
await saveArchivedHead({ worktreePath: worktree, workspaceIds: [workspace.workspaceId] });
expect(git(repo, ["for-each-ref", "--format=%(objectname)", "refs/paseo"])).toBe(
git(worktree, ["rev-parse", "HEAD"]),
);
// Another git command holds the refs lock.
writeFileSync(path.join(repo, ".git", "packed-refs.lock"), "");
await expect(provisioning.ensureWorkspaceRecordUnarchived(workspace)).rejects.toThrow();
expect((await workspaceRegistry.get(workspace.workspaceId))?.archivedAt).toBe(ARCHIVED_AT);
});
test("ensureWorkspaceRecordUnarchived preserves the consumed auto-archive change request", async () => {
const repo = path.join(tmpDir, "repo");
const changeRequestUrl = "https://github.com/getpaseo/paseo/pull/2714";
@@ -23,7 +23,6 @@ import { deriveProjectKey } from "../../project-key.js";
import { areEquivalentPaths, createRealpathAwarePathMatcher } from "../../../utils/path.js";
import type { UntrustedWorkspaceSource } from "../../workspace-automation-gate.js";
import { readPaseoWorktreeMetadata } from "../../../utils/worktree-metadata.js";
import { releaseArchivedHead } from "../workspace-recovery/archived-head.js";
export interface ResolveOrCreateWorkspaceIdInput {
createdWorktree: CreatePaseoWorktreeWorkflowResult | null;
@@ -435,21 +434,6 @@ export function createWorkspaceProvisioningService(deps: {
: workspace.autoArchivedChangeRequestUrl;
}
// Every unarchive passes through ensureWorkspaceRecordUnarchived, so releasing here means a
// saved HEAD exists only while its workspace is archived.
async function releaseSavedHead(
workspace: PersistedWorkspaceRecord,
project: PersistedProjectRecord,
): Promise<void> {
if (!workspace.archivedAt) return;
await releaseArchivedHead({
// COMPAT(worktreeRestoreMissingMainRepoRoot): records created before v0.1.110 lack
// mainRepoRoot; remove the project-root fallback after 2027-01-17.
repoRoot: workspace.mainRepoRoot ?? project.rootPath,
workspaceId: workspace.workspaceId,
});
}
async function ensureWorkspaceRecordUnarchived(
workspace: PersistedWorkspaceRecord,
archivedAt = workspace.archivedAt,
@@ -477,7 +461,6 @@ export function createWorkspaceProvisioningService(deps: {
updatedAt: timestamp,
};
}
await releaseSavedHead(workspace, project);
if (project.archivedAt || workspace.archivedAt) {
const projectCheckout =
checkout && areEquivalentPaths(project.rootPath, workspace.cwd)
@@ -1,110 +0,0 @@
import { execFileSync } from "node:child_process";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, expect, test } from "vitest";
import { readArchivedHead, releaseArchivedHead, saveArchivedHead } from "./archived-head.js";
const tempDirectories: string[] = [];
afterEach(() => {
for (const directory of tempDirectories.splice(0)) {
rmSync(directory, { recursive: true, force: true });
}
});
function git(cwd: string, args: string[]): string {
return execFileSync("git", ["-c", "user.name=T", "-c", "user.email=t@e.com", ...args], {
cwd,
encoding: "utf8",
}).trim();
}
function createRepositoryWithWorktree() {
const tempDir = mkdtempSync(join(tmpdir(), "paseo-archived-head-"));
tempDirectories.push(tempDir);
const repoRoot = join(tempDir, "repo");
const worktreePath = join(tempDir, "worktree");
git(tempDir, ["init", "-b", "main", repoRoot]);
git(repoRoot, ["commit", "--allow-empty", "-m", "base"]);
git(repoRoot, ["worktree", "add", "-b", "feature", worktreePath]);
git(worktreePath, ["commit", "--allow-empty", "-m", "feature work"]);
return { repoRoot, worktreePath };
}
function removeWorktree(repoRoot: string, worktreePath: string): void {
git(repoRoot, ["worktree", "remove", "--force", worktreePath]);
}
test("restore checks out the saved branch while it still points at the saved commit, and the commit otherwise", async () => {
const { repoRoot, worktreePath } = createRepositoryWithWorktree();
const commit = git(worktreePath, ["rev-parse", "HEAD"]);
await saveArchivedHead({ worktreePath, workspaceIds: ["wks_a"] });
removeWorktree(repoRoot, worktreePath);
const onBranch = await readArchivedHead({ repoRoot, workspaceId: "wks_a" });
git(repoRoot, ["branch", "-f", "feature", "main"]);
const branchMoved = await readArchivedHead({ repoRoot, workspaceId: "wks_a" });
git(repoRoot, ["branch", "-D", "feature"]);
const branchDeleted = await readArchivedHead({ repoRoot, workspaceId: "wks_a" });
expect({ onBranch, branchMoved, branchDeleted }).toEqual({
onBranch: { checkout: "feature", commit },
branchMoved: { checkout: commit, commit },
branchDeleted: { checkout: commit, commit },
});
});
test("each workspace on the folder keeps its own saved HEAD until it is released", async () => {
const { repoRoot, worktreePath } = createRepositoryWithWorktree();
const commit = git(worktreePath, ["rev-parse", "HEAD"]);
// Before v0.1.95 a workspace ID was its path, which git rejects in a ref name.
const pathShapedId = "/home/u/.paseo/worktrees/repo/feature";
await saveArchivedHead({ worktreePath, workspaceIds: ["wks_root", pathShapedId] });
removeWorktree(repoRoot, worktreePath);
await releaseArchivedHead({ repoRoot, workspaceId: "wks_root" });
expect({
released: await readArchivedHead({ repoRoot, workspaceId: "wks_root" }),
kept: await readArchivedHead({ repoRoot, workspaceId: pathShapedId }),
never: await readArchivedHead({ repoRoot, workspaceId: "wks_other" }),
}).toEqual({ released: null, kept: { checkout: "feature", commit }, never: null });
await releaseArchivedHead({ repoRoot, workspaceId: pathShapedId });
expect(git(repoRoot, ["for-each-ref", "refs/paseo"])).toBe("");
});
test("archiving again once the folder is gone keeps the HEAD saved before", async () => {
const { repoRoot, worktreePath } = createRepositoryWithWorktree();
const commit = git(worktreePath, ["rev-parse", "HEAD"]);
await saveArchivedHead({ worktreePath, workspaceIds: ["wks_a"] });
removeWorktree(repoRoot, worktreePath);
await saveArchivedHead({ worktreePath, workspaceIds: ["wks_a"] });
expect(await readArchivedHead({ repoRoot, workspaceId: "wks_a" })).toEqual({
checkout: "feature",
commit,
});
});
test("saving again replaces the HEAD saved before, whatever git named it", async () => {
const { repoRoot, worktreePath } = createRepositoryWithWorktree();
await saveArchivedHead({ worktreePath, workspaceIds: ["wks_a"] });
// The next name sits below the saved one, which git cannot hold beside it.
git(worktreePath, ["checkout", "-b", "other"]);
git(worktreePath, ["branch", "-D", "feature"]);
git(worktreePath, ["checkout", "-b", "feature/next"]);
git(worktreePath, ["checkout", "--detach"]);
const detached = git(worktreePath, ["rev-parse", "HEAD"]);
await saveArchivedHead({ worktreePath, workspaceIds: ["wks_a"] });
git(worktreePath, ["checkout", "feature/next"]);
await saveArchivedHead({ worktreePath, workspaceIds: ["wks_a"] });
removeWorktree(repoRoot, worktreePath);
expect({
saved: git(repoRoot, ["for-each-ref", "--format=%(objectname)", "refs/paseo"]),
restored: await readArchivedHead({ repoRoot, workspaceId: "wks_a" }),
}).toEqual({ saved: detached, restored: { checkout: "feature/next", commit: detached } });
});
@@ -1,122 +0,0 @@
import { createHash } from "node:crypto";
import { stat } from "node:fs/promises";
import { join } from "node:path";
import { runGitCommand } from "../../../utils/run-git-command.js";
// Removing a worktree folder at archive deletes its HEAD, and with it the only hold on commits
// that no branch reaches. Archive saves HEAD for each workspace it archives, at that moment and
// whether or not the folder goes:
//
// refs/paseo/archived/<sha256 of the workspace ID>/<git's name for HEAD> -> HEAD's commit
//
// The name is `git rev-parse --abbrev-ref HEAD`, stored as git prints it and never parsed here.
// The ref keeps the commit alive, and recovery hands the name back to git when it still means
// that commit, so git decides whether the worktree comes back on a branch or detached.
//
// The ref belongs to the workspace record: only its archive writes it, only its restore reads it,
// and only its unarchive deletes it. The ID is hashed because pre-v0.1.95 IDs are paths, which git rejects in a ref name.
// Refs outside refs/heads, refs/tags and refs/remotes are shared by every worktree of a
// repository and hidden from branch lists, pushes and fetches.
async function exists(path: string): Promise<boolean> {
return stat(path).then(
() => true,
() => false,
);
}
function savedHeadPrefix(workspaceId: string): string {
const workspace = createHash("sha256").update(workspaceId).digest("hex");
return `refs/paseo/archived/${workspace}/`;
}
async function listSavedHeads(cwd: string, prefix: string): Promise<string[]> {
const { stdout } = await runGitCommand(
["for-each-ref", "--format=%(objectname) %(refname)", prefix],
{ cwd },
);
return stdout.split("\n").filter((line) => line.length > 0);
}
async function discardSavedHeads(cwd: string, prefix: string): Promise<void> {
for (const line of await listSavedHeads(cwd, prefix)) {
await runGitCommand(["update-ref", "-d", line.slice(line.indexOf(" ") + 1)], { cwd });
}
}
async function isRepository(path: string): Promise<boolean> {
if (!(await exists(path))) return false;
const repository = await runGitCommand(["rev-parse", "--git-dir"], {
cwd: path,
acceptExitCodes: [0, 128],
});
return repository.exitCode === 0;
}
// git's name for the folder's HEAD, or null when the folder no longer has one: its `.git` link
// is gone, or the administration it points to is.
async function readHeadName(worktreePath: string): Promise<string | null> {
if (!(await exists(join(worktreePath, ".git")))) return null;
const head = await runGitCommand(["rev-parse", "--abbrev-ref", "HEAD"], {
cwd: worktreePath,
acceptExitCodes: [0, 128],
});
return head.exitCode === 0 ? head.stdout.trim() : null;
}
/**
* Saves the worktree's HEAD for each workspace being archived from it. A folder without a HEAD has
* nothing to save, and what an earlier archive saved for these workspaces stays.
*/
export async function saveArchivedHead(input: {
worktreePath: string;
workspaceIds: readonly string[];
}): Promise<void> {
const name = await readHeadName(input.worktreePath);
if (!name) return;
const cwd = input.worktreePath;
for (const workspaceId of input.workspaceIds) {
const prefix = savedHeadPrefix(workspaceId);
// Delete before create: an earlier `feature` would block a new `feature/next`.
await discardSavedHeads(cwd, prefix);
await runGitCommand(["update-ref", `${prefix}${name}`, "HEAD"], { cwd });
}
}
/** What recovery checks out: the saved name while it still means the saved commit, else the commit. */
export interface ArchivedHead {
checkout: string;
commit: string;
}
export async function readArchivedHead(input: {
repoRoot: string;
workspaceId: string;
}): Promise<ArchivedHead | null> {
if (!(await isRepository(input.repoRoot))) return null;
const prefix = savedHeadPrefix(input.workspaceId);
const [saved] = await listSavedHeads(input.repoRoot, prefix);
if (!saved) return null;
const separator = saved.indexOf(" ");
const commit = saved.slice(0, separator);
const name = saved.slice(separator + 1 + prefix.length);
const named = await runGitCommand(["rev-parse", "--verify", "--quiet", `${name}^{commit}`], {
cwd: input.repoRoot,
acceptExitCodes: [0, 1],
});
return { checkout: named.stdout.trim() === commit ? name : commit, commit };
}
/**
* Deletes the workspace's saved HEAD when it is unarchived. Throws when git cannot, so the
* workspace stays archived with its ref rather than active with a ref a later restore would read.
*/
export async function releaseArchivedHead(input: {
repoRoot: string;
workspaceId: string;
}): Promise<void> {
// Without a repository there is no ref to delete.
if (!(await isRepository(input.repoRoot))) return;
await discardSavedHeads(input.repoRoot, savedHeadPrefix(input.workspaceId));
}
@@ -29,7 +29,6 @@ import {
type PersistedProjectRecord,
type PersistedWorkspaceRecord,
} from "../../workspace-registry.js";
import { saveArchivedHead } from "./archived-head.js";
import { createWorkspaceRecoveryService } from "./workspace-recovery-service.js";
const NOW = "2026-07-11T10:12:30.752Z";
@@ -397,64 +396,6 @@ test("restores a branchless workspace from its recorded base so work can continu
);
});
test.each([
["still names the branch HEAD left", "feature"],
["names no branch", null],
])(
"restores the HEAD archive saved, and does not describe a branch, when the record %s",
async (_label, recordedBranch) => {
const fixture = await createBaseRecoveryFixture("main");
const worktree = fixture.workspace.cwd;
execFileSync("git", ["checkout", "--detach"], { cwd: worktree, stdio: "pipe" });
writeFileSync(join(worktree, "detached.txt"), "detached\n");
execFileSync("git", ["add", "detached.txt"], { cwd: worktree, stdio: "pipe" });
execFileSync("git", ["-c", "commit.gpgsign=false", "commit", "-m", "detached"], {
cwd: worktree,
stdio: "pipe",
});
const detachedCommit = execFileSync("git", ["rev-parse", "HEAD"], {
cwd: worktree,
encoding: "utf8",
}).trim();
await fixture.registry.update(fixture.workspace.workspaceId, (workspace) => ({
...workspace,
branch: recordedBranch,
}));
await saveArchivedHead({
worktreePath: worktree,
workspaceIds: [fixture.workspace.workspaceId],
});
await fixture.archiveAndRemove();
const described = await fixture.service.inspect(fixture.workspace.workspaceId);
await fixture.service.restore(fixture.workspace.workspaceId);
expect({
described: described.kind === "recoverable" ? described.branch : "unavailable",
branch: execFileSync("git", ["branch", "--show-current"], {
cwd: worktree,
encoding: "utf8",
}).trim(),
head: execFileSync("git", ["rev-parse", "HEAD"], { cwd: worktree, encoding: "utf8" }).trim(),
}).toEqual({ described: null, branch: "", head: detachedCommit });
},
);
test("restores the HEAD archive saved against the repository default when the record has no base", async () => {
const fixture = await createBaseRecoveryFixture(null);
await saveArchivedHead({
worktreePath: fixture.workspace.cwd,
workspaceIds: [fixture.workspace.workspaceId],
});
await fixture.archiveAndRemove();
await fixture.service.restore(fixture.workspace.workspaceId);
expect(await readPaseoWorktreeMetadata(fixture.workspace.cwd)).toMatchObject({
baseRefName: "main",
});
});
test("restores a branchless workspace from the repository default when its base is missing", async () => {
const fixture = await createBaseRecoveryFixture("refs/heads/deleted-base");
await fixture.registry.update(fixture.workspace.workspaceId, (workspace) => ({
@@ -17,7 +17,6 @@ import {
type PersistedProjectRecord,
type PersistedWorkspaceRecord,
} from "../../workspace-registry.js";
import { readArchivedHead, type ArchivedHead } from "./archived-head.js";
export type WorkspaceRecoveryAction = "unarchive" | "restore";
@@ -58,16 +57,8 @@ type RecoveryPlan =
state: Extract<WorkspaceRecoveryState, { kind: "recoverable" }>;
workspace: PersistedWorkspaceRecord;
sourceRepoRoot: string;
previousWorktree: PreviousWorktree;
// Read once here so the state shown to the user and the checkout restore makes agree.
archivedHead: ArchivedHead | null;
};
interface PreviousWorktree {
path: string;
isRecorded: boolean;
}
type UnavailableRecoveryState = Extract<WorkspaceRecoveryState, { kind: "unavailable" }>;
export function createWorkspaceRecoveryService(deps: {
@@ -133,33 +124,7 @@ export function createWorkspaceRecoveryService(deps: {
};
}
const previousWorktree = await resolvePreviousWorktree(workspace);
const archivedHead = await readArchivedHead({
repoRoot: sourceRepoRoot,
workspaceId: workspace.workspaceId,
});
return createRecoveryPlan({
action: "restore",
workspace,
sourceRepoRoot,
previousWorktree,
archivedHead,
});
}
async function resolvePreviousWorktree(
workspace: PersistedWorkspaceRecord,
): Promise<PreviousWorktree> {
if (workspace.worktreeRoot) return { path: workspace.worktreeRoot, isRecorded: true };
// COMPAT(worktreeRestoreMissingWorktreeRoot): records created before v0.1.110
// lack durable backing placement; remove filesystem discovery after 2027-01-17.
const ownership = await isPaseoOwnedWorktreeCwd(workspace.cwd, {
paseoHome: deps.paseoHome,
worktreesRoot: deps.worktreesRoot,
});
return ownership.allowed
? { path: ownership.worktreePath ?? workspace.cwd, isRecorded: true }
: { path: workspace.cwd, isRecorded: false };
return createRecoveryPlan({ action: "restore", workspace, sourceRepoRoot });
}
async function inspect(workspaceId: string): Promise<WorkspaceRecoveryState> {
@@ -176,17 +141,23 @@ export function createWorkspaceRecoveryService(deps: {
}
if (resolved.kind === "restore") {
await recreateArchivedWorktree(resolved);
await recreateArchivedWorktree(resolved.workspace, resolved.sourceRepoRoot);
}
await deps.unarchiveWorkspace(resolved.workspace);
return { workspaceId, action: resolved.kind };
}
async function recreateArchivedWorktree(
plan: Extract<RecoveryPlan, { kind: "restore" }>,
workspace: PersistedWorkspaceRecord,
sourceRepoRoot: string,
): Promise<void> {
const { workspace, sourceRepoRoot, previousWorktree } = plan;
const source = await resolveRecoverySource(plan);
const source: WorktreeSource = workspace.branch
? { kind: "restore", branchName: workspace.branch, baseRef: workspace.baseBranch }
: {
kind: "restore-from-base",
branchName: `restored/${randomUUID().slice(0, 8)}`,
baseRef: await resolveRecoveryBase(sourceRepoRoot, workspace.baseBranch),
};
try {
await runGitCommand(["worktree", "prune"], { cwd: sourceRepoRoot, timeout: 30_000 });
@@ -194,16 +165,31 @@ export function createWorkspaceRecoveryService(deps: {
// A stale worktree registration is not guaranteed; creation reports any real conflict.
}
let previousWorktreePath = workspace.worktreeRoot;
let hasRecordedWorktreePath = Boolean(previousWorktreePath);
if (!previousWorktreePath) {
// COMPAT(worktreeRestoreMissingWorktreeRoot): records created before v0.1.110
// lack durable backing placement; remove filesystem discovery after 2027-01-17.
const ownership = await isPaseoOwnedWorktreeCwd(workspace.cwd, {
paseoHome: deps.paseoHome,
worktreesRoot: deps.worktreesRoot,
});
previousWorktreePath = ownership.allowed
? (ownership.worktreePath ?? workspace.cwd)
: workspace.cwd;
hasRecordedWorktreePath = ownership.allowed;
}
let recreatedWorktreePath: string;
try {
const result = await createWorktree({
cwd: sourceRepoRoot,
worktreeSlug: basename(previousWorktree.path),
worktreeSlug: basename(previousWorktreePath),
source,
paseoHome: deps.paseoHome,
worktreesRoot: deps.worktreesRoot,
...(previousWorktree.isRecorded ? { worktreePath: previousWorktree.path } : {}),
...(hasRecordedWorktreePath ? { worktreePath: previousWorktreePath } : {}),
});
recreatedWorktreePath = result.worktreePath;
} catch (error) {
@@ -212,7 +198,7 @@ export function createWorkspaceRecoveryService(deps: {
try {
const recreatedWorkspacePath = mapWorkspaceCwdToWorktree({
sourceWorktreePath: previousWorktree.path,
sourceWorktreePath: previousWorktreePath,
workspaceCwd: workspace.cwd,
targetWorktreePath: recreatedWorktreePath,
});
@@ -245,27 +231,6 @@ export function createWorkspaceRecoveryService(deps: {
return { inspect, restore };
}
async function resolveRecoverySource(
plan: Extract<RecoveryPlan, { kind: "restore" }>,
): Promise<WorktreeSource> {
const { workspace, sourceRepoRoot, archivedHead } = plan;
if (archivedHead) {
return {
kind: "restore-archived-head",
...archivedHead,
baseRef: workspace.baseBranch ?? (await resolveRepositoryDefaultBranch(sourceRepoRoot)),
};
}
if (workspace.branch) {
return { kind: "restore", branchName: workspace.branch, baseRef: workspace.baseBranch };
}
return {
kind: "restore-from-base",
branchName: `restored/${randomUUID().slice(0, 8)}`,
baseRef: await resolveRecoveryBase(sourceRepoRoot, workspace.baseBranch),
};
}
async function resolveRecoveryBase(repoRoot: string, recordedBase: string | null): Promise<string> {
if (recordedBase) {
try {
@@ -289,7 +254,7 @@ async function resolveRecoveryBase(repoRoot: string, recordedBase: string | null
function createRecoveryPlan(
input:
| { action: "unarchive"; workspace: PersistedWorkspaceRecord }
| (Omit<Extract<RecoveryPlan, { kind: "restore" }>, "kind" | "state"> & { action: "restore" }),
| { action: "restore"; workspace: PersistedWorkspaceRecord; sourceRepoRoot: string },
): RecoveryPlan {
const state = {
kind: "recoverable" as const,
@@ -298,13 +263,11 @@ function createRecoveryPlan(
branch: input.workspace.branch,
};
if (input.action === "restore") {
const { action, ...plan } = input;
return {
...plan,
kind: action,
// The record's branch is the last one observed, and HEAD may have left it before the
// archive. With a saved HEAD, git decides at restore what HEAD comes back as.
state: { ...state, action, branch: input.archivedHead ? null : state.branch },
kind: input.action,
state: { ...state, action: input.action },
workspace: input.workspace,
sourceRepoRoot: input.sourceRepoRoot,
};
}
return {
@@ -21,7 +21,6 @@ import type {
import { createRealpathAwarePathMatcher } from "../utils/path.js";
import { runWithGitCommandPriority } from "../utils/run-git-command.js";
import { WorkspaceAutomationBlockedError } from "./workspace-automation-gate.js";
import { saveArchivedHead } from "./session/workspace-recovery/archived-head.js";
export type ActiveWorkspaceRef = Pick<
PersistedWorkspaceRecord,
@@ -447,20 +446,6 @@ async function maybeRemoveDirectory(
return { removedDirectory: false };
}
try {
// Each workspace this archive took off the folder keeps the HEAD it had, whether or not the
// folder goes, so no later archive of the folder writes for it.
await saveArchivedHead({ worktreePath: backing.path, workspaceIds: archivedWorkspaceIds });
} catch (error) {
// Without the saved HEAD, removing the folder could delete commits that only its HEAD holds.
const reason = "could not save its HEAD";
dependencies.sessionLogger?.warn(
{ err: error, targetPath: backing.path, requestId: request.requestId },
`Worktree directory left in place during archive: ${reason}`,
);
return { removedDirectory: false, directoryLeftBehind: { path: backing.path, reason } };
}
const archivedWorkspaceIdSet = new Set(archivedWorkspaceIds);
const teardownTargets = target.teardownTargets.filter(
(teardownTarget) =>
@@ -35,10 +35,6 @@ function git(repoDir: string, args: string[]): void {
execFileSync("git", args, { cwd: repoDir, stdio: "pipe" });
}
function gitOutput(cwd: string, args: string[]): string {
return execFileSync("git", args, { cwd, encoding: "utf8" }).trim();
}
/** A repo whose worktree teardown parks until released. */
function createRepoWithGatedTeardown(): GatedRepo {
const tempRoot = mkdtempSync(path.join(tmpdir(), "workspace-archive-undo-"));
@@ -155,234 +151,6 @@ test.skipIf(process.platform === "win32")(
60000,
);
function commitWork(directory: string, file: string): string {
mkdirSync(path.dirname(path.join(directory, file)), { recursive: true });
writeFileSync(path.join(directory, file), "work\n");
git(directory, ["add", file]);
git(directory, ["-c", "commit.gpgsign=false", "commit", "-m", `work on ${file}`]);
return gitOutput(directory, ["rev-parse", "HEAD"]);
}
// What HEAD was at archive, and what the repository did with its branch while archived.
const archivedHeadCases = [
{ name: "detached", detach: true, afterArchive: "nothing", comesBackOn: "" },
{ name: "on a branch", detach: false, afterArchive: "nothing", comesBackOn: "branch" },
{ name: "on a branch that moved", detach: false, afterArchive: "move", comesBackOn: "" },
{ name: "on a branch that was deleted", detach: false, afterArchive: "delete", comesBackOn: "" },
] as const;
for (const route of ["undo", "restore"] as const) {
test.skipIf(process.platform === "win32").each(archivedHeadCases)(
`${route} brings back a worktree archived $name at the commit it was on`,
async ({ detach, afterArchive, comesBackOn }) => {
const repo = createRepoWithGatedTeardown();
repo.releaseTeardown();
const { workspaceId, directory } = await createWorktreeWorkspaceWithAgent(
repo.repoDir,
`archived-head-${route}`,
);
const branch = gitOutput(directory, ["branch", "--show-current"]);
if (detach) git(directory, ["checkout", "--detach"]);
const archivedCommit = commitWork(directory, "work.txt");
const archived = await ctx.client.archiveWorkspace(workspaceId);
expect(archived.error).toBeNull();
expect(existsSync(directory)).toBe(false);
if (afterArchive === "move") git(repo.repoDir, ["branch", "-f", branch, "main"]);
if (afterArchive === "delete") git(repo.repoDir, ["branch", "-D", branch]);
const branchTip =
afterArchive === "move" ? gitOutput(repo.repoDir, ["rev-parse", branch]) : null;
collectUnreachableCommits(repo.repoDir);
if (route === "undo") await ctx.client.undoWorkspaceArchive(workspaceId);
else await ctx.client.restoreWorkspace(workspaceId);
expect({
workspaceActive: await isWorkspaceActive(workspaceId),
head: gitOutput(directory, ["rev-parse", "HEAD"]),
branch: gitOutput(directory, ["branch", "--show-current"]),
branchTip: branchTip && gitOutput(repo.repoDir, ["rev-parse", branch]),
savedHeads: gitOutput(repo.repoDir, ["for-each-ref", "refs/paseo"]),
}).toEqual({
workspaceActive: true,
head: archivedCommit,
branch: comesBackOn === "branch" ? branch : "",
branchTip,
savedHeads: "",
});
},
60000,
);
}
function commitOnDetachedHead(directory: string, file: string): string {
git(directory, ["checkout", "--detach"]);
return commitWork(directory, file);
}
function collectUnreachableCommits(repoDir: string): void {
git(repoDir, ["reflog", "expire", "--expire-unreachable=now", "--all"]);
git(repoDir, ["gc", "--prune=now", "--quiet"]);
}
test.skipIf(process.platform === "win32")(
"archiving again to clean up a folder a failed teardown left keeps its detached commit",
async () => {
const tempRoot = mkdtempSync(path.join(tmpdir(), "workspace-archive-cleanup-"));
tempRoots.push(tempRoot);
const repoDir = path.join(tempRoot, "repo");
execFileSync("git", ["init", "-b", "main", repoDir], { stdio: "pipe" });
git(repoDir, ["config", "user.email", "test@getpaseo.local"]);
git(repoDir, ["config", "user.name", "Paseo Test"]);
writeFileSync(
path.join(repoDir, "paseo.json"),
JSON.stringify({ worktree: { teardown: ["exit 1"] } }),
);
git(repoDir, ["add", "paseo.json"]);
git(repoDir, ["-c", "commit.gpgsign=false", "commit", "-m", "failing teardown"]);
const { workspaceId, directory } = await createWorktreeWorkspaceWithAgent(
repoDir,
"cleanup-archive",
);
const detachedCommit = commitOnDetachedHead(directory, "detached.txt");
await ctx.client.archiveWorkspace(workspaceId);
expect(existsSync(directory)).toBe(true);
await ctx.client.archiveWorkspace(workspaceId);
expect(existsSync(directory)).toBe(false);
collectUnreachableCommits(repoDir);
await ctx.client.restoreWorkspace(workspaceId);
expect({
workspaceActive: await isWorkspaceActive(workspaceId),
head: gitOutput(directory, ["rev-parse", "HEAD"]),
savedHeads: gitOutput(repoDir, ["for-each-ref", "refs/paseo"]),
}).toEqual({ workspaceActive: true, head: detachedCommit, savedHeads: "" });
},
60000,
);
test.skipIf(process.platform === "win32")(
"restoring a worktree archived on a branch opens the new worktree that checked the branch out",
async () => {
const repo = createRepoWithGatedTeardown();
repo.releaseTeardown();
const created = await ctx.client.createWorkspace({
source: {
kind: "worktree",
cwd: repo.repoDir,
action: "branch-off",
branchName: "reused-branch",
baseBranch: "main",
},
});
const archivedId = created.workspace?.id;
const archivedDirectory = created.workspace?.workspaceDirectory;
if (!archivedId || !archivedDirectory) throw new Error(created.error ?? "Failed to create");
const commit = commitWork(archivedDirectory, "work.txt");
await ctx.client.archiveWorkspace(archivedId);
const reopened = await ctx.client.createWorkspace({
source: { kind: "worktree", cwd: repo.repoDir, action: "checkout", refName: "reused-branch" },
});
await ctx.client.restoreWorkspace(archivedId);
expect({
reopenedDirectory: reopened.workspace?.workspaceDirectory,
archivedActive: await isWorkspaceActive(archivedId),
reopenedActive: await isWorkspaceActive(reopened.workspace?.id ?? ""),
head: gitOutput(archivedDirectory, ["rev-parse", "HEAD"]),
branch: gitOutput(archivedDirectory, ["branch", "--show-current"]),
savedHeads: gitOutput(repo.repoDir, ["for-each-ref", "refs/paseo"]),
}).toEqual({
reopenedDirectory: archivedDirectory,
archivedActive: true,
reopenedActive: true,
head: commit,
branch: "reused-branch",
savedHeads: "",
});
},
60000,
);
test.skipIf(process.platform === "win32").each([
{ name: "detached", detach: true },
{ name: "on a branch", detach: false },
] as const)(
"restoring a worktree archived $name brings it back as it was after a new worktree used its folder",
async ({ detach }) => {
const repo = createRepoWithGatedTeardown();
repo.releaseTeardown();
const first = await createWorktreeWorkspaceWithAgent(repo.repoDir, "reused-folder");
const branch = gitOutput(first.directory, ["branch", "--show-current"]);
if (detach) git(first.directory, ["checkout", "--detach"]);
const archivedCommit = commitWork(first.directory, "work.txt");
await ctx.client.archiveWorkspace(first.workspaceId);
const second = await createWorktreeWorkspaceWithAgent(repo.repoDir, "reused-folder");
const secondCommit = gitOutput(second.directory, ["rev-parse", "HEAD"]);
await ctx.client.archiveWorkspace(second.workspaceId);
collectUnreachableCommits(repo.repoDir);
await ctx.client.restoreWorkspace(first.workspaceId);
expect({
secondDirectory: second.directory,
workspaceActive: await isWorkspaceActive(first.workspaceId),
head: gitOutput(first.directory, ["rev-parse", "HEAD"]),
branch: gitOutput(first.directory, ["branch", "--show-current"]),
savedHeads: gitOutput(repo.repoDir, ["for-each-ref", "--format=%(objectname)", "refs/paseo"]),
}).toEqual({
secondDirectory: first.directory,
workspaceActive: true,
head: archivedCommit,
branch: detach ? "" : branch,
savedHeads: secondCommit,
});
},
60000,
);
test.skipIf(process.platform === "win32").each([
["root", "subdirectory"],
["subdirectory", "root"],
] as const)(
"restoring the %s workspace first brings back the detached commit of a worktree two workspaces share",
async (first, second) => {
const repo = createRepoWithGatedTeardown();
repo.releaseTeardown();
const root = await createWorktreeWorkspaceWithAgent(repo.repoDir, `shared-${first}`);
const detachedCommit = commitOnDetachedHead(root.directory, "sub/detached.txt");
const opened = await ctx.client.createWorkspace({
source: { kind: "directory", path: path.join(root.directory, "sub") },
});
const subdirectoryId = opened.workspace?.id;
if (!subdirectoryId) throw new Error(opened.error ?? "Failed to open the subdirectory");
const workspaceIds = { root: root.workspaceId, subdirectory: subdirectoryId };
await ctx.client.archiveWorkspace(workspaceIds.root);
expect(existsSync(root.directory)).toBe(true);
await ctx.client.archiveWorkspace(workspaceIds.subdirectory);
expect(existsSync(root.directory)).toBe(false);
collectUnreachableCommits(repo.repoDir);
await ctx.client.restoreWorkspace(workspaceIds[first]);
await ctx.client.restoreWorkspace(workspaceIds[second]);
expect({
rootActive: await isWorkspaceActive(workspaceIds.root),
subdirectoryActive: await isWorkspaceActive(workspaceIds.subdirectory),
head: gitOutput(root.directory, ["rev-parse", "HEAD"]),
savedHeads: gitOutput(repo.repoDir, ["for-each-ref", "refs/paseo"]),
}).toEqual({
rootActive: true,
subdirectoryActive: true,
head: detachedCommit,
savedHeads: "",
});
},
60000,
);
test.skipIf(process.platform === "win32")(
"archive, undo, archive leaves the workspace archived",
async () => {
+10 -41
View File
@@ -189,8 +189,6 @@ export type WorktreeSource =
| { kind: "checkout-branch"; branchName: string }
| { kind: "restore"; branchName: string; baseRef: string | null }
| { kind: "restore-from-base"; baseRef: string; branchName: string }
// Checks out what archive saved: a branch name puts HEAD back on the branch, a commit detaches.
| { kind: "restore-archived-head"; checkout: string; commit: string; baseRef: string | null }
| {
kind: "checkout-change-request";
forge: string;
@@ -1465,24 +1463,6 @@ interface WorktreeSourcePlan {
};
}
async function resolveRestoredBaseMetadata(
cwd: string,
input: { baseRef: string | null; fallback: string },
): Promise<Pick<WorktreeSourcePlan, "metadataBaseRefName" | "metadataBaseRef">> {
let exactBase: string | undefined;
if (input.baseRef && isQualifiedRef(input.baseRef)) {
try {
exactBase = await resolveBaseBranchForWorktree(cwd, input.baseRef);
} catch {
// Restore the worktree even when its comparison ref no longer exists.
}
}
return {
metadataBaseRefName: normalizeRequiredBaseBranch(input.baseRef ?? input.fallback),
...(exactBase ? { metadataBaseRef: exactBase } : {}),
};
}
async function resolveRestoredWorktreeSourcePlan(
cwd: string,
source: Extract<WorktreeSource, { kind: "restore" }>,
@@ -1492,12 +1472,18 @@ async function resolveRestoredWorktreeSourcePlan(
if (await isBranchCheckedOut(cwd, source.branchName)) {
throw new BranchAlreadyCheckedOutError(source.branchName);
}
let exactBase: string | undefined;
if (source.baseRef && isQualifiedRef(source.baseRef)) {
try {
exactBase = await resolveBaseBranchForWorktree(cwd, source.baseRef);
} catch {
// Restore the saved branch even when its comparison ref no longer exists.
}
}
return {
branchName: source.branchName,
...(await resolveRestoredBaseMetadata(cwd, {
baseRef: source.baseRef,
fallback: source.branchName,
})),
metadataBaseRefName: normalizeRequiredBaseBranch(source.baseRef ?? source.branchName),
...(exactBase ? { metadataBaseRef: exactBase } : {}),
changeRequestLookupTarget: createPaseoWorktreeChangeRequestHint({
headRef: source.branchName,
localBranchName: source.branchName,
@@ -1521,21 +1507,6 @@ async function resolveRestoredWorktreeFromBasePlan(
};
}
async function resolveRestoredArchivedHeadPlan(
cwd: string,
source: Extract<WorktreeSource, { kind: "restore-archived-head" }>,
): Promise<WorktreeSourcePlan> {
return {
// A detached checkout has no branch; the restored worktree's caller reads only its path.
branchName: source.checkout,
...(await resolveRestoredBaseMetadata(cwd, {
baseRef: source.baseRef,
fallback: source.commit,
})),
addArguments: [source.checkout],
};
}
async function resolveBranchOffWorktreeSourcePlan(
cwd: string,
source: Extract<WorktreeSource, { kind: "branch-off" }>,
@@ -1575,8 +1546,6 @@ async function resolveWorktreeSourcePlan({
return resolveRestoredWorktreeSourcePlan(cwd, source);
case "restore-from-base":
return resolveRestoredWorktreeFromBasePlan(cwd, source);
case "restore-archived-head":
return resolveRestoredArchivedHeadPlan(cwd, source);
case "checkout-branch": {
await validateGitBranchName(cwd, source.branchName);
await ensureLocalBranch(cwd, source.branchName);