Compare commits

...
Author SHA1 Message Date
Mohamed Boudra 224ba30fb3 test(workspaces): verify detached checkout after restore
Update the browser journey for detached restore and allow the daemon restart test enough time on Windows runners.
2026-11-17 17:06:27 +01:00
Mohamed Boudra 02d1068aab fix(workspaces): scope saved HEAD to each archive
An archive with no readable checkout must not retain the HEAD saved by an earlier archive.
2026-11-17 16:35:19 +01:00
Mohamed Boudra 5eff161fb8 fix(workspaces): preserve git HEAD identity through restore
Record Git’s full HEAD ref or commit so restore can pass branch and detached checkouts to Git without guessing from a short name.
2026-11-17 16:25:28 +01:00
Mohamed Boudra a0c4865630 fix(workspaces): restore saved checkouts through one git path
Keep existing archive and deletion behavior when Git cannot read a worktree HEAD, and record every readable checkout for a common restore path.
2026-11-17 16:03:01 +01:00
Mohamed BoudraandOkan YILDIRIM e5021f89de fix(workspaces): preserve commits when archiving worktrees
A removed worktree can be the only reference to its HEAD. Keep that commit before deletion and record the checkout so detached workspaces restore at the same commit.

Co-authored-by: Okan YILDIRIM <63511519+ragokan@users.noreply.github.com>
2026-11-17 15:49:37 +01:00
paseo-bot[bot]andClaude Opus 5.5 94f2df6263 Keep the Import Session list in place when Load more fetches the next page (#9974)
Tapping Load more emptied the list until the larger page arrived: the sheet
showed "Loading sessions...", unmounted the virtualized list, and brought it
back scrolled to the top. The sessions queries set keepPreviousData, but
useQueries gives a changed key a new observer with no previous data, so the
placeholder was always empty. The placeholder is now the cached page that
Load more grew from, for the same scope, search, and provider.

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

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 12:00:55 +00:00
paseo-bot[bot]andpanta82 02124454bc Keep failed downloads inside the app on web and desktop (#9937)
On web and desktop, Download over a direct connection now fetches the file and saves it from a blob instead of navigating the window to the host URL. A rejected or unreachable download shows an error in the download toast and the app stays on the workspace. The daemon's HTTP CORS check uses the same origin rule as the WebSocket upgrade.

Closes #9895

Co-authored-by: panta82 <4291324+panta82@users.noreply.github.com>
2026-11-17 08:04:50 +00:00
30 changed files with 662 additions and 114 deletions
@@ -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 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();
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:");
expect(downloaded.suggestedFilename()).toBe(fileName);
const savedFile = testInfo.outputPath(fileName);
await downloaded.saveAs(savedFile);
@@ -479,6 +479,45 @@ 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) => {
@@ -361,6 +361,10 @@ test.describe("Worktree restore", () => {
cwd: backingWorktree.workspaceDirectory,
stdio: "pipe",
});
const originalHead = execFileSync("git", ["rev-parse", "HEAD"], {
cwd: backingWorktree.workspaceDirectory,
encoding: "utf8",
}).trim();
const created = await worktreeClient.createWorkspace({
source: { kind: "directory", path: backingWorktree.workspaceDirectory },
title: "Sample workspace",
@@ -389,10 +393,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");
@@ -409,17 +410,13 @@ test.describe("Worktree restore", () => {
cwd: backingWorktree.workspaceDirectory,
encoding: "utf8",
}).trim();
const defaultHead = execFileSync("git", ["rev-parse", "main"], {
cwd: tempRepo.path,
encoding: "utf8",
}).trim();
expect(restoredHead).toBe(defaultHead);
expect(restoredHead).toBe(originalHead);
expect(
execFileSync("git", ["branch", "--show-current"], {
cwd: backingWorktree.workspaceDirectory,
encoding: "utf8",
}).trim(),
).toMatch(/^restored\//);
).toBe("");
});
test("restore failure stays visible and permits a successful retry", async ({ page }) => {
@@ -97,18 +97,15 @@ export class ImportSessionFlow {
await target.scrollIntoViewIfNeeded();
await expect(target).toBeInViewport();
}
/**
* Scrolls the virtualized list, the only one that leaves rows unmounted. A row handle is no way
* in: the list unmounts rows as it scrolls, and a detached row has no scroller above it.
*/
private async scrollList(forward: boolean) {
await this.page
.locator('[data-testid^="import-session-session-"]')
.first()
.evaluate((row, advance) => {
let element = row.parentElement;
while (element && !["auto", "scroll"].includes(getComputedStyle(element).overflowY))
element = element.parentElement;
if (!element) throw new Error("Import list has no scroll owner");
element.scrollTop = advance ? element.scrollTop + element.clientHeight * 0.8 : 0;
element.dispatchEvent(new Event("scroll"));
}, forward);
await this.page.getByTestId("import-session-list").evaluate((list, advance) => {
list.scrollTop = advance ? list.scrollTop + list.clientHeight * 0.8 : 0;
list.dispatchEvent(new Event("scroll"));
}, forward);
}
async search(query: string) {
await this.page.getByTestId("import-session-search").fill(query);
@@ -120,11 +117,18 @@ export class ImportSessionFlow {
await this.page.getByTestId("import-session-search").fill("");
await expect(this.page.getByTestId("import-session-load-more")).toBeVisible();
}
/** Load more keeps the reader down the list instead of sending them back to the top. */
async loadMore() {
await this.page.getByTestId("import-session-load-more").click();
const loadMore = this.page.getByTestId("import-session-load-more");
const topRow = this.page.getByTestId((await this.rowIds())[0]!);
await expect(topRow).toBeInViewport();
await loadMore.click();
// The next page is the last and short, so the button leaves once it lands.
await expect(loadMore).toHaveCount(0);
await expect(this.page.getByText("Loading sessions...", { exact: true })).toHaveCount(0);
await expect(topRow).not.toBeInViewport();
await this.revealSession("fixture-root-20");
await expect(this.page.getByText("Root session 20", { exact: true })).toBeInViewport();
await expect(this.page.getByTestId("import-session-load-more")).toHaveCount(0);
}
async retryProvider(provider: string, label: string) {
await this.expectProviderError(label);
@@ -17,6 +17,11 @@ export function nextPageLimit(limit: number): number {
return PAGE_LIMITS.find((candidate) => candidate > limit) ?? limit;
}
/** The page Load more grew this limit from, or null for the first page. */
export function previousPageLimit(limit: number): number | null {
return PAGE_LIMITS.findLast((candidate) => candidate < limit) ?? null;
}
export function requiresImportSessionsHostUpgrade(input: {
supportsSnapshot: boolean;
workspaceId?: string | null;
@@ -1172,6 +1172,44 @@ describe("ImportSessionSheet", () => {
});
});
it("keeps the loaded list in place while Load more fetches the next page", async () => {
let releaseNextPage: () => void = () => undefined;
const nextPage = new Promise<void>((resolve) => {
releaseNextPage = resolve;
});
const fetchRecentProviderSessions = vi.fn(async (options: { limit?: number } | undefined) => {
if (options?.limit !== 15) await nextPage;
return {
requestId: "recent-provider-sessions",
entries: createPageOfEntries(options?.limit === 15 ? 15 : 20),
};
});
renderSheet(createRecentSessionsClient(fetchRecentProviderSessions, vi.fn()), {
cwd: null,
snapshot: { supportsSnapshot: true, entries: [createSnapshotEntry("claude")] },
});
fireEvent.click(await screen.findByTestId("import-session-load-more"));
// The list the user scrolled to Load more is the one they keep: replacing it would drop
// them back at the top, behind a loading state, until the larger page lands.
const list = screen.getByTestId("import-session-list");
await waitFor(() => {
expect(fetchRecentProviderSessions).toHaveBeenCalledWith({
providers: ["claude"],
limit: 45,
});
});
expect(screen.getByTestId("import-session-list")).toBe(list);
expect(screen.queryByText("Loading sessions...")).toBeNull();
releaseNextPage();
await waitFor(() => {
expect(screen.queryByTestId("import-session-load-more")).toBeNull();
});
expect(screen.getByTestId("import-session-list")).toBe(list);
});
it("stops the refresh spinner and retries only the failed provider", async () => {
const fetchRecentProviderSessions = vi.fn(
async (options: { providers?: string[] } | undefined) => {
@@ -1,6 +1,6 @@
import React, { type ReactNode, useCallback, useEffect, useMemo, useRef, useState } from "react";
import { Pressable, type PressableStateCallbackType, Text, View } from "react-native";
import { keepPreviousData, useMutation, useQueries, useQueryClient } from "@tanstack/react-query";
import { useMutation, useQueries, useQueryClient, type QueryClient } from "@tanstack/react-query";
import { useTranslation } from "react-i18next";
import type {
DaemonClient,
@@ -40,6 +40,7 @@ import {
resolveDirectoryLabel,
nextPageLimit,
PER_PROVIDER_LIMIT,
previousPageLimit,
type ProviderErrorRow,
resolveImportTarget,
resolveProvidersToFetch,
@@ -100,11 +101,12 @@ interface SessionsQueryConfig {
// Query's default retry would keep the header spinner turning and pile up
// in-flight daemon requests behind a dead provider (#2512).
retry: false;
placeholderData: typeof keepPreviousData;
placeholderData: () => RecentSessionsResponse | undefined;
queryFn: () => Promise<RecentSessionsResponse>;
}
function buildSessionsQueriesConfig(args: {
queryClient: QueryClient;
providersToFetch: AgentProvider[] | null;
visible: boolean;
client: RecentProviderSessionsClient | null;
@@ -113,14 +115,24 @@ function buildSessionsQueriesConfig(args: {
limit: number;
hostDisconnectedMessage?: string;
}): SessionsQueryConfig[] {
const { providersToFetch, visible, client, cwd, query, limit, hostDisconnectedMessage } = args;
const { queryClient, providersToFetch, visible, client, cwd, query, limit } = args;
const { hostDisconnectedMessage } = args;
if (providersToFetch === null) return [];
const enabled = visible && Boolean(client);
const previousLimit = previousPageLimit(limit);
return providersToFetch.map((provider) => ({
queryKey: buildSessionsQueryKey({ cwd, query, limit, provider }),
enabled,
retry: false as const,
placeholderData: keepPreviousData,
// While Load more fetches the next page, keep showing the page it grew from. React Query's
// keepPreviousData cannot do this here: useQueries gives a changed key a new observer, which
// has no previous data, so the rows would vanish and the list would remount at the top.
placeholderData: () =>
previousLimit === null
? undefined
: queryClient.getQueryData<RecentSessionsResponse>(
buildSessionsQueryKey({ cwd, query, limit: previousLimit, provider }),
),
queryFn: async () => {
if (!client) {
throw new Error(hostDisconnectedMessage ?? i18n.t("workspace.terminal.hostDisconnected"));
@@ -522,6 +534,7 @@ export function ImportSessionSheet({
const queriesConfig = useMemo(
() =>
buildSessionsQueriesConfig({
queryClient,
providersToFetch,
visible,
client,
@@ -530,7 +543,7 @@ export function ImportSessionSheet({
limit: pageLimit,
hostDisconnectedMessage: t("workspace.terminal.hostDisconnected"),
}),
[providersToFetch, visible, client, scopeCwd, query, pageLimit, t],
[queryClient, providersToFetch, visible, client, scopeCwd, query, pageLimit, t],
);
const queries = useQueries({ queries: queriesConfig });
+2 -2
View File
@@ -484,8 +484,7 @@ export const ar: TranslationResources = {
archivedTitle: "مساحة العمل مؤرشفة",
restoreDescription:
"استعد {{workspaceName}} للعودة إلى وكلائها. ستستخدم شجرة العمل الفرع {{branch}}.",
restoreWithoutBranchDescription:
"استعد {{workspaceName}} للعودة إلى وكلائها. سيبدأ فرع جديد من الفرع الأساسي المحفوظ أو الفرع الافتراضي للمستودع.",
restoreWithoutBranchDescription: "استعد {{workspaceName}} للعودة إلى وكلائها.",
unarchiveDescription: "{{workspaceName}} مؤرشفة. ألغِ أرشفتها لفتحها مجددًا.",
restoreAction: "استعادة",
unarchiveAction: "إلغاء الأرشفة",
@@ -2017,6 +2016,7 @@ export const ar: TranslationResources = {
hostUnavailable: "مضيف التنزيل غير متاح.",
cancelled: "تم إلغاء التنزيل.",
failed: "فشل تنزيل الملف.",
httpFailed: "فشل تنزيل الملف (HTTP {{status}}).",
shareFile: "مشاركة الملف",
shareFileNamed: "مشاركة{{fileName}}",
},
+2 -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",
@@ -2045,6 +2044,7 @@ 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,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",
@@ -2066,6 +2065,7 @@ 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,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",
@@ -2065,6 +2064,7 @@ 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,8 +489,7 @@ export const ja: TranslationResources = {
archivedTitle: "ワークスペースはアーカイブ済みです",
restoreDescription:
"{{workspaceName}} を復元してエージェントに戻ります。worktree ではブランチ {{branch}} を使用します。",
restoreWithoutBranchDescription:
"{{workspaceName}} を復元してエージェントに戻ります。保存されたベース、またはリポジトリのデフォルトブランチから新しいブランチを作成します。",
restoreWithoutBranchDescription: "{{workspaceName}} を復元してエージェントに戻ります。",
unarchiveDescription:
"{{workspaceName}} はアーカイブされています。再度開くにはアーカイブを解除してください。",
restoreAction: "復元",
@@ -2038,6 +2037,7 @@ export const ja: TranslationResources = {
hostUnavailable: "ダウンロードホストが利用できません。",
cancelled: "ダウンロードがキャンセルされました。",
failed: "ファイルのダウンロードに失敗しました。",
httpFailed: "ファイルのダウンロードに失敗しました (HTTP {{status}}).",
shareFile: "ファイルを共有",
shareFileNamed: "{{fileName}}を共有",
},
+2 -2
View File
@@ -485,8 +485,7 @@ export const ko: TranslationResources = {
archivedTitle: "워크스페이스가 보관되었습니다",
restoreDescription:
"{{workspaceName}}를 복원하여 에이전트로 돌아갑니다. 워크트리는 {{branch}} 브랜치를 사용합니다.",
restoreWithoutBranchDescription:
"{{workspaceName}}를 복원하여 에이전트로 돌아갑니다. 저장된 기반 브랜치 또는 저장소 기본 브랜치에서 새 브랜치를 만듭니다.",
restoreWithoutBranchDescription: "{{workspaceName}}를 복원하여 에이전트로 돌아갑니다.",
unarchiveDescription: "{{workspaceName}}가 보관되었습니다. 다시 열려면 보관을 취소하세요.",
restoreAction: "복원",
unarchiveAction: "보관 취소",
@@ -2028,6 +2027,7 @@ export const ko: TranslationResources = {
hostUnavailable: "다운로드 호스트를 사용할 수 없습니다.",
cancelled: "다운로드가 취소되었습니다.",
failed: "파일을 다운로드하지 못했습니다.",
httpFailed: "파일을 다운로드하지 못했습니다 (HTTP {{status}}).",
shareFile: "파일 공유",
shareFileNamed: "{{fileName}} 공유",
},
+2 -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",
@@ -2051,6 +2050,7 @@ 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}}",
},
+2 -1
View File
@@ -489,7 +489,7 @@ export const ru: TranslationResources = {
restoreDescription:
"Восстановите «{{workspaceName}}», чтобы вернуться к его агентам. Worktree будет использовать ветку {{branch}}.",
restoreWithoutBranchDescription:
"Восстановите «{{workspaceName}}», чтобы вернуться к его агентам. Новая ветка будет создана от сохранённой базовой или ветки репозитория по умолчанию.",
"Восстановите «{{workspaceName}}», чтобы вернуться к его агентам.",
unarchiveDescription:
"Рабочее пространство «{{workspaceName}}» находится в архиве. Разархивируйте его, чтобы снова открыть.",
restoreAction: "Восстановить",
@@ -2051,6 +2051,7 @@ export const ru: TranslationResources = {
hostUnavailable: "Хост загрузки недоступен.",
cancelled: "Загрузка отменена.",
failed: "Не удалось загрузить файл.",
httpFailed: "Не удалось загрузить файл (HTTP {{status}}).",
shareFile: "Поделиться файлом",
shareFileNamed: "Поделиться {{fileName}}",
},
+2 -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: "取消归档",
@@ -1994,6 +1993,7 @@ export const zhCN: TranslationResources = {
hostUnavailable: "下载 Host 不可用。",
cancelled: "下载已取消。",
failed: "下载文件失败。",
httpFailed: "下载文件失败 (HTTP {{status}}).",
shareFile: "共享文件",
shareFileNamed: "共享 {{fileName}}",
},
@@ -90,6 +90,7 @@ 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> {
@@ -108,6 +109,7 @@ 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;
@@ -203,6 +205,57 @@ 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");
+39 -34
View File
@@ -4,7 +4,6 @@ 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";
@@ -59,6 +58,7 @@ 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,6 +86,7 @@ export const useDownloadStore = create<DownloadState>()((set, get) => ({
requestFileDownloadToken,
readFile,
saveFile = saveDownloadedBytes,
fetchFile = fetch,
}) => {
const id = generateDownloadId();
const download: Download = {
@@ -144,14 +145,11 @@ export const useDownloadStore = create<DownloadState>()((set, get) => ({
throw new Error(i18n.t("downloads.hostUnavailable"));
}
const downloadUrl = buildDownloadUrl(
downloadTarget.baseUrl,
tokenResponse.token,
isWeb ? downloadTarget.authCredentials : null,
);
const downloadUrl = buildDownloadUrl(downloadTarget.baseUrl, tokenResponse.token);
if (isWeb) {
triggerBrowserDownload(downloadUrl, resolvedFileName);
const file = await fetchDownload(fetchFile, downloadUrl);
saveBrowserFile(file, resolvedFileName);
get().completeDownload(id);
return;
}
@@ -198,11 +196,6 @@ 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);
}
},
@@ -283,7 +276,6 @@ function findMostRecentDownloadId(downloads: Map<string, Download>): string | nu
interface DownloadTarget {
baseUrl: string | null;
authHeader: string | null;
authCredentials: { username: string; password: string } | null;
}
/**
@@ -306,7 +298,7 @@ function resolveDaemonDownloadTarget(
buildDaemonWebSocketUrl(connection.endpoint, { useTls: connection.useTls ?? false }),
);
} catch {
return { baseUrl: null, authHeader: null, authCredentials: null };
return { baseUrl: null, authHeader: null };
}
if (parsed.protocol === "ws:") {
@@ -332,23 +324,41 @@ function resolveDaemonDownloadTarget(
? `Basic ${btoa(`${authCredentials.username}:${authCredentials.password}`)}`
: null;
return { baseUrl, authHeader, authCredentials };
return { baseUrl, authHeader };
}
function buildDownloadUrl(
baseUrl: string,
token: string,
authCredentials: { username: string; password: string } | null,
): string {
function buildDownloadUrl(baseUrl: string, token: string): 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.
@@ -361,12 +371,7 @@ async function saveDownloadedBytes({
if (isWeb) {
const buffer = new ArrayBuffer(bytes.byteLength);
new Uint8Array(buffer).set(bytes);
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);
saveBrowserFile(new Blob([buffer], { type: mimeType ?? "application/octet-stream" }), fileName);
return null;
}
// Resolve and write in one tick so two downloads of the same name cannot pick the same path.
@@ -390,14 +395,12 @@ async function shareSavedFile(
}
}
function triggerBrowserDownload(url: string, fileName: string) {
function saveBrowserFile(file: Blob, 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;
@@ -405,6 +408,8 @@ function triggerBrowserDownload(url: string, 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 {
+2 -2
View File
@@ -128,7 +128,7 @@ export async function fanOutReconciledWorkspaceUpdates(input: {
);
}
import { VoiceAssistantWebSocketServer } from "./websocket-server.js";
import { VoiceAssistantWebSocketServer, isDaemonOriginAllowed } 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 && (allowedOrigins.has("*") || allowedOrigins.has(origin))) {
if (origin && isDaemonOriginAllowed(origin, req.headers.host ?? null, allowedOrigins)) {
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 } from "node:http";
import { get, type IncomingMessage } from "node:http";
import { tmpdir } from "os";
import path from "path";
import { createDaemonTestContext, type DaemonTestContext } from "../test-utils/index.js";
@@ -69,6 +69,29 @@ 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 () => {
@@ -554,7 +554,7 @@ test("Hub resolves persisted execution ownership after daemon restart", async ()
expect(workspaceId).toEqual(expect.any(String));
expect(await hub.archivedWorkspaceAt(workspaceId!)).toEqual(expect.any(String));
expect(await hub.worktreeState(worktreeCwd)).toEqual({ exists: false, listed: false });
}, 20_000);
}, 60_000);
test("Hub treats missing and foreign executions as already controlled without exposing ownership", async () => {
const hub = await launchRelationship();
@@ -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-commit" }
>;
export interface ResolveWorktreeCreationIntentInput {
@@ -335,11 +335,15 @@ async function createBaseRecoveryFixture(baseBranch: string | null) {
await registry.update(record.workspaceId, (value) => ({ ...value, archivedAt: null }));
},
});
async function archiveAndRemove() {
await archivePersistedWorkspaceRecord({
workspaceId: workspace.workspaceId,
workspaceRegistry: registry,
});
async function archiveAndRemove(legacy = false) {
if (legacy) {
await registry.archive(workspace.workspaceId, new Date().toISOString());
} else {
await archivePersistedWorkspaceRecord({
workspaceId: workspace.workspaceId,
workspaceRegistry: registry,
});
}
await deletePaseoWorktree({ cwd: repoDir, worktreePath: workspace.cwd, paseoHome });
expect(existsSync(workspace.cwd)).toBe(false);
}
@@ -357,6 +361,134 @@ test("preserves ordinary checkout behavior when no separate base was recorded",
).toMatchObject({ currentBranch: "feature", baseRef: "feature" });
});
test("records the full HEAD ref of an archived checkout", async () => {
const fixture = await createBaseRecoveryFixture(null);
await fixture.archiveAndRemove();
expect(await fixture.registry.get(fixture.workspace.workspaceId)).toMatchObject({
branch: "feature",
head: "refs/heads/feature",
});
});
test("archives a workspace whose worktree Git administration is missing", async () => {
const fixture = await createBaseRecoveryFixture(null);
const gitDir = execFileSync("git", ["rev-parse", "--absolute-git-dir"], {
cwd: fixture.workspace.cwd,
encoding: "utf8",
}).trim();
rmSync(gitDir, { recursive: true, force: true });
await archivePersistedWorkspaceRecord({
workspaceId: fixture.workspace.workspaceId,
workspaceRegistry: fixture.registry,
});
expect((await fixture.registry.get(fixture.workspace.workspaceId))?.archivedAt).toBeTruthy();
});
test("restores a branch that shares its name with a tag", async () => {
const fixture = await createBaseRecoveryFixture("main");
execFileSync("git", ["tag", "feature"], { cwd: fixture.repoDir });
await fixture.archiveAndRemove();
expect((await fixture.registry.get(fixture.workspace.workspaceId))?.head).toBe(
"refs/heads/feature",
);
expect(await fixture.service.inspect(fixture.workspace.workspaceId)).toMatchObject({
branch: "feature",
});
await fixture.service.restore(fixture.workspace.workspaceId);
expect(
execFileSync("git", ["symbolic-ref", "HEAD"], {
cwd: fixture.workspace.cwd,
encoding: "utf8",
}).trim(),
).toBe("refs/heads/feature");
});
test("restores detached HEAD even when the stored branch is stale", async () => {
const fixture = await createBaseRecoveryFixture("main");
execFileSync("git", ["switch", "--detach"], { cwd: fixture.workspace.cwd });
const commit = execFileSync("git", ["rev-parse", "HEAD"], {
cwd: fixture.workspace.cwd,
encoding: "utf8",
}).trim();
await fixture.archiveAndRemove();
expect(await fixture.registry.get(fixture.workspace.workspaceId)).toMatchObject({
branch: "feature",
head: commit,
});
expect(await fixture.service.inspect(fixture.workspace.workspaceId)).toMatchObject({
branch: null,
});
await fixture.service.restore(fixture.workspace.workspaceId);
expect(
execFileSync("git", ["rev-parse", "--abbrev-ref", "HEAD"], {
cwd: fixture.workspace.cwd,
encoding: "utf8",
}).trim(),
).toBe("HEAD");
expect(
execFileSync("git", ["rev-parse", "HEAD"], {
cwd: fixture.workspace.cwd,
encoding: "utf8",
}).trim(),
).toBe(commit);
});
test.each(["manual", "reconciliation"] as const)(
"a later %s archive without a readable HEAD restores the latest recorded branch",
async (route) => {
const fixture = await createBaseRecoveryFixture("main");
await fixture.archiveAndRemove();
await fixture.service.restore(fixture.workspace.workspaceId);
execFileSync("git", ["switch", "-c", "feature-b"], { cwd: fixture.workspace.cwd });
writeFileSync(join(fixture.workspace.cwd, "newer.txt"), "newer\n");
execFileSync("git", ["add", "newer.txt"], { cwd: fixture.workspace.cwd });
execFileSync("git", ["-c", "commit.gpgsign=false", "commit", "-m", "newer"], {
cwd: fixture.workspace.cwd,
});
const commit = execFileSync("git", ["rev-parse", "HEAD"], {
cwd: fixture.workspace.cwd,
encoding: "utf8",
}).trim();
// Placement reconciliation records the branch observed while the workspace is active.
await fixture.registry.update(fixture.workspace.workspaceId, (workspace) => ({
...workspace,
branch: "feature-b",
}));
execFileSync("git", ["worktree", "remove", "--force", fixture.workspace.cwd], {
cwd: fixture.repoDir,
});
if (route === "manual") {
await archivePersistedWorkspaceRecord({
workspaceId: fixture.workspace.workspaceId,
workspaceRegistry: fixture.registry,
});
} else {
await fixture.registry.archive(fixture.workspace.workspaceId, new Date().toISOString());
}
expect(await fixture.registry.get(fixture.workspace.workspaceId)).toMatchObject({
branch: "feature-b",
head: undefined,
});
expect(await fixture.service.inspect(fixture.workspace.workspaceId)).toMatchObject({
branch: "feature-b",
});
await fixture.service.restore(fixture.workspace.workspaceId);
expect(
execFileSync("git", ["symbolic-ref", "HEAD"], {
cwd: fixture.workspace.cwd,
encoding: "utf8",
}).trim(),
).toBe("refs/heads/feature-b");
expect(
execFileSync("git", ["rev-parse", "HEAD"], {
cwd: fixture.workspace.cwd,
encoding: "utf8",
}).trim(),
).toBe(commit);
},
);
test("restores a branchless workspace from its recorded base so work can continue", async () => {
const fixture = await createBaseRecoveryFixture("refs/heads/release");
execFileSync("git", ["switch", "-c", "release"], { cwd: fixture.repoDir, stdio: "pipe" });
@@ -368,7 +500,7 @@ test("restores a branchless workspace from its recorded base so work can continu
...workspace,
branch: null,
}));
await fixture.archiveAndRemove();
await fixture.archiveAndRemove(true);
await expect(fixture.service.inspect(fixture.workspace.workspaceId)).resolves.toMatchObject({
kind: "recoverable",
@@ -402,7 +534,7 @@ test("restores a branchless workspace from the repository default when its base
...workspace,
branch: null,
}));
await fixture.archiveAndRemove();
await fixture.archiveAndRemove(true);
await expect(fixture.service.restore(fixture.workspace.workspaceId)).resolves.toEqual({
workspaceId: fixture.workspace.workspaceId,
@@ -418,6 +550,44 @@ test("restores a branchless workspace from the repository default when its base
);
});
test("restores the archived detached checkout at its recorded commit", async () => {
const fixture = await createBaseRecoveryFixture("refs/heads/main");
execFileSync("git", ["switch", "--detach"], { cwd: fixture.workspace.cwd });
writeFileSync(join(fixture.workspace.cwd, "detached.txt"), "detached\n");
execFileSync("git", ["add", "detached.txt"], { cwd: fixture.workspace.cwd });
execFileSync("git", ["-c", "commit.gpgsign=false", "commit", "-m", "detached"], {
cwd: fixture.workspace.cwd,
});
const commit = execFileSync("git", ["rev-parse", "HEAD"], {
cwd: fixture.workspace.cwd,
encoding: "utf8",
}).trim();
await fixture.archiveAndRemove();
expect(await fixture.registry.get(fixture.workspace.workspaceId)).toMatchObject({
branch: "feature",
head: commit,
});
execFileSync("git", ["reflog", "expire", "--expire=now", "--all"], { cwd: fixture.repoDir });
execFileSync("git", ["gc", "--prune=now"], { cwd: fixture.repoDir });
await fixture.service.restore(fixture.workspace.workspaceId);
expect(await readPaseoWorktreeMetadata(fixture.workspace.cwd)).toMatchObject({
baseRefName: "main",
baseRef: "refs/heads/main",
});
expect(
execFileSync("git", ["rev-parse", "HEAD"], {
cwd: fixture.workspace.cwd,
encoding: "utf8",
}).trim(),
).toBe(commit);
expect(
execFileSync("git", ["rev-parse", "--abbrev-ref", "HEAD"], {
cwd: fixture.workspace.cwd,
encoding: "utf8",
}).trim(),
).toBe("HEAD");
});
test("restores the branch HEAD with a base name when the exact base is missing", async () => {
const fixture = await createBaseRecoveryFixture("refs/remotes/upstream/main");
const headBeforeArchive = execFileSync("git", ["rev-parse", "HEAD"], {
@@ -151,13 +151,27 @@ export function createWorkspaceRecoveryService(deps: {
workspace: PersistedWorkspaceRecord,
sourceRepoRoot: string,
): 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),
};
let source: WorktreeSource;
const checkout = parseWorkspaceHead(workspace);
if (checkout.kind === "branch") {
source = {
kind: "restore",
branchName: checkout.branch,
baseRef: workspace.baseBranch,
};
} else if (checkout.kind === "commit") {
source = {
kind: "restore-commit",
commit: checkout.commit,
baseRef: await resolveRecoveryBase(sourceRepoRoot, workspace.baseBranch),
};
} else {
source = {
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 });
@@ -251,16 +265,29 @@ async function resolveRecoveryBase(repoRoot: string, recordedBase: string | null
return defaultBranch;
}
function parseWorkspaceHead(
workspace: PersistedWorkspaceRecord,
): { kind: "branch"; branch: string } | { kind: "commit"; commit: string } | { kind: "missing" } {
if (workspace.head) {
const prefix = "refs/heads/";
return workspace.head.startsWith(prefix)
? { kind: "branch", branch: workspace.head.slice(prefix.length) }
: { kind: "commit", commit: workspace.head };
}
return workspace.branch ? { kind: "branch", branch: workspace.branch } : { kind: "missing" };
}
function createRecoveryPlan(
input:
| { action: "unarchive"; workspace: PersistedWorkspaceRecord }
| { action: "restore"; workspace: PersistedWorkspaceRecord; sourceRepoRoot: string },
): RecoveryPlan {
const checkout = parseWorkspaceHead(input.workspace);
const state = {
kind: "recoverable" as const,
workspaceId: input.workspace.workspaceId,
workspaceName: resolveWorkspaceDisplayName(input.workspace),
branch: input.workspace.branch,
branch: checkout.kind === "branch" ? checkout.branch : null,
};
if (input.action === "restore") {
return {
+17 -3
View File
@@ -998,9 +998,7 @@ export class VoiceAssistantWebSocketServer {
callback(false, 403, "Host not allowed");
return;
}
const sameOrigin = isWebSocketSameOrigin(origin, requestHost);
if (!origin || allowedOrigins.has("*") || allowedOrigins.has(origin) || sameOrigin) {
if (!origin || isDaemonOriginAllowed(origin, requestHost, allowedOrigins)) {
callback(true);
} else {
this.incrementRuntimeCounter("originRejected");
@@ -3267,6 +3265,22 @@ 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,
@@ -8,6 +8,7 @@ import type { WorkspaceGitService } from "./workspace-git-service.js";
import type { ForgeService } from "../services/forge-service.js";
import {
deletePaseoWorktree,
readWorktreeHeadReference,
isPaseoOwnedWorktreeCwd,
runWorktreeTeardownCommands,
WorktreeTeardownError,
@@ -707,7 +708,15 @@ export async function archivePersistedWorkspaceRecord(input: {
}
const archivedAt = input.archivedAt ?? new Date().toISOString();
await input.workspaceRegistry.archive(input.workspaceId, archivedAt, input.context);
let head: string | null = null;
if (existingWorkspace.kind === "worktree") {
const cwd = existingWorkspace.worktreeRoot ?? existingWorkspace.cwd;
head = await readWorktreeHeadReference(cwd);
}
await input.workspaceRegistry.archive(input.workspaceId, archivedAt, {
...input.context,
...(head ? { head } : {}),
});
return existingWorkspace;
}
@@ -151,6 +151,40 @@ test.skipIf(process.platform === "win32")(
60000,
);
test.skipIf(process.platform === "win32").each([
["branch", "restore"],
["branch", "undo"],
["detached", "restore"],
["detached", "undo"],
] as const)(
"%s checkout survives archive and %s",
async (checkout, action) => {
const repo = createRepoWithGatedTeardown();
repo.releaseTeardown();
const { workspaceId, directory } = await createWorktreeWorkspaceWithAgent(
repo.repoDir,
`keep-${checkout}-${action}`,
);
if (checkout === "detached") git(directory, ["switch", "--detach"]);
writeFileSync(path.join(directory, "change.txt"), `${checkout}\n`);
git(directory, ["add", "change.txt"]);
git(directory, ["-c", "commit.gpgsign=false", "commit", "-m", "workspace commit"]);
const readHead = (args: string[]) =>
execFileSync("git", args, { cwd: directory, encoding: "utf8" }).trim();
const commit = readHead(["rev-parse", "HEAD"]);
const branch = readHead(["rev-parse", "--abbrev-ref", "HEAD"]);
expect((await ctx.client.archiveWorkspace(workspaceId)).error).toBeNull();
expect(existsSync(directory)).toBe(false);
git(repo.repoDir, ["reflog", "expire", "--expire=now", "--all"]);
git(repo.repoDir, ["gc", "--prune=now"]);
if (action === "undo") await ctx.client.undoWorkspaceArchive(workspaceId);
else await ctx.client.restoreWorkspace(workspaceId);
expect(readHead(["rev-parse", "HEAD"])).toBe(commit);
expect(readHead(["rev-parse", "--abbrev-ref", "HEAD"])).toBe(branch);
},
60000,
);
test.skipIf(process.platform === "win32")(
"archive, undo, archive leaves the workspace archived",
async () => {
@@ -72,6 +72,7 @@ const PersistedWorkspaceRecordSchema = z.object({
.nullable()
.optional()
.transform((value) => value ?? null),
head: z.string().optional(),
// Exact checkout/worktree root backing cwd. This differs from cwd when the
// selected project is a subdirectory inside a repository. Persist it so
// archive and recovery do not need the directory to still exist in order to
@@ -126,6 +127,7 @@ export interface WorkspaceMutationContext {
export interface WorkspaceArchiveContext {
autoArchivedChangeRequestUrl?: string;
head?: string;
}
export interface ProjectMutation {
@@ -586,6 +588,7 @@ export class FileBackedWorkspaceRegistry
...existing,
updatedAt: archivedAt,
archivedAt,
head: context?.head,
...(context?.autoArchivedChangeRequestUrl
? { autoArchivedChangeRequestUrl: context.autoArchivedChangeRequestUrl }
: {}),
@@ -1406,6 +1406,32 @@ describe.skipIf(isPlatform("win32"))("worktree POSIX-only", () => {
rmSync(tempDir, { recursive: true, force: true });
});
it("keeps an otherwise unreachable detached commit after deleting the worktree", async () => {
const result = await createWorktreePrimitive({
cwd: repoDir,
worktreeSlug: "keep-commit",
source: { kind: "branch-off", baseBranch: "main", branchName: "feature/keep-commit" },
paseoHome,
});
execFileSync("git", ["checkout", "--detach"], { cwd: result.worktreePath });
writeFileSync(join(result.worktreePath, "file.txt"), "detached change\n");
execFileSync("git", ["add", "file.txt"], { cwd: result.worktreePath });
execFileSync("git", ["-c", "commit.gpgsign=false", "commit", "-m", "detached"], {
cwd: result.worktreePath,
});
const commit = execFileSync("git", ["rev-parse", "HEAD"], {
cwd: result.worktreePath,
encoding: "utf8",
}).trim();
await deletePaseoWorktree({ cwd: repoDir, worktreePath: result.worktreePath, paseoHome });
execFileSync("git", ["reflog", "expire", "--expire=now", "--all"], { cwd: repoDir });
execFileSync("git", ["gc", "--prune=now"], { cwd: repoDir });
expect(
execFileSync("git", ["cat-file", "-t", commit], { cwd: repoDir, encoding: "utf8" }).trim(),
).toBe("commit");
});
it("places, owns, lists, and deletes a worktree outside the legacy root", async () => {
// Sibling layout: <repo-parent>/wt-<slug>
@@ -3,6 +3,7 @@ import {
createWorktree as createWorktreePrimitive,
deriveWorktreeProjectHash,
deletePaseoWorktree,
readWorktreeHead,
isPaseoOwnedWorktreeCwd,
mapWorkspaceCwdToWorktree,
runWorktreeTeardownCommands,
@@ -302,6 +303,29 @@ describe("paseo worktree manager", () => {
expect(existsSync(created.worktreePath)).toBe(false);
});
it("does not read a parent repository's HEAD when the worktree has no .git", async () => {
const directory = join(repoDir, "missing-worktree");
mkdirSync(directory);
await expect(readWorktreeHead(directory)).resolves.toBeNull();
});
it("keeps a worktree when writing its retention ref fails", async () => {
const created = await createLegacyWorktreeForTest({
branchName: "ref-write-failure",
cwd: repoDir,
baseBranch: "main",
worktreeSlug: "ref-write-failure",
paseoHome,
});
mkdirSync(join(repoDir, ".git", "refs", "paseo"), { recursive: true });
writeFileSync(join(repoDir, ".git", "refs", "paseo", "kept-commits"), "blocked\n");
await expect(
deletePaseoWorktree({ cwd: repoDir, worktreePath: created.worktreePath, paseoHome }),
).rejects.toThrow();
expect(existsSync(created.worktreePath)).toBe(true);
});
it("deletes a worktree when Git reports its source through native and long path spellings", async () => {
const created = await createLegacyWorktreeForTest({
branchName: "identity-delete",
+69 -6
View File
@@ -188,6 +188,7 @@ export type WorktreeSource =
| { kind: "branch-off"; baseBranch: string; branchName: string }
| { kind: "checkout-branch"; branchName: string }
| { kind: "restore"; branchName: string; baseRef: string | null }
| { kind: "restore-commit"; commit: string; baseRef: string }
| { kind: "restore-from-base"; baseRef: string; branchName: string }
| {
kind: "checkout-change-request";
@@ -1153,6 +1154,32 @@ async function assertWorktreeBelongsToRepo(cwd: string, worktreePath: string): P
}
}
export async function readWorktreeHead(worktreePath: string): Promise<string | null> {
if (!(await pathExists(join(worktreePath, ".git")))) return null;
try {
const { stdout } = await runGitCommand(["rev-parse", "--verify", "HEAD^{commit}"], {
cwd: worktreePath,
});
return stdout.trim();
} catch {
return null;
}
}
export async function readWorktreeHeadReference(worktreePath: string): Promise<string | null> {
if (!(await pathExists(join(worktreePath, ".git")))) return null;
try {
const result = await runGitCommand(["symbolic-ref", "--quiet", "HEAD"], {
cwd: worktreePath,
acceptExitCodes: [0, 1],
});
if (result.exitCode === 0) return result.stdout.trim();
return readWorktreeHead(worktreePath);
} catch {
return null;
}
}
export async function deletePaseoWorktree({
cwd,
worktreePath,
@@ -1208,6 +1235,12 @@ export async function deletePaseoWorktree({
teardownCwd,
});
}
const commit = await readWorktreeHead(resolvedWorktree);
if (commit) {
await runGitCommand(["update-ref", `refs/paseo/kept-commits/${commit}`, commit], {
cwd: resolvedWorktree,
});
}
}
if (cwd) {
@@ -1361,14 +1394,22 @@ export async function resolveDefaultWorktreePath(
/**
* Create a git worktree with proper naming conventions
*/
export const createWorktree = async ({
export function createWorktree(
options: CreateWorktreeOptions & { source: Exclude<WorktreeSource, { kind: "restore-commit" }> },
): Promise<CreatedWorktree>;
export function createWorktree(
options: CreateWorktreeOptions,
): Promise<Omit<CreatedWorktree, "branchName"> & { branchName: string | null }>;
export async function createWorktree({
cwd,
source,
worktreeSlug,
paseoHome,
worktreesRoot,
worktreePath: explicitWorktreePath,
}: CreateWorktreeOptions): Promise<CreatedWorktree> => {
}: CreateWorktreeOptions): Promise<
Omit<CreatedWorktree, "branchName"> & { branchName: string | null }
> {
const branchesBefore =
source.kind === "checkout-branch" ||
source.kind === "checkout-change-request" ||
@@ -1394,14 +1435,14 @@ export const createWorktree = async ({
});
worktreePath = await normalizePathForOwnership(worktreePath);
if (sourcePlan.pushRemote) {
if (sourcePlan.pushRemote && sourcePlan.branchName) {
await configureWorktreePushRemote({
cwd,
branchName: sourcePlan.branchName,
remote: sourcePlan.pushRemote,
});
}
if (sourcePlan.trackingRemote) {
if (sourcePlan.trackingRemote && sourcePlan.branchName) {
await configureWorktreeTrackingRemote({
cwd,
branchName: sourcePlan.branchName,
@@ -1434,7 +1475,7 @@ export const createWorktree = async ({
}
throw error;
}
};
}
interface ResolveWorktreeSourcePlanOptions {
cwd: string;
@@ -1443,7 +1484,7 @@ interface ResolveWorktreeSourcePlanOptions {
}
interface WorktreeSourcePlan {
branchName: string;
branchName: string | null;
// Display name and exact ref are two different facts. The name cannot round-trip to a
// commit — "main" resolves local-first even when the worktree was cut from a fork's
// upstream — so comparisons and actions read the ref and the UI reads the name.
@@ -1492,6 +1533,26 @@ async function resolveRestoredWorktreeSourcePlan(
};
}
async function resolveRestoredCommitSourcePlan(
cwd: string,
source: Extract<WorktreeSource, { kind: "restore-commit" }>,
): Promise<WorktreeSourcePlan> {
let exactBase: string | undefined;
if (isQualifiedRef(source.baseRef)) {
try {
exactBase = await resolveBaseBranchForWorktree(cwd, source.baseRef);
} catch {
// Restore the saved commit even when its comparison ref no longer exists.
}
}
return {
branchName: null,
metadataBaseRefName: normalizeRequiredBaseBranch(source.baseRef),
...(exactBase ? { metadataBaseRef: exactBase } : {}),
addArguments: ["--detach", source.commit],
};
}
async function resolveRestoredWorktreeFromBasePlan(
cwd: string,
source: Extract<WorktreeSource, { kind: "restore-from-base" }>,
@@ -1544,6 +1605,8 @@ async function resolveWorktreeSourcePlan({
return resolveBranchOffWorktreeSourcePlan(cwd, source, desiredSlug);
case "restore":
return resolveRestoredWorktreeSourcePlan(cwd, source);
case "restore-commit":
return resolveRestoredCommitSourcePlan(cwd, source);
case "restore-from-base":
return resolveRestoredWorktreeFromBasePlan(cwd, source);
case "checkout-branch": {