Compare commits

..
Author SHA1 Message Date
Mohamed BoudraandOkan YILDIRIM 7d07d2df2d fix(archive): save a workspace's HEAD when it is archived, not when its folder goes
Archive saved HEAD for every record on a folder at the moment the folder
was removed, including records archived from it earlier. A new worktree
that reused an archived worktree's folder therefore overwrote the archived
record's saved HEAD when it was itself archived, and the archived one came
back on the new worktree's branch or lost its detached commits.

Archive now saves HEAD for each workspace it archives, at that moment,
whether or not the folder goes. A record's ref is written only by its own
archive, read only by its restore and deleted only by its unarchive. The
listAllWorkspaces dependency and its wiring are gone.

Co-authored-by: Okan YILDIRIM <63511519+ragokan@users.noreply.github.com>
2026-11-17 14:50:03 +01:00
Mohamed BoudraandOkan YILDIRIM 6b64b05e6e fix(archive): save a worktree's HEAD per workspace record, not per folder path
Keying the saved HEAD by folder path needed a path reservation, so a new
worktree at an archived worktree's path could not replace its saved HEAD.
That broke a common flow that works on main: archive a worktree on branch
B, create a new worktree for B, restore the archived one. The new worktree
got <slug>-1, and the restore failed with "already used by worktree". The
path key also needed symlink resolution so placement, archive and restore
agreed on one folder.

The saved HEAD now belongs to the workspace record:
refs/paseo/archived/<sha256 of workspace ID>/<git's name for HEAD>.
Removing a folder saves HEAD once for each record on it, including
records archived from it earlier. Unarchiving a record deletes its own
ref, and fails if git cannot, so no leftover ref is ever read as current.

This removes the path reservation in resolveDefaultWorktreePath, the
utils -> session import, canonicalFolderPath, and hadActiveWorkspace.

Co-authored-by: Okan YILDIRIM <63511519+ragokan@users.noreply.github.com>
2026-11-17 14:30:27 +01:00
Mohamed BoudraandOkan YILDIRIM ce637139e0 fix(archive): key a saved HEAD by the folder's real path
Archive and recovery key the saved HEAD by the recorded worktree root,
which is already a real path. Worktree placement checked the path as
written, so with a symlink in the Paseo home or worktrees root a new
worktree missed the saved HEAD and took the archived folder's path.

archived-head.ts now resolves symlinks itself when it builds the key,
through the nearest existing ancestor when the folder is gone, so every
spelling of one folder reaches the same ref.

Co-authored-by: Okan YILDIRIM <63511519+ragokan@users.noreply.github.com>
2026-11-17 13:53:56 +01:00
Mohamed BoudraandOkan YILDIRIM de77c82889 fix(archive): keep an archived worktree's path and base through restore
A new worktree whose slug matched an archived one took its path once the
folder was gone. Archiving the new worktree then replaced the first
one's saved HEAD, so its detached commits lost their ref and restoring
it came back on the second worktree's checkout. The default path picker
now treats a path with a saved HEAD as taken.

Restoring a saved HEAD for a record with no base branch recorded the
restored commit as the base, so the worktree showed no changes against
it. It now uses the repository default, as a branchless restore does.

Co-authored-by: Okan YILDIRIM <63511519+ragokan@users.noreply.github.com>
2026-11-17 13:34:22 +01:00
Mohamed BoudraandOkan YILDIRIM 65cbef6204 fix(archive): keep every worktree's HEAD through archive and restore it as it was
Archive saved a commit only for a detached HEAD, keyed by workspace ID.
That split Paseo into HEAD kinds, keyed the ref to something two
workspaces can share, and restore still came back on a new restored/<id>
branch instead of the detached HEAD the worktree had.

Archive now saves the HEAD of every worktree folder it removes as
refs/paseo/archived/<sha256 of the folder path>/<git's name for HEAD>,
the name being `git rev-parse --abbrev-ref HEAD`. Restore checks out
that name when it still resolves to the saved commit, and the commit
otherwise. Git decides whether that puts HEAD on a branch or detaches
it; restore never creates, moves, or deletes a branch. The restore
screen no longer names a branch when a saved HEAD exists.

The saved HEAD is deleted on every unarchive. A failed delete is logged
and does not block the unarchive; the next archive of an active
workspace whose folder is already gone drops the leftover ref, so it is
never read as current.

ragokan found the lost detached commits in #9850.

Closes #9856

Co-authored-by: Okan YILDIRIM <63511519+ragokan@users.noreply.github.com>
2026-11-17 13:09:35 +01:00
Mohamed Boudra fe670b6fb5 fix(archive): stop keeping a detached HEAD's commit on every unarchive
Archive keeps a detached HEAD's commit before removing the folder. When the
removal failed, the folder stayed, and Undo, Restore or reopening the
directory unarchived the workspace without deleting the ref. A later archive
with the folder gone kept the old ref, and a restore came back at that
stale commit instead of the workspace's branch.

The ref is now deleted in ensureWorkspaceRecordUnarchived, which every
unarchive passes through, so a kept commit exists only while its workspace
is archived. A repository root that is gone or no longer a git repository
has no ref to delete and does not block the unarchive.
2026-11-17 11:52:07 +01:00
Mohamed BoudraandOkan YILDIRIM a36aca247a fix(archive): keep a detached HEAD's commit through archive and restore it
Archiving a worktree on a detached HEAD removed its folder, and nothing
pointed at the commits that only HEAD held. Undo or Restore came back on
the record's branch or a branch cut from the base, without those commits,
and git's cleanup later deleted them.

Before archive removes the folder of a worktree on a detached HEAD, it now
records HEAD as refs/paseo/archived/<workspaceId>. The ref keeps the commit
alive while the workspace stays archived. Undo and Restore read it before
the record's branch, which can still name the branch HEAD left, create a
new restored/<id> branch at that commit, and then delete the ref. A
worktree on a branch archives and restores as before. If the commit cannot
be recorded, the folder stays in place.

ragokan found the lost detached commits in #9850.

Closes #9856

Co-authored-by: Okan YILDIRIM <63511519+ragokan@users.noreply.github.com>
2026-11-17 11:15:55 +01:00
26 changed files with 851 additions and 146 deletions
+16
View File
@@ -281,6 +281,22 @@ 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,3 +1,6 @@
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";
@@ -238,6 +241,38 @@ 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,10 +389,7 @@ test.describe("Worktree restore", () => {
await page.getByTestId(`agent-row-${getServerId()}-${agent.id}`).click();
await expect(page.getByText("Workspace archived", { exact: true })).toBeVisible();
await expect(
page.getByText(
"Restore Sample workspace to return to its agents. A new branch will start from the saved base or the repository default.",
{ exact: true },
),
page.getByText("Restore Sample workspace to return to its agents.", { exact: true }),
).toBeVisible();
await captureBranchlessRestoreStep(page, "01-restore-workspace.png");
@@ -419,7 +416,7 @@ test.describe("Worktree restore", () => {
cwd: backingWorktree.workspaceDirectory,
encoding: "utf8",
}).trim(),
).toMatch(/^restored\//);
).toBe("");
});
test("restore failure stays visible and permits a successful retry", async ({ page }) => {
@@ -97,15 +97,18 @@ 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.getByTestId("import-session-list").evaluate((list, advance) => {
list.scrollTop = advance ? list.scrollTop + list.clientHeight * 0.8 : 0;
list.dispatchEvent(new Event("scroll"));
}, forward);
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);
}
async search(query: string) {
await this.page.getByTestId("import-session-search").fill(query);
@@ -117,18 +120,11 @@ 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() {
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.page.getByTestId("import-session-load-more").click();
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,11 +17,6 @@ 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,44 +1172,6 @@ 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 { useMutation, useQueries, useQueryClient, type QueryClient } from "@tanstack/react-query";
import { keepPreviousData, useMutation, useQueries, useQueryClient } from "@tanstack/react-query";
import { useTranslation } from "react-i18next";
import type {
DaemonClient,
@@ -40,7 +40,6 @@ import {
resolveDirectoryLabel,
nextPageLimit,
PER_PROVIDER_LIMIT,
previousPageLimit,
type ProviderErrorRow,
resolveImportTarget,
resolveProvidersToFetch,
@@ -101,12 +100,11 @@ 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: () => RecentSessionsResponse | undefined;
placeholderData: typeof keepPreviousData;
queryFn: () => Promise<RecentSessionsResponse>;
}
function buildSessionsQueriesConfig(args: {
queryClient: QueryClient;
providersToFetch: AgentProvider[] | null;
visible: boolean;
client: RecentProviderSessionsClient | null;
@@ -115,24 +113,14 @@ function buildSessionsQueriesConfig(args: {
limit: number;
hostDisconnectedMessage?: string;
}): SessionsQueryConfig[] {
const { queryClient, providersToFetch, visible, client, cwd, query, limit } = args;
const { hostDisconnectedMessage } = args;
const { providersToFetch, visible, client, cwd, query, limit, 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,
// 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 }),
),
placeholderData: keepPreviousData,
queryFn: async () => {
if (!client) {
throw new Error(hostDisconnectedMessage ?? i18n.t("workspace.terminal.hostDisconnected"));
@@ -534,7 +522,6 @@ export function ImportSessionSheet({
const queriesConfig = useMemo(
() =>
buildSessionsQueriesConfig({
queryClient,
providersToFetch,
visible,
client,
@@ -543,7 +530,7 @@ export function ImportSessionSheet({
limit: pageLimit,
hostDisconnectedMessage: t("workspace.terminal.hostDisconnected"),
}),
[queryClient, providersToFetch, visible, client, scopeCwd, query, pageLimit, t],
[providersToFetch, visible, client, scopeCwd, query, pageLimit, t],
);
const queries = useQueries({ queries: queriesConfig });
+1 -2
View File
@@ -484,8 +484,7 @@ export const ar: TranslationResources = {
archivedTitle: "مساحة العمل مؤرشفة",
restoreDescription:
"استعد {{workspaceName}} للعودة إلى وكلائها. ستستخدم شجرة العمل الفرع {{branch}}.",
restoreWithoutBranchDescription:
"استعد {{workspaceName}} للعودة إلى وكلائها. سيبدأ فرع جديد من الفرع الأساسي المحفوظ أو الفرع الافتراضي للمستودع.",
restoreWithoutBranchDescription: "استعد {{workspaceName}} للعودة إلى وكلائها.",
unarchiveDescription: "{{workspaceName}} مؤرشفة. ألغِ أرشفتها لفتحها مجددًا.",
restoreAction: "استعادة",
unarchiveAction: "إلغاء الأرشفة",
+1 -2
View File
@@ -483,8 +483,7 @@ export const en = {
archivedTitle: "Workspace archived",
restoreDescription:
"Restore {{workspaceName}} to return to its agents. Its worktree will use branch {{branch}}.",
restoreWithoutBranchDescription:
"Restore {{workspaceName}} to return to its agents. A new branch will start from the saved base or the repository default.",
restoreWithoutBranchDescription: "Restore {{workspaceName}} to return to its agents.",
unarchiveDescription: "{{workspaceName}} is archived. Unarchive it to open it again.",
restoreAction: "Restore",
unarchiveAction: "Unarchive",
+1 -2
View File
@@ -489,8 +489,7 @@ export const es: TranslationResources = {
archivedTitle: "Espacio de trabajo archivado",
restoreDescription:
"Restaura {{workspaceName}} para volver a sus agentes. Su worktree usará la rama {{branch}}.",
restoreWithoutBranchDescription:
"Restaura {{workspaceName}} para volver a sus agentes. Se creará una rama nueva desde la base guardada o la rama predeterminada del repositorio.",
restoreWithoutBranchDescription: "Restaura {{workspaceName}} para volver a sus agentes.",
unarchiveDescription:
"{{workspaceName}} está archivado. Desarchívalo para volver a abrirlo.",
restoreAction: "Restaurar",
+1 -2
View File
@@ -489,8 +489,7 @@ export const fr: TranslationResources = {
archivedTitle: "Espace de travail archivé",
restoreDescription:
"Restaurez {{workspaceName}} pour retrouver ses agents. Son worktree utilisera la branche {{branch}}.",
restoreWithoutBranchDescription:
"Restaurez {{workspaceName}} pour retrouver ses agents. Une nouvelle branche partira de la base enregistrée ou de la branche par défaut du dépôt.",
restoreWithoutBranchDescription: "Restaurez {{workspaceName}} pour retrouver ses agents.",
unarchiveDescription: "{{workspaceName}} est archivé. Désarchivez-le pour le rouvrir.",
restoreAction: "Restaurer",
unarchiveAction: "Désarchiver",
+1 -2
View File
@@ -489,8 +489,7 @@ export const ja: TranslationResources = {
archivedTitle: "ワークスペースはアーカイブ済みです",
restoreDescription:
"{{workspaceName}} を復元してエージェントに戻ります。worktree ではブランチ {{branch}} を使用します。",
restoreWithoutBranchDescription:
"{{workspaceName}} を復元してエージェントに戻ります。保存されたベース、またはリポジトリのデフォルトブランチから新しいブランチを作成します。",
restoreWithoutBranchDescription: "{{workspaceName}} を復元してエージェントに戻ります。",
unarchiveDescription:
"{{workspaceName}} はアーカイブされています。再度開くにはアーカイブを解除してください。",
restoreAction: "復元",
+1 -2
View File
@@ -485,8 +485,7 @@ export const ko: TranslationResources = {
archivedTitle: "워크스페이스가 보관되었습니다",
restoreDescription:
"{{workspaceName}}를 복원하여 에이전트로 돌아갑니다. 워크트리는 {{branch}} 브랜치를 사용합니다.",
restoreWithoutBranchDescription:
"{{workspaceName}}를 복원하여 에이전트로 돌아갑니다. 저장된 기반 브랜치 또는 저장소 기본 브랜치에서 새 브랜치를 만듭니다.",
restoreWithoutBranchDescription: "{{workspaceName}}를 복원하여 에이전트로 돌아갑니다.",
unarchiveDescription: "{{workspaceName}}가 보관되었습니다. 다시 열려면 보관을 취소하세요.",
restoreAction: "복원",
unarchiveAction: "보관 취소",
+1 -2
View File
@@ -488,8 +488,7 @@ export const ptBR: TranslationResources = {
archivedTitle: "Workspace arquivado",
restoreDescription:
"Restaure {{workspaceName}} para voltar aos seus agentes. A worktree usará a branch {{branch}}.",
restoreWithoutBranchDescription:
"Restaure {{workspaceName}} para voltar aos seus agentes. Uma nova branch partirá da base salva ou da branch padrão do repositório.",
restoreWithoutBranchDescription: "Restaure {{workspaceName}} para voltar aos seus agentes.",
unarchiveDescription:
"{{workspaceName}} está arquivado. Desarquive-o para abri-lo novamente.",
restoreAction: "Restaurar",
+1 -1
View File
@@ -489,7 +489,7 @@ export const ru: TranslationResources = {
restoreDescription:
"Восстановите «{{workspaceName}}», чтобы вернуться к его агентам. Worktree будет использовать ветку {{branch}}.",
restoreWithoutBranchDescription:
"Восстановите «{{workspaceName}}», чтобы вернуться к его агентам. Новая ветка будет создана от сохранённой базовой или ветки репозитория по умолчанию.",
"Восстановите «{{workspaceName}}», чтобы вернуться к его агентам.",
unarchiveDescription:
"Рабочее пространство «{{workspaceName}}» находится в архиве. Разархивируйте его, чтобы снова открыть.",
restoreAction: "Восстановить",
+1 -2
View File
@@ -484,8 +484,7 @@ 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" }
{ kind: "restore" | "restore-from-base" | "restore-archived-head" }
>;
export interface ResolveWorktreeCreationIntentInput {
@@ -1,6 +1,7 @@
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 { mkdirSync, mkdtempSync, rmSync, statSync, symlinkSync, writeFileSync } from "node:fs";
import { afterEach, beforeEach, expect, test } from "vitest";
@@ -25,6 +26,7 @@ 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,
@@ -586,6 +588,106 @@ 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,6 +23,7 @@ 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;
@@ -434,6 +435,21 @@ 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,
@@ -461,6 +477,7 @@ export function createWorkspaceProvisioningService(deps: {
updatedAt: timestamp,
};
}
await releaseSavedHead(workspace, project);
if (project.archivedAt || workspace.archivedAt) {
const projectCheckout =
checkout && areEquivalentPaths(project.rootPath, workspace.cwd)
@@ -0,0 +1,110 @@
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 } });
});
@@ -0,0 +1,122 @@
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,6 +29,7 @@ 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";
@@ -396,6 +397,64 @@ 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,6 +17,7 @@ import {
type PersistedProjectRecord,
type PersistedWorkspaceRecord,
} from "../../workspace-registry.js";
import { readArchivedHead, type ArchivedHead } from "./archived-head.js";
export type WorkspaceRecoveryAction = "unarchive" | "restore";
@@ -57,8 +58,16 @@ 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: {
@@ -124,7 +133,33 @@ export function createWorkspaceRecoveryService(deps: {
};
}
return createRecoveryPlan({ action: "restore", workspace, sourceRepoRoot });
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 };
}
async function inspect(workspaceId: string): Promise<WorkspaceRecoveryState> {
@@ -141,23 +176,17 @@ export function createWorkspaceRecoveryService(deps: {
}
if (resolved.kind === "restore") {
await recreateArchivedWorktree(resolved.workspace, resolved.sourceRepoRoot);
await recreateArchivedWorktree(resolved);
}
await deps.unarchiveWorkspace(resolved.workspace);
return { workspaceId, action: resolved.kind };
}
async function recreateArchivedWorktree(
workspace: PersistedWorkspaceRecord,
sourceRepoRoot: string,
plan: Extract<RecoveryPlan, { kind: "restore" }>,
): Promise<void> {
const source: WorktreeSource = workspace.branch
? { kind: "restore", branchName: workspace.branch, baseRef: workspace.baseBranch }
: {
kind: "restore-from-base",
branchName: `restored/${randomUUID().slice(0, 8)}`,
baseRef: await resolveRecoveryBase(sourceRepoRoot, workspace.baseBranch),
};
const { workspace, sourceRepoRoot, previousWorktree } = plan;
const source = await resolveRecoverySource(plan);
try {
await runGitCommand(["worktree", "prune"], { cwd: sourceRepoRoot, timeout: 30_000 });
@@ -165,31 +194,16 @@ 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(previousWorktreePath),
worktreeSlug: basename(previousWorktree.path),
source,
paseoHome: deps.paseoHome,
worktreesRoot: deps.worktreesRoot,
...(hasRecordedWorktreePath ? { worktreePath: previousWorktreePath } : {}),
...(previousWorktree.isRecorded ? { worktreePath: previousWorktree.path } : {}),
});
recreatedWorktreePath = result.worktreePath;
} catch (error) {
@@ -198,7 +212,7 @@ export function createWorkspaceRecoveryService(deps: {
try {
const recreatedWorkspacePath = mapWorkspaceCwdToWorktree({
sourceWorktreePath: previousWorktreePath,
sourceWorktreePath: previousWorktree.path,
workspaceCwd: workspace.cwd,
targetWorktreePath: recreatedWorktreePath,
});
@@ -231,6 +245,27 @@ 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 {
@@ -254,7 +289,7 @@ async function resolveRecoveryBase(repoRoot: string, recordedBase: string | null
function createRecoveryPlan(
input:
| { action: "unarchive"; workspace: PersistedWorkspaceRecord }
| { action: "restore"; workspace: PersistedWorkspaceRecord; sourceRepoRoot: string },
| (Omit<Extract<RecoveryPlan, { kind: "restore" }>, "kind" | "state"> & { action: "restore" }),
): RecoveryPlan {
const state = {
kind: "recoverable" as const,
@@ -263,11 +298,13 @@ function createRecoveryPlan(
branch: input.workspace.branch,
};
if (input.action === "restore") {
const { action, ...plan } = input;
return {
kind: input.action,
state: { ...state, action: input.action },
workspace: input.workspace,
sourceRepoRoot: input.sourceRepoRoot,
...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 },
};
}
return {
@@ -21,6 +21,7 @@ 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,
@@ -446,6 +447,20 @@ 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,6 +35,10 @@ 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-"));
@@ -151,6 +155,234 @@ 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 () => {
+41 -10
View File
@@ -189,6 +189,8 @@ 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;
@@ -1463,6 +1465,24 @@ 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" }>,
@@ -1472,18 +1492,12 @@ 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,
metadataBaseRefName: normalizeRequiredBaseBranch(source.baseRef ?? source.branchName),
...(exactBase ? { metadataBaseRef: exactBase } : {}),
...(await resolveRestoredBaseMetadata(cwd, {
baseRef: source.baseRef,
fallback: source.branchName,
})),
changeRequestLookupTarget: createPaseoWorktreeChangeRequestHint({
headRef: source.branchName,
localBranchName: source.branchName,
@@ -1507,6 +1521,21 @@ 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" }>,
@@ -1546,6 +1575,8 @@ 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);