Compare commits

..
Author SHA1 Message Date
paseo-bot[bot] b0e8724383 fix(opencode): keep history loads read-only and save the new session id at once
Only an interactive resume replaces a lost OpenCode session, so opening an
archived agent's history no longer creates a native session. A replaced
session reports persistenceUpdatedOnResume, so the agent manager stores
the new id when it registers the session, not after the next prompt.
2026-11-17 07:32:24 +00:00
paseo-bot[bot] b4ae32d77e fix(opencode): continue in a new session when the saved one is gone
Resuming an OpenCode agent reused the saved session id without checking
that OpenCode still had it. When the session was gone, every prompt failed
with NotFoundError "Session not found" and the agent never recovered.

Resume now asks OpenCode for the session first. When OpenCode reports it
missing, the agent starts a new native session on the same server, so the
next prompt runs and the new session id is persisted.
2026-11-17 07:20:32 +00:00
31 changed files with 294 additions and 1023 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
@@ -466,12 +466,12 @@ test("downloads a file over direct TCP with its original filename and bytes", as
await gotoWorkspace(page, workspace.workspaceId);
await openFileExplorer(page);
const daemonRequest = page.waitForRequest("**/api/files/download?*");
const downloaded = await downloadFileFromExplorer(page, fileName);
const requestUrl = new URL((await daemonRequest).url());
expect(requestUrl.port).toBe(getE2EDaemonPort());
expect(requestUrl.searchParams.get("token")).toBeTruthy();
expect(new URL(downloaded.url()).protocol).toBe("blob:");
const url = new URL(downloaded.url());
expect(url.protocol).toBe("http:");
expect(url.port).toBe(getE2EDaemonPort());
expect(url.pathname).toBe("/api/files/download");
expect(url.searchParams.get("token")).toBeTruthy();
expect(downloaded.suggestedFilename()).toBe(fileName);
const savedFile = testInfo.outputPath(fileName);
await downloaded.saveAs(savedFile);
@@ -479,45 +479,6 @@ test("downloads a file over direct TCP with its original filename and bytes", as
expect(await readFile(savedFile)).toEqual(source);
});
test("keeps the app open and shows the error when the host rejects a download", async ({
page,
}, testInfo) => {
const fileName = "removed-during-download.bin";
const filePath = path.join(workspace.workspaceDirectory, fileName);
const source = Buffer.from([0, 1, 2, 255]);
await writeFile(filePath, source);
await gotoWorkspace(page, workspace.workspaceId);
await openFileExplorer(page);
const workspaceUrl = page.url();
// The file disappears after the token is issued, so the real daemon answers 404.
await page.route(
"**/api/files/download?*",
async (route) => {
await rm(filePath);
await route.continue();
},
{ times: 1 },
);
await page
.getByTestId("file-explorer-tree-scroll")
.getByText(fileName, { exact: true })
.click({ button: "right" });
await page.getByRole("menuitem", { name: "Download", exact: true }).click();
await expect(
page.getByText("Failed to download file (HTTP 404).", { exact: true }),
).toBeVisible();
expect(page.url()).toBe(workspaceUrl);
await writeFile(filePath, source);
const downloaded = await downloadFileFromExplorer(page, fileName);
const savedFile = testInfo.outputPath(fileName);
await downloaded.saveAs(savedFile);
expect(await readFile(savedFile)).toEqual(source);
expect(page.url()).toBe(workspaceUrl);
});
test("downloads an unsupported binary from its preview with original filename and bytes", async ({
page,
}, testInfo) => {
@@ -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 }) => {
+2 -2
View File
@@ -484,7 +484,8 @@ export const ar: TranslationResources = {
archivedTitle: "مساحة العمل مؤرشفة",
restoreDescription:
"استعد {{workspaceName}} للعودة إلى وكلائها. ستستخدم شجرة العمل الفرع {{branch}}.",
restoreWithoutBranchDescription: "استعد {{workspaceName}} للعودة إلى وكلائها.",
restoreWithoutBranchDescription:
"استعد {{workspaceName}} للعودة إلى وكلائها. سيبدأ فرع جديد من الفرع الأساسي المحفوظ أو الفرع الافتراضي للمستودع.",
unarchiveDescription: "{{workspaceName}} مؤرشفة. ألغِ أرشفتها لفتحها مجددًا.",
restoreAction: "استعادة",
unarchiveAction: "إلغاء الأرشفة",
@@ -2016,7 +2017,6 @@ export const ar: TranslationResources = {
hostUnavailable: "مضيف التنزيل غير متاح.",
cancelled: "تم إلغاء التنزيل.",
failed: "فشل تنزيل الملف.",
httpFailed: "فشل تنزيل الملف (HTTP {{status}}).",
shareFile: "مشاركة الملف",
shareFileNamed: "مشاركة{{fileName}}",
},
+2 -2
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",
@@ -2044,7 +2045,6 @@ export const en = {
hostUnavailable: "Download host is unavailable.",
cancelled: "Download was cancelled.",
failed: "Failed to download file.",
httpFailed: "Failed to download file (HTTP {{status}}).",
shareFile: "Share file",
shareFileNamed: "Share {{fileName}}",
},
+2 -2
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",
@@ -2065,7 +2066,6 @@ export const es: TranslationResources = {
hostUnavailable: "El host de descarga no está disponible.",
cancelled: "La descarga fue cancelada.",
failed: "No se pudo descargar el archivo.",
httpFailed: "No se pudo descargar el archivo (HTTP {{status}}).",
shareFile: "compartir archivo",
shareFileNamed: "Compartir{{fileName}}",
},
+2 -2
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",
@@ -2064,7 +2065,6 @@ export const fr: TranslationResources = {
hostUnavailable: "L’hôte de téléchargement est indisponible.",
cancelled: "Téléchargement annulé.",
failed: "Impossible de télécharger le fichier.",
httpFailed: "Impossible de télécharger le fichier (HTTP {{status}}).",
shareFile: "Partager le fichier",
shareFileNamed: "Partager {{fileName}}",
},
+2 -2
View File
@@ -489,7 +489,8 @@ export const ja: TranslationResources = {
archivedTitle: "ワークスペースはアーカイブ済みです",
restoreDescription:
"{{workspaceName}} を復元してエージェントに戻ります。worktree ではブランチ {{branch}} を使用します。",
restoreWithoutBranchDescription: "{{workspaceName}} を復元してエージェントに戻ります。",
restoreWithoutBranchDescription:
"{{workspaceName}} を復元してエージェントに戻ります。保存されたベース、またはリポジトリのデフォルトブランチから新しいブランチを作成します。",
unarchiveDescription:
"{{workspaceName}} はアーカイブされています。再度開くにはアーカイブを解除してください。",
restoreAction: "復元",
@@ -2037,7 +2038,6 @@ export const ja: TranslationResources = {
hostUnavailable: "ダウンロードホストが利用できません。",
cancelled: "ダウンロードがキャンセルされました。",
failed: "ファイルのダウンロードに失敗しました。",
httpFailed: "ファイルのダウンロードに失敗しました (HTTP {{status}}).",
shareFile: "ファイルを共有",
shareFileNamed: "{{fileName}}を共有",
},
+2 -2
View File
@@ -485,7 +485,8 @@ export const ko: TranslationResources = {
archivedTitle: "워크스페이스가 보관되었습니다",
restoreDescription:
"{{workspaceName}}를 복원하여 에이전트로 돌아갑니다. 워크트리는 {{branch}} 브랜치를 사용합니다.",
restoreWithoutBranchDescription: "{{workspaceName}}를 복원하여 에이전트로 돌아갑니다.",
restoreWithoutBranchDescription:
"{{workspaceName}}를 복원하여 에이전트로 돌아갑니다. 저장된 기반 브랜치 또는 저장소 기본 브랜치에서 새 브랜치를 만듭니다.",
unarchiveDescription: "{{workspaceName}}가 보관되었습니다. 다시 열려면 보관을 취소하세요.",
restoreAction: "복원",
unarchiveAction: "보관 취소",
@@ -2027,7 +2028,6 @@ export const ko: TranslationResources = {
hostUnavailable: "다운로드 호스트를 사용할 수 없습니다.",
cancelled: "다운로드가 취소되었습니다.",
failed: "파일을 다운로드하지 못했습니다.",
httpFailed: "파일을 다운로드하지 못했습니다 (HTTP {{status}}).",
shareFile: "파일 공유",
shareFileNamed: "{{fileName}} 공유",
},
+2 -2
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",
@@ -2050,7 +2051,6 @@ export const ptBR: TranslationResources = {
hostUnavailable: "Host de download indisponível.",
cancelled: "Download cancelado.",
failed: "Falha ao baixar arquivo.",
httpFailed: "Falha ao baixar arquivo (HTTP {{status}}).",
shareFile: "Compartilhar arquivo",
shareFileNamed: "Compartilhar {{fileName}}",
},
+1 -2
View File
@@ -489,7 +489,7 @@ export const ru: TranslationResources = {
restoreDescription:
"Восстановите «{{workspaceName}}», чтобы вернуться к его агентам. Worktree будет использовать ветку {{branch}}.",
restoreWithoutBranchDescription:
"Восстановите «{{workspaceName}}», чтобы вернуться к его агентам.",
"Восстановите «{{workspaceName}}», чтобы вернуться к его агентам. Новая ветка будет создана от сохранённой базовой или ветки репозитория по умолчанию.",
unarchiveDescription:
"Рабочее пространство «{{workspaceName}}» находится в архиве. Разархивируйте его, чтобы снова открыть.",
restoreAction: "Восстановить",
@@ -2051,7 +2051,6 @@ export const ru: TranslationResources = {
hostUnavailable: "Хост загрузки недоступен.",
cancelled: "Загрузка отменена.",
failed: "Не удалось загрузить файл.",
httpFailed: "Не удалось загрузить файл (HTTP {{status}}).",
shareFile: "Поделиться файлом",
shareFileNamed: "Поделиться {{fileName}}",
},
+2 -2
View File
@@ -484,7 +484,8 @@ export const zhCN: TranslationResources = {
archivedTitle: "Workspace 已归档",
restoreDescription:
"恢复 {{workspaceName}} 以返回其中的代理。worktree 将使用分支 {{branch}}。",
restoreWithoutBranchDescription: "恢复 {{workspaceName}} 以返回其中的代理。",
restoreWithoutBranchDescription:
"恢复 {{workspaceName}} 以返回其中的代理。新分支将从保存的基准分支或仓库默认分支创建。",
unarchiveDescription: "{{workspaceName}} 已归档。取消归档以重新打开。",
restoreAction: "恢复",
unarchiveAction: "取消归档",
@@ -1993,7 +1994,6 @@ export const zhCN: TranslationResources = {
hostUnavailable: "下载 Host 不可用。",
cancelled: "下载已取消。",
failed: "下载文件失败。",
httpFailed: "下载文件失败 (HTTP {{status}}).",
shareFile: "共享文件",
shareFileNamed: "共享 {{fileName}}",
},
@@ -90,7 +90,6 @@ interface StartInput {
token?: ReturnType<typeof createTokenRequest>;
reader?: ReturnType<typeof createFileReader>;
saver?: ReturnType<typeof createFileSaver>;
fetchFile?: typeof fetch;
}
async function startDownload(input: StartInput): Promise<Download | undefined> {
@@ -109,7 +108,6 @@ async function startDownload(input: StartInput): Promise<Download | undefined> {
requestFileDownloadToken: token.request,
readFile: reader.read,
saveFile: saver.save,
fetchFile: input.fetchFile ?? (async () => new Response(FILE_BYTES)),
});
const { activeDownloadId, downloads } = useDownloadStore.getState();
return activeDownloadId ? downloads.get(activeDownloadId) : undefined;
@@ -205,57 +203,6 @@ describe("download store transport selection", () => {
expect(saver.savedFiles).toEqual([]);
});
it("fails with the HTTP status when a proxy in front of the host rejects the download", async () => {
const requests: Array<RequestInit | undefined> = [];
const download = await startDownload({
profile: profileWith([localTcpConnection]),
activeConnectionId: localTcpConnection.id,
fetchFile: async (_url, init) => {
requests.push(init);
return new Response("<h1>401 Authorization Required</h1>", {
status: 401,
headers: { "WWW-Authenticate": 'Basic realm="Paseo"' },
});
},
});
expect(download).toMatchObject({
status: "error",
message: i18n.t("downloads.httpFailed", { status: 401 }),
});
expect(requests).toEqual([{ credentials: "include", redirect: "error" }]);
});
it("fails with a readable message when the download request cannot reach the host", async () => {
const download = await startDownload({
profile: profileWith([localTcpConnection]),
activeConnectionId: localTcpConnection.id,
fetchFile: async () => {
throw new TypeError("Failed to fetch");
},
});
expect(download).toMatchObject({ status: "error", message: i18n.t("downloads.failed") });
});
it("fails with a readable message when the connection drops while the file is downloading", async () => {
const saver = createFileSaver();
const download = await startDownload({
profile: profileWith([localTcpConnection]),
activeConnectionId: localTcpConnection.id,
fetchFile: async () =>
new Response(
new ReadableStream({
start: (controller) => controller.error(new TypeError("network error")),
}),
),
saver,
});
expect(download).toMatchObject({ status: "error", message: i18n.t("downloads.failed") });
expect(saver.savedFiles).toEqual([]);
});
it("fails the download and saves nothing when the session read fails", async () => {
const reader = createFileReader(async () => {
throw new Error("Connection lost");
+34 -39
View File
@@ -4,6 +4,7 @@ import * as LegacyFileSystem from "expo-file-system/legacy";
import * as Sharing from "expo-sharing";
import type { HostProfile } from "@/types/host-connection";
import { buildDaemonWebSocketUrl } from "@/utils/daemon-endpoints";
import { openExternalUrl } from "@/utils/open-external-url";
import { isWeb } from "@/constants/platform";
import { i18n } from "@/i18n/i18next";
@@ -58,7 +59,6 @@ interface DownloadState {
/** Reads the whole file over the session socket; used when no direct HTTP endpoint is active. */
readFile: (path: string, maxBytes: number) => Promise<{ bytes: Uint8Array; size: number }>;
saveFile?: typeof saveDownloadedBytes;
fetchFile?: typeof fetch;
}) => Promise<void>;
updateProgress: (id: string, progress: DownloadProgress) => void;
@@ -86,7 +86,6 @@ export const useDownloadStore = create<DownloadState>()((set, get) => ({
requestFileDownloadToken,
readFile,
saveFile = saveDownloadedBytes,
fetchFile = fetch,
}) => {
const id = generateDownloadId();
const download: Download = {
@@ -145,11 +144,14 @@ export const useDownloadStore = create<DownloadState>()((set, get) => ({
throw new Error(i18n.t("downloads.hostUnavailable"));
}
const downloadUrl = buildDownloadUrl(downloadTarget.baseUrl, tokenResponse.token);
const downloadUrl = buildDownloadUrl(
downloadTarget.baseUrl,
tokenResponse.token,
isWeb ? downloadTarget.authCredentials : null,
);
if (isWeb) {
const file = await fetchDownload(fetchFile, downloadUrl);
saveBrowserFile(file, resolvedFileName);
triggerBrowserDownload(downloadUrl, resolvedFileName);
get().completeDownload(id);
return;
}
@@ -196,6 +198,11 @@ export const useDownloadStore = create<DownloadState>()((set, get) => ({
await shareSavedFile(result.uri, tokenResponse.mimeType, resolvedFileName);
} catch (error) {
const message = error instanceof Error ? error.message : i18n.t("downloads.failed");
if (isWeb) {
console.warn("[DownloadStore] Download failed:", message);
get().failDownload(id, message);
return;
}
get().failDownload(id, message);
}
},
@@ -276,6 +283,7 @@ function findMostRecentDownloadId(downloads: Map<string, Download>): string | nu
interface DownloadTarget {
baseUrl: string | null;
authHeader: string | null;
authCredentials: { username: string; password: string } | null;
}
/**
@@ -298,7 +306,7 @@ function resolveDaemonDownloadTarget(
buildDaemonWebSocketUrl(connection.endpoint, { useTls: connection.useTls ?? false }),
);
} catch {
return { baseUrl: null, authHeader: null };
return { baseUrl: null, authHeader: null, authCredentials: null };
}
if (parsed.protocol === "ws:") {
@@ -324,41 +332,23 @@ function resolveDaemonDownloadTarget(
? `Basic ${btoa(`${authCredentials.username}:${authCredentials.password}`)}`
: null;
return { baseUrl, authHeader };
return { baseUrl, authHeader, authCredentials };
}
function buildDownloadUrl(baseUrl: string, token: string): string {
function buildDownloadUrl(
baseUrl: string,
token: string,
authCredentials: { username: string; password: string } | null,
): string {
const url = new URL("/api/files/download", baseUrl);
url.searchParams.set("token", token);
if (authCredentials) {
url.username = authCredentials.username;
url.password = authCredentials.password;
}
return url.toString();
}
/**
* Fetches the file instead of navigating to it. The app runs on another origin than the host
* (paseo://app on desktop), so a link to the download URL navigates the whole window, and any
* response that is not the file (a proxy's 401 page, a 404) replaces the app.
*/
async function fetchDownload(fetchFile: typeof fetch, url: string): Promise<Blob> {
let response: Response;
try {
// Send the same cookies the host's WebSocket handshake sends, so a proxy in front of the
// host lets the download through. Refuse redirects: a proxy that redirects to a login page
// would otherwise be saved as the file.
response = await fetchFile(url, { credentials: "include", redirect: "error" });
} catch {
throw new Error(i18n.t("downloads.failed"));
}
if (!response.ok) {
throw new Error(i18n.t("downloads.httpFailed", { status: response.status }));
}
try {
// The body streams after the headers, so the connection can still drop here.
return await response.blob();
} catch {
throw new Error(i18n.t("downloads.failed"));
}
}
/**
* Saves bytes read over the session. Web and Electron hand them to the browser's download
* manager and return `null`; native writes the file and returns its URI for the share sheet.
@@ -371,7 +361,12 @@ async function saveDownloadedBytes({
if (isWeb) {
const buffer = new ArrayBuffer(bytes.byteLength);
new Uint8Array(buffer).set(bytes);
saveBrowserFile(new Blob([buffer], { type: mimeType ?? "application/octet-stream" }), fileName);
const url = URL.createObjectURL(
new Blob([buffer], { type: mimeType ?? "application/octet-stream" }),
);
triggerBrowserDownload(url, fileName);
// The browser may still be reading the blob while its save prompt is open.
setTimeout(() => URL.revokeObjectURL(url), 60_000);
return null;
}
// Resolve and write in one tick so two downloads of the same name cannot pick the same path.
@@ -395,12 +390,14 @@ async function shareSavedFile(
}
}
function saveBrowserFile(file: Blob, fileName: string) {
function triggerBrowserDownload(url: string, fileName: string) {
if (typeof document === "undefined") {
if (typeof window !== "undefined") {
void openExternalUrl(url);
}
return;
}
const url = URL.createObjectURL(file);
const link = document.createElement("a");
link.href = url;
link.download = fileName;
@@ -408,8 +405,6 @@ function saveBrowserFile(file: Blob, fileName: string) {
document.body.appendChild(link);
link.click();
link.remove();
// The browser may still be reading the blob while its save prompt is open.
setTimeout(() => URL.revokeObjectURL(url), 60_000);
}
function resolveDownloadTargetFile(fileName: string): FSFile {
@@ -0,0 +1,59 @@
import { beforeAll, beforeEach, describe, expect, test } from "vitest";
import pino from "pino";
import type { AgentSession, AgentStreamEvent } from "../agent-sdk-types.js";
import {
canRunRealProvider,
createRealProviderClient,
getRealProviderConfig,
} from "../../daemon-e2e/real-provider-test-config.js";
import { streamSession } from "./test-utils/session-stream-adapter.js";
function isTerminalEvent(event: AgentStreamEvent): boolean {
return (
event.type === "turn_completed" ||
event.type === "turn_failed" ||
event.type === "turn_canceled"
);
}
async function runTurn(session: AgentSession, prompt: string): Promise<AgentStreamEvent> {
for await (const event of streamSession(session, prompt)) {
if (isTerminalEvent(event)) return event;
}
throw new Error("turn ended without a terminal event");
}
describe("opencode agent whose native session is gone (real)", () => {
let canRun = false;
beforeAll(async () => {
canRun = await canRunRealProvider("opencode");
});
beforeEach((context) => {
if (!canRun) context.skip();
});
test("a resumed agent whose OpenCode session no longer exists continues in a new session", async () => {
const client = createRealProviderClient("opencode", pino({ level: "silent" }));
const config = { ...getRealProviderConfig("opencode"), cwd: process.cwd() };
// A non-persistent session deletes its native OpenCode session on close, which
// leaves the handle naming a session OpenCode no longer has.
const lost = await client.createSession(config, undefined, { persistSession: false });
const handle = lost.describePersistence();
await lost.close();
expect(handle).not.toBeNull();
const resumed = await client.resumeSession(handle!, config);
try {
const turn = await runTurn(resumed, "Reply with exactly: OK");
expect(turn).toMatchObject({ type: "turn_completed" });
expect(resumed.describePersistence()?.sessionId).not.toBe(handle!.sessionId);
} finally {
await resumed.close().catch(() => undefined);
}
}, 120_000);
});
@@ -814,6 +814,79 @@ describe("OpenCodeAgentClient adapter smoke tests", () => {
}
});
test("resuming an agent whose OpenCode session is gone continues in a new session", async () => {
const runtime = new TestOpenCodeHarness();
const execution = new TestOpenCodeClient();
execution.sessionGetResponse = {
error: { name: "NotFoundError", data: { message: "Session not found: ses_lost" } },
};
execution.sessionCreateResponse = { data: { id: "ses_fresh" } };
execution.sessionPromptAsyncImplementation = async (parameters) => {
const { sessionID } = parameters as { sessionID: string };
if (sessionID === "ses_lost") {
return {
error: { name: "NotFoundError", data: { message: "Session not found: ses_lost" } },
};
}
execution.emitEvent({ type: "session.idle", properties: { sessionID } });
return {};
};
runtime.enqueueClient(execution);
const client = new OpenCodeAgentClient(logger, undefined, {
serverManager: runtime,
createClient: runtime.createClient,
});
const cwd = tmpCwd();
try {
const session = await client.resumeSession({
provider: "opencode",
sessionId: "ses_lost",
metadata: { cwd },
});
try {
const turn = await collectTurnEvents(streamSession(session, "Are you there?"));
expect(turn.turnCompleted).toBe(true);
expect(session.describePersistence()?.sessionId).toBe("ses_fresh");
expect(session.persistenceUpdatedOnResume).toBe(true);
} finally {
await session.close();
}
} finally {
rmSync(cwd, { recursive: true, force: true });
}
});
test("loading history of an agent whose OpenCode session is gone creates no session", async () => {
const runtime = new TestOpenCodeHarness();
const execution = new TestOpenCodeClient();
execution.sessionGetResponse = {
error: { name: "NotFoundError", data: { message: "Session not found: ses_lost" } },
};
runtime.enqueueClient(execution);
const client = new OpenCodeAgentClient(logger, undefined, {
serverManager: runtime,
createClient: runtime.createClient,
});
const cwd = tmpCwd();
try {
const session = await client.resumeSession(
{ provider: "opencode", sessionId: "ses_lost", metadata: { cwd } },
undefined,
undefined,
{ purpose: "history" },
);
try {
expect(execution.calls.sessionCreate).toEqual([]);
expect(session.describePersistence()?.sessionId).toBe("ses_lost");
} finally {
await session.close();
}
} finally {
rmSync(cwd, { recursive: true, force: true });
}
});
test("fetchCatalog returns models with required fields", async () => {
const runtime = new TestOpenCodeHarness();
const openCodeClient = new TestOpenCodeClient();
@@ -546,6 +546,15 @@ function isOpenCodeNotFoundError(error: unknown): boolean {
);
}
async function isOpenCodeSessionMissing(
client: Pick<OpencodeClient, "session">,
sessionId: string,
directory: string,
): Promise<boolean> {
const response = await client.session.get({ sessionID: sessionId, directory });
return isOpenCodeNotFoundError(response.error);
}
async function abortOpenCodeSession(params: {
client: Pick<OpencodeClient, "session">;
sessionId: string;
@@ -1457,8 +1466,18 @@ export class OpenCodeAgentClient implements AgentClient {
options?: AgentCreateSessionOptions,
): Promise<AgentSession> {
const openCodeConfig = this.assertConfig(config);
const connection = await this.connectServer(openCodeConfig, launchContext);
return this.startNewSession(connection, config, openCodeConfig, launchContext, options);
}
private async startNewSession(
connection: OpenCodeServerConnection,
config: AgentSessionConfig,
openCodeConfig: OpenCodeAgentConfig,
launchContext?: AgentLaunchContext,
options?: AgentCreateSessionOptions,
): Promise<OpenCodeAgentSession> {
const connectServer = this.connectServer.bind(this, openCodeConfig, launchContext);
const connection = await connectServer();
const { client } = connection;
// OpenCode stores permission rules on the session, so they are set here and on resume
@@ -1522,7 +1541,7 @@ export class OpenCodeAgentClient implements AgentClient {
handle: AgentPersistenceHandle,
overrides?: Partial<AgentSessionConfig>,
launchContext?: AgentLaunchContext,
_options?: AgentResumeSessionOptions,
options?: AgentResumeSessionOptions,
): Promise<AgentSession> {
const metadata = (handle.metadata ?? {}) as Partial<AgentSessionConfig>;
const cwd = overrides?.cwd ?? metadata.cwd;
@@ -1547,6 +1566,32 @@ export class OpenCodeAgentClient implements AgentClient {
: await connectServer();
const { client } = connection;
// History loads stay read-only, so only an interactive resume replaces a lost session.
let sessionMissing = false;
if ((options?.purpose ?? "interactive") === "interactive") {
try {
sessionMissing = await isOpenCodeSessionMissing(
client,
handle.sessionId,
openCodeConfig.cwd,
);
} catch (error) {
await connection.release();
throw error;
}
}
if (sessionMissing) {
// Every prompt to a session OpenCode no longer has fails, so the agent
// continues in a new native session instead of staying unusable.
this.logger.warn(
{ sessionId: handle.sessionId },
"OpenCode session no longer exists; continuing in a new session",
);
const session = await this.startNewSession(connection, config, openCodeConfig, launchContext);
session.persistenceUpdatedOnResume = true;
return session;
}
try {
await this.applySessionPermissionRules(client, openCodeConfig, handle.sessionId);
await this.populateModelContextWindowCache(client, openCodeConfig.cwd);
@@ -3380,6 +3425,8 @@ interface OpenCodeServerConnection {
}
class OpenCodeAgentSession implements AgentSession {
/** Set when resume replaced a lost native session, so the new handle is saved at once. */
persistenceUpdatedOnResume = false;
readonly provider = "opencode" as const;
readonly capabilities = OPENCODE_CAPABILITIES;
readonly openOptionsPatch: Record<string, unknown>;
+2 -2
View File
@@ -128,7 +128,7 @@ export async function fanOutReconciledWorkspaceUpdates(input: {
);
}
import { VoiceAssistantWebSocketServer, isDaemonOriginAllowed } from "./websocket-server.js";
import { VoiceAssistantWebSocketServer } from "./websocket-server.js";
import { WorkspaceSetupRuntime } from "./workspace-setup-runtime.js";
import { createWorkspaceLabelService } from "./workspace-labels/index.js";
import { createGitHubService } from "../services/github-service.js";
@@ -813,7 +813,7 @@ export async function createPaseoDaemon(
app.use((req, res, next) => {
const origin = req.headers.origin;
if (origin && isDaemonOriginAllowed(origin, req.headers.host ?? null, allowedOrigins)) {
if (origin && (allowedOrigins.has("*") || allowedOrigins.has(origin))) {
res.setHeader("Access-Control-Allow-Origin", origin);
res.setHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS");
res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
@@ -9,7 +9,7 @@ import {
symlinkSync,
} from "fs";
import { once } from "node:events";
import { get, type IncomingMessage } from "node:http";
import { get } from "node:http";
import { tmpdir } from "os";
import path from "path";
import { createDaemonTestContext, type DaemonTestContext } from "../test-utils/index.js";
@@ -69,29 +69,6 @@ describe("daemon E2E", () => {
}, 60000);
describe("file download tokens", () => {
test("lets a page on a loopback alias of the request's host and port fetch a download", async () => {
const cwd = tmpCwd();
writeFileSync(path.join(cwd, "download.bin"), "download bytes");
try {
// The web UI behind a remapped port (for example Docker -p 8080:6767): the page is at
// http://127.0.0.1:8080 and the app sends the request to localhost:8080. The WebSocket
// accepts this origin, so the download must as well.
const token = await ctx.client.requestDownloadToken(cwd, "download.bin");
const request = get({
host: "127.0.0.1",
port: ctx.daemon.port,
path: `/api/files/download?token=${token.token}`,
headers: { Host: "localhost:8080", Origin: "http://127.0.0.1:8080" },
});
const [response] = (await once(request, "response")) as [IncomingMessage];
response.resume();
expect(response.statusCode).toBe(200);
expect(response.headers["access-control-allow-origin"]).toBe("http://127.0.0.1:8080");
} finally {
rmSync(cwd, { recursive: true, force: true });
}
});
test.skipIf(process.platform !== "linux")(
"releases file descriptors after repeated HTTP download cancellations",
async () => {
@@ -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 {
+3 -17
View File
@@ -998,7 +998,9 @@ export class VoiceAssistantWebSocketServer {
callback(false, 403, "Host not allowed");
return;
}
if (!origin || isDaemonOriginAllowed(origin, requestHost, allowedOrigins)) {
const sameOrigin = isWebSocketSameOrigin(origin, requestHost);
if (!origin || allowedOrigins.has("*") || allowedOrigins.has(origin) || sameOrigin) {
callback(true);
} else {
this.incrementRuntimeCounter("originRejected");
@@ -3265,22 +3267,6 @@ function isLoopbackAlias(hostname: string): boolean {
return /^127(?:\.\d{1,3}){3}$/.test(normalized);
}
/**
* Whether a page at `origin` may talk to the daemon reached at `requestHost`. The WebSocket
* upgrade and the HTTP CORS check both use it, so a page that can connect can also fetch.
*/
export function isDaemonOriginAllowed(
origin: string,
requestHost: string | null,
allowedOrigins: Set<string>,
): boolean {
return (
allowedOrigins.has("*") ||
allowedOrigins.has(origin) ||
isWebSocketSameOrigin(origin, requestHost)
);
}
export function isWebSocketSameOrigin(
origin: string | undefined,
requestHost: string | null,
@@ -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);