Compare commits

..
Author SHA1 Message Date
JIHUN LEEandClaude Opus 5.5 576d0320c8 Keep Android text at the window's density on Samsung DeX (#9995)
React Native 0.86 converts between px and dp with the density of the
phone's built-in display, while Fabric lays out at the window's density.
In a DeX window (240 dpi on a 360 dpi phone) every text box came out at
two thirds of the height its text needed, so the text was clipped.

Backport the rule from react/react-native#59087: right after React
Native reads the display (when it creates the root view and on each
configuration change), restore the window's density and keep only the
display's size. Remove once the app runs React Native 0.89 or later
with useWindowDensityForDisplayMetricsAndroid on.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 21:08:05 +00:00
paseo-bot[bot]andClaude Opus 5.5 c8e3d67e29 Wait for each plugin content subscription id before checking its release (#10012)
The plugin-buttons journey reads the details' event subscription id to
check that closing, crashing and disabling the content releases it. The
id arrives with the daemon's subscription response, after the details
render. The first open already waited for it; the reopens read it as
soon as the cached summary showed, so the id could still be empty and
the release poll then waited for an id that never exists.

Every read now waits for a non-empty id.

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 18:01:24 +00:00
95f2c7d16a Keep a Claude agent's process and background work when its effort level changes (#10008)
Changing the thinking level of a running Claude agent marked its query for a
restart. The next turn, mode change or model change then retired the Claude
process, which ended every background shell, workflow and subagent it ran with
"connection lost".

A move between two effort levels now goes to the running query through
applyFlagSettings({ effortLevel }), as Fast mode already does, and marks no
restart. Switching thinking off, to ultracode or back to the default still
restarts, because those change how the query is launched. If the running
process does not take the change, the old restart path runs, so the change is
never lost.


Row: app-built-from-one-set
Paseo: c6210e21-fc13-4dfa-adfc-43a050c7d75a

Co-authored-by: gilad-rubin <6134299+gilad-rubin@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 16:57:22 +00:00
paseo-bot[bot]andClaude Opus 5.5 2c2385f362 Create the workspace in the caller's directory when --path is relative (#10010)
* Create the workspace in the caller's directory when --path is relative

`paseo workspace create --path .` adopted the daemon's working directory
instead of the directory the command ran in. The CLI sent the relative
path unchanged, and the daemon resolved it against its own cwd. The CLI
now resolves a relative --path against the caller's directory before it
sends the request, as it already does when --path is omitted. Absolute
POSIX and Windows paths pass through unchanged so a remote daemon on
another operating system still gets the path as written.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Leave a home-relative --path for the daemon to expand

Resolving every non-absolute --path against the caller's directory turned
`--path=~/repo` (and a quoted "~/repo") into `<cwd>/~/repo`. Before this
change the daemon expanded the leading ~ itself. `~` and `~/…` now pass
through unchanged again.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Send a relative --path to an explicit daemon endpoint as written

The CLI already resolves caller paths only for a local daemon and sends
them unchanged to an explicit --host endpoint (resolveRepositoryDirectory,
project create). workspace create, and paseo run, which builds its
workspace source through it, now follow the same rule instead of turning
a relative path into a path on the caller's machine for a remote daemon.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

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 15:51:43 +00:00
paseo-bot[bot]andDominic Anaeto 7f0fe57c48 Settle a stuck agent run after a repeated cancel (#9774)
A force-cancel finalizes turn X in the daemon while the provider keeps
running it, so the next run can be bound to the same X. handleStreamEvent
dropped every terminal for a finalized turn id, including the synthetic
turn_canceled that cancelAgentRunNow dispatches for the tracked run and
the provider's own terminal. The run never settled, cancelAgentRunNow
waited on it forever, and every later cancel, reload and send queued
behind it until the daemon restarted.

A terminal for the tracked run's own turn id is no longer dropped.

Fixes #6355
Supersedes #8405

Co-authored-by: Dominic Anaeto <dominic.anaeto@gmail.com>
2026-11-17 15:08:26 +00:00
38 changed files with 570 additions and 410 deletions
+8
View File
@@ -121,6 +121,14 @@ from `packages/app/android`:
These check terminal arrow ownership, held-key repeats and modifiers, and ordinary text-field editing.
Run the display density regression tests the same way:
```bash
./gradlew :paseo-display-metrics:connectedDebugAndroidTest --no-daemon --max-workers=2 -Dorg.gradle.parallel=false
```
These check that React Native sizes text at the window's density when the window is on another display, such as Samsung DeX.
### Diagnostic logs without ADB
In a dogfood build, open Android's Files app → Downloads → **Paseo diagnostics** and share all
+2
View File
@@ -7,6 +7,7 @@ const withAndroidProfileable = require("./plugins/with-android-profileable");
const withFdroidAutolinking = require("./plugins/with-fdroid-autolinking");
const withPasteInput = require("./plugins/with-paste-input");
const withAndroidScroll = require("./modules/paseo-scroll/app.plugin");
const withAndroidDisplayMetrics = require("./modules/paseo-display-metrics/app.plugin");
const { getNativeReleaseVersion } = require("./native-release-version");
const appVariant = process.env.APP_VARIANT ?? "production";
const isFdroidBuild = process.env.PASEO_FDROID_BUILD === "1";
@@ -146,6 +147,7 @@ export default {
"expo-router",
withPasteInput,
withAndroidScroll,
withAndroidDisplayMetrics,
[withAndroidAsyncStorageSize, 64],
...buildProfile.cameraPlugins,
withAndroidOptionalCamera,
@@ -361,10 +361,6 @@ 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",
@@ -393,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");
@@ -410,13 +409,17 @@ test.describe("Worktree restore", () => {
cwd: backingWorktree.workspaceDirectory,
encoding: "utf8",
}).trim();
expect(restoredHead).toBe(originalHead);
const defaultHead = execFileSync("git", ["rev-parse", "main"], {
cwd: tempRepo.path,
encoding: "utf8",
}).trim();
expect(restoredHead).toBe(defaultHead);
expect(
execFileSync("git", ["branch", "--show-current"], {
cwd: backingWorktree.workspaceDirectory,
encoding: "utf8",
}).trim(),
).toBe("");
).toMatch(/^restored\//);
});
test("restore failure stays visible and permits a successful retry", async ({ page }) => {
@@ -198,6 +198,14 @@ async function expectDetails(page: Page) {
await expect(page.getByText("All systems operational", { exact: true })).toBeInViewport();
}
// The details render before the daemon answers their event subscription, and reopened
// details show the cached summary at once, so wait for the subscription id to arrive.
async function readContentObservation(page: Page): Promise<string> {
const observation = page.getByLabel("Content observation", { exact: true });
await expect(observation).not.toHaveText("");
return (await observation.textContent())!;
}
function workspaceMenuRow(page: Page, title: string): Locator {
return compactWorkspaceMenu(page).getByRole("menuitem", { name: title, exact: true });
}
@@ -354,14 +362,12 @@ export async function withButtonShowcase(
test.step("closing and crashing content release its owner while sibling buttons and app remain live", async () => {
await press(page, "Header status");
await expectDetails(page);
const observation = page.getByLabel("Content observation", { exact: true });
await expect(observation).not.toHaveText("");
const first = (await observation.textContent())!;
const first = await readContentObservation(page);
await press(page, "Close deployment details");
await expect.poll(() => released.has(first)).toBe(true);
await press(page, "Composer status");
await expectDetails(page);
const second = (await observation.textContent())!;
const second = await readContentObservation(page);
expect(second).not.toBe(first);
await workspace.client.renameProject(workspace.projectId, "Observer control");
await expect(page.getByText("Observed updates: 1", { exact: true })).toBeVisible();
@@ -373,7 +379,7 @@ export async function withButtonShowcase(
await page.keyboard.press("Escape");
await press(page, "Header status");
await expectDetails(page);
const recovered = (await observation.textContent())!;
const recovered = await readContentObservation(page);
expect([first, second]).not.toContain(recovered);
await showcase.setTitle("Healthy app after button failure");
await expect(page.getByTestId("workspace-header-title")).toHaveText(
@@ -687,9 +693,7 @@ export async function withButtonShowcase(
page,
page.getByRole("button", { name: "Close deployment details", exact: true }),
);
const observation = page.getByLabel("Content observation", { exact: true });
await expect(observation).not.toHaveText("");
const owner = (await observation.textContent())!;
const owner = await readContentObservation(page);
await showcase.disable();
await expect.poll(() => released.has(owner)).toBe(true);
await expect(
@@ -0,0 +1,2 @@
/android/.cxx/
/android/build/
@@ -0,0 +1,23 @@
apply plugin: 'com.android.library'
group = 'sh.paseo.displaymetrics'
version = '0.1.0'
def expoModulesCorePlugin = new File(project(":expo-modules-core").projectDir.absolutePath, "ExpoModulesCorePlugin.gradle")
apply from: expoModulesCorePlugin
applyKotlinExpoModulesCorePlugin()
useCoreDependencies()
useDefaultAndroidSdkVersions()
android {
namespace "sh.paseo.displaymetrics"
defaultConfig {
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
}
dependencies {
implementation "com.facebook.react:react-android"
androidTestImplementation 'androidx.test:runner:1.6.2'
androidTestImplementation 'androidx.test.ext:junit:1.2.1'
}
@@ -0,0 +1,86 @@
package sh.paseo.displaymetrics
import android.util.DisplayMetrics
import android.util.TypedValue
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import com.facebook.react.uimanager.DisplayMetricsHolder
import com.facebook.react.uimanager.PixelUtil
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertSame
import org.junit.Assert.assertThrows
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class PaseoDisplayMetricsTest {
private lateinit var display: DisplayMetrics
@Before
fun readDisplayLikeReactNative() {
DisplayMetricsHolder.initDisplayMetrics(InstrumentationRegistry.getInstrumentation().targetContext)
display = DisplayMetricsHolder.getScreenDisplayMetrics()
}
@After
fun forgetDisplay() {
DisplayMetricsHolder.setScreenDisplayMetrics(null)
}
@Test
fun reservesRoomForTextAtTheWindowDensity() {
// A DeX window at two thirds of the phone's density (240 dpi on a 360 dpi phone). React Native
// reads the font scale from the window but the density from the phone's display.
val window = windowAt(display.densityDpi * 2 / 3)
DisplayMetricsHolder.setScreenDisplayMetrics(
DisplayMetrics().apply {
setTo(display)
scaledDensity = window.scaledDensity
},
)
assertTrue(reservedTextPx(window) < drawnTextPx())
PaseoDisplayMetrics.syncWithWindow(window)
assertEquals(drawnTextPx(), reservedTextPx(window), 0.01f)
assertEquals(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 16f, window), drawnTextPx(), 0.01f)
val synced = DisplayMetricsHolder.getScreenDisplayMetrics()
assertEquals(window.densityDpi, synced.densityDpi)
assertEquals(display.widthPixels, synced.widthPixels)
assertEquals(display.heightPixels, synced.heightPixels)
}
@Test
fun leavesTheBuiltInDisplayAlone() {
PaseoDisplayMetrics.syncWithWindow(windowAt(display.densityDpi))
assertSame(display, DisplayMetricsHolder.getScreenDisplayMetrics())
}
@Test
fun waitsForReactNativeToReadTheDisplay() {
DisplayMetricsHolder.setScreenDisplayMetrics(null)
PaseoDisplayMetrics.syncWithWindow(windowAt(display.densityDpi / 2))
assertThrows(IllegalStateException::class.java) { DisplayMetricsHolder.getScreenDisplayMetrics() }
}
private fun windowAt(densityDpi: Int): DisplayMetrics =
DisplayMetrics().apply {
setTo(display)
this.densityDpi = densityDpi
density = densityDpi.toFloat() / DisplayMetrics.DENSITY_DEFAULT
scaledDensity = density * display.scaledDensity / display.density
}
/** A 16sp font as React Native draws it, in pixels. */
private fun drawnTextPx(): Float = PixelUtil.toPixelFromSP(16f)
/** The box React Native lays out for that font, once the window renders it in pixels. */
private fun reservedTextPx(window: DisplayMetrics): Float =
PixelUtil.toDIPFromPixel(drawnTextPx()) * window.density
}
@@ -0,0 +1,43 @@
package sh.paseo.displaymetrics
import android.app.Activity
import android.util.DisplayMetrics
import com.facebook.react.uimanager.DisplayMetricsHolder
/**
* React Native 0.86 converts between px and dp, and so sizes text, with the density of the
* device's built-in display, because `DisplayMetricsHolder` reads `Display.getRealMetrics()`.
* Fabric lays out at the window's density. On a display with another density, such as a Samsung
* DeX monitor, text boxes come out too small and clip their text.
*
* Backports react/react-native#59087 (`useWindowDensityForDisplayMetricsAndroid`): keep the
* window's density and take only the size from the display. Remove once the app runs React Native
* 0.89 or later with that flag on.
*/
object PaseoDisplayMetrics {
/** Call right after React Native reads the display, which it does again on each configuration change. */
@JvmStatic
fun syncWithWindow(activity: Activity) {
syncWithWindow(activity.resources.displayMetrics)
}
@JvmStatic
fun syncWithWindow(window: DisplayMetrics) {
val screen =
try {
DisplayMetricsHolder.getScreenDisplayMetrics()
} catch (_: IllegalStateException) {
// React Native hasn't read the display yet, so there is nothing to correct.
return
}
if (screen.densityDpi == window.densityDpi) return
DisplayMetricsHolder.setScreenDisplayMetrics(
DisplayMetrics().apply {
setTo(screen)
density = window.density
densityDpi = window.densityDpi
},
)
}
}
@@ -0,0 +1,35 @@
const { withMainActivity } = require("expo/config-plugins");
const ACTIVITY_CLASS = "class MainActivity : ReactActivity() {";
const SYNC = "sh.paseo.displaymetrics.PaseoDisplayMetrics.syncWithWindow(this)";
// React Native re-reads the built-in display's density when it creates the root view and on every
// configuration change, so the window's density has to be restored right after each `super` call.
const OVERRIDES = `
override fun onContentChanged() {
super.onContentChanged()
${SYNC}
}
override fun onConfigurationChanged(newConfig: android.content.res.Configuration) {
super.onConfigurationChanged(newConfig)
${SYNC}
}
`;
function configureDisplayMetricsActivity(contents) {
if (contents.includes(SYNC)) return contents;
if (
!contents.includes(ACTIVITY_CLASS) ||
/override fun on(ContentChanged|ConfigurationChanged)\(/.test(contents)
) {
throw new Error("Could not keep React Native text at the window's density in MainActivity");
}
return contents.replace(ACTIVITY_CLASS, `${ACTIVITY_CLASS}${OVERRIDES}`);
}
module.exports = (config) =>
withMainActivity(config, (mod) => {
mod.modResults.contents = configureDisplayMetricsActivity(mod.modResults.contents);
return mod;
});
module.exports.configureDisplayMetricsActivity = configureDisplayMetricsActivity;
@@ -0,0 +1,29 @@
import { describe, expect, it } from "vitest";
const { configureDisplayMetricsActivity } = require("./app.plugin");
const SYNC = "sh.paseo.displaymetrics.PaseoDisplayMetrics.syncWithWindow(this)";
describe("Android display metrics", () => {
it("restores the window's density after React Native reads the display", () => {
const source = "class MainActivity : ReactActivity() {\n}";
const result = configureDisplayMetricsActivity(source);
expect(result).toContain(`super.onContentChanged()\n ${SYNC}`);
expect(result).toContain(`super.onConfigurationChanged(newConfig)\n ${SYNC}`);
expect(configureDisplayMetricsActivity(result)).toBe(result);
});
it("fails prebuild when the template no longer has a place for the overrides", () => {
expect(() => configureDisplayMetricsActivity("changed template")).toThrow(
"Could not keep React Native text at the window's density",
);
});
it("fails prebuild rather than replace another plugin's configuration handler", () => {
const source =
"class MainActivity : ReactActivity() {\n override fun onConfigurationChanged(newConfig: Configuration) {}\n}";
expect(() => configureDisplayMetricsActivity(source)).toThrow(
"Could not keep React Native text at the window's density",
);
});
});
@@ -0,0 +1,6 @@
{
"platforms": ["android"],
"android": {
"modules": []
}
}
@@ -0,0 +1,5 @@
{
"name": "paseo-display-metrics",
"version": "0.1.0",
"private": true
}
+2 -1
View File
@@ -484,7 +484,8 @@ export const ar: TranslationResources = {
archivedTitle: "مساحة العمل مؤرشفة",
restoreDescription:
"استعد {{workspaceName}} للعودة إلى وكلائها. ستستخدم شجرة العمل الفرع {{branch}}.",
restoreWithoutBranchDescription: "استعد {{workspaceName}} للعودة إلى وكلائها.",
restoreWithoutBranchDescription:
"استعد {{workspaceName}} للعودة إلى وكلائها. سيبدأ فرع جديد من الفرع الأساسي المحفوظ أو الفرع الافتراضي للمستودع.",
unarchiveDescription: "{{workspaceName}} مؤرشفة. ألغِ أرشفتها لفتحها مجددًا.",
restoreAction: "استعادة",
unarchiveAction: "إلغاء الأرشفة",
+2 -1
View File
@@ -483,7 +483,8 @@ export const en = {
archivedTitle: "Workspace archived",
restoreDescription:
"Restore {{workspaceName}} to return to its agents. Its worktree will use branch {{branch}}.",
restoreWithoutBranchDescription: "Restore {{workspaceName}} to return to its agents.",
restoreWithoutBranchDescription:
"Restore {{workspaceName}} to return to its agents. A new branch will start from the saved base or the repository default.",
unarchiveDescription: "{{workspaceName}} is archived. Unarchive it to open it again.",
restoreAction: "Restore",
unarchiveAction: "Unarchive",
+2 -1
View File
@@ -489,7 +489,8 @@ export const es: TranslationResources = {
archivedTitle: "Espacio de trabajo archivado",
restoreDescription:
"Restaura {{workspaceName}} para volver a sus agentes. Su worktree usará la rama {{branch}}.",
restoreWithoutBranchDescription: "Restaura {{workspaceName}} para volver a sus agentes.",
restoreWithoutBranchDescription:
"Restaura {{workspaceName}} para volver a sus agentes. Se creará una rama nueva desde la base guardada o la rama predeterminada del repositorio.",
unarchiveDescription:
"{{workspaceName}} está archivado. Desarchívalo para volver a abrirlo.",
restoreAction: "Restaurar",
+2 -1
View File
@@ -489,7 +489,8 @@ export const fr: TranslationResources = {
archivedTitle: "Espace de travail archivé",
restoreDescription:
"Restaurez {{workspaceName}} pour retrouver ses agents. Son worktree utilisera la branche {{branch}}.",
restoreWithoutBranchDescription: "Restaurez {{workspaceName}} pour retrouver ses agents.",
restoreWithoutBranchDescription:
"Restaurez {{workspaceName}} pour retrouver ses agents. Une nouvelle branche partira de la base enregistrée ou de la branche par défaut du dépôt.",
unarchiveDescription: "{{workspaceName}} est archivé. Désarchivez-le pour le rouvrir.",
restoreAction: "Restaurer",
unarchiveAction: "Désarchiver",
+2 -1
View File
@@ -489,7 +489,8 @@ export const ja: TranslationResources = {
archivedTitle: "ワークスペースはアーカイブ済みです",
restoreDescription:
"{{workspaceName}} を復元してエージェントに戻ります。worktree ではブランチ {{branch}} を使用します。",
restoreWithoutBranchDescription: "{{workspaceName}} を復元してエージェントに戻ります。",
restoreWithoutBranchDescription:
"{{workspaceName}} を復元してエージェントに戻ります。保存されたベース、またはリポジトリのデフォルトブランチから新しいブランチを作成します。",
unarchiveDescription:
"{{workspaceName}} はアーカイブされています。再度開くにはアーカイブを解除してください。",
restoreAction: "復元",
+2 -1
View File
@@ -485,7 +485,8 @@ export const ko: TranslationResources = {
archivedTitle: "워크스페이스가 보관되었습니다",
restoreDescription:
"{{workspaceName}}를 복원하여 에이전트로 돌아갑니다. 워크트리는 {{branch}} 브랜치를 사용합니다.",
restoreWithoutBranchDescription: "{{workspaceName}}를 복원하여 에이전트로 돌아갑니다.",
restoreWithoutBranchDescription:
"{{workspaceName}}를 복원하여 에이전트로 돌아갑니다. 저장된 기반 브랜치 또는 저장소 기본 브랜치에서 새 브랜치를 만듭니다.",
unarchiveDescription: "{{workspaceName}}가 보관되었습니다. 다시 열려면 보관을 취소하세요.",
restoreAction: "복원",
unarchiveAction: "보관 취소",
+2 -1
View File
@@ -488,7 +488,8 @@ export const ptBR: TranslationResources = {
archivedTitle: "Workspace arquivado",
restoreDescription:
"Restaure {{workspaceName}} para voltar aos seus agentes. A worktree usará a branch {{branch}}.",
restoreWithoutBranchDescription: "Restaure {{workspaceName}} para voltar aos seus agentes.",
restoreWithoutBranchDescription:
"Restaure {{workspaceName}} para voltar aos seus agentes. Uma nova branch partirá da base salva ou da branch padrão do repositório.",
unarchiveDescription:
"{{workspaceName}} está arquivado. Desarquive-o para abri-lo novamente.",
restoreAction: "Restaurar",
+1 -1
View File
@@ -489,7 +489,7 @@ export const ru: TranslationResources = {
restoreDescription:
"Восстановите «{{workspaceName}}», чтобы вернуться к его агентам. Worktree будет использовать ветку {{branch}}.",
restoreWithoutBranchDescription:
"Восстановите «{{workspaceName}}», чтобы вернуться к его агентам.",
"Восстановите «{{workspaceName}}», чтобы вернуться к его агентам. Новая ветка будет создана от сохранённой базовой или ветки репозитория по умолчанию.",
unarchiveDescription:
"Рабочее пространство «{{workspaceName}}» находится в архиве. Разархивируйте его, чтобы снова открыть.",
restoreAction: "Восстановить",
+2 -1
View File
@@ -484,7 +484,8 @@ export const zhCN: TranslationResources = {
archivedTitle: "Workspace 已归档",
restoreDescription:
"恢复 {{workspaceName}} 以返回其中的代理。worktree 将使用分支 {{branch}}。",
restoreWithoutBranchDescription: "恢复 {{workspaceName}} 以返回其中的代理。",
restoreWithoutBranchDescription:
"恢复 {{workspaceName}} 以返回其中的代理。新分支将从保存的基准分支或仓库默认分支创建。",
unarchiveDescription: "{{workspaceName}} 已归档。取消归档以重新打开。",
restoreAction: "恢复",
unarchiveAction: "取消归档",
@@ -1,3 +1,4 @@
import path from "node:path";
import { describe, expect, it } from "vitest";
import { buildWorkspaceSource } from "./create.js";
@@ -8,6 +9,49 @@ describe("workspace create source", () => {
).toEqual({ kind: "directory", path: "/tmp/project", projectId: "project-1" });
});
it("resolves a relative path against the directory the command runs in", () => {
const daemonTarget = { kind: "instance" as const, home: "/tmp/paseo-home" };
expect(buildWorkspaceSource({ daemonTarget, isolation: "local", path: "." })).toEqual({
kind: "directory",
path: process.cwd(),
});
expect(
buildWorkspaceSource({ daemonTarget, isolation: "worktree", path: "../sibling" }),
).toEqual({
kind: "worktree",
cwd: path.resolve(process.cwd(), "../sibling"),
action: "branch-off",
});
});
it("sends a relative path to an explicit daemon endpoint as written", () => {
const daemonTarget = { kind: "endpoint" as const, host: "other-box:6767" };
expect(buildWorkspaceSource({ daemonTarget, isolation: "local", path: "repo" })).toEqual({
kind: "directory",
path: "repo",
});
});
it("passes an absolute path from another operating system through unchanged", () => {
expect(buildWorkspaceSource({ isolation: "local", path: "C:\\repos\\project" })).toEqual({
kind: "directory",
path: "C:\\repos\\project",
});
});
it("leaves a home-relative path for the daemon to expand", () => {
const daemonTarget = { kind: "instance" as const, home: "/tmp/paseo-home" };
expect(buildWorkspaceSource({ daemonTarget, isolation: "local", path: "~/repo" })).toEqual({
kind: "directory",
path: "~/repo",
});
expect(buildWorkspaceSource({ daemonTarget, isolation: "worktree", path: "~" })).toEqual({
kind: "worktree",
cwd: "~",
action: "branch-off",
});
});
it("keeps branch names separate from managed worktree slugs", () => {
expect(
buildWorkspaceSource({
+20 -2
View File
@@ -1,6 +1,10 @@
import { isAbsolute as isPosixAbsolute } from "node:path/posix";
import { isAbsolute as isWindowsAbsolute } from "node:path/win32";
import { resolve } from "node:path";
import type { Command } from "commander";
import { connectToDaemon, getDaemonHost } from "../../utils/client.js";
import { resolveCallerAgentId } from "../../utils/caller-agent.js";
import type { DaemonTarget } from "../../utils/daemon-target.js";
import type { CommandError, CommandOptions, SingleResult } from "../../output/index.js";
import { toWorkspaceRow, workspaceSchema, type WorkspaceRow } from "./shared.js";
@@ -121,12 +125,26 @@ function buildWorktreeWorkspaceSource(options: WorkspaceCreateOptions, path: str
}
}
// A relative --path names a directory relative to where the command runs, so
// it is made absolute here for a local daemon, which would otherwise resolve
// it against its own working directory. For an explicit endpoint the path is
// sent as written, the same rule as resolveRepositoryDirectory. An absolute
// path can target a daemon on a different operating system, and the daemon
// expands a leading ~ to its own home directory.
function resolveCallerPath(input: string, daemonTarget: DaemonTarget): string {
const isHomeRelative = input === "~" || input.startsWith("~/");
if (isHomeRelative || isPosixAbsolute(input) || isWindowsAbsolute(input)) return input;
return daemonTarget.kind === "instance" ? resolve(input) : input;
}
export function buildWorkspaceSource(options: WorkspaceCreateOptions) {
const callerPath =
options.path === undefined ? undefined : resolveCallerPath(options.path, options.daemonTarget);
if (options.isolation === "local") {
return buildLocalWorkspaceSource(options, options.path ?? process.cwd());
return buildLocalWorkspaceSource(options, callerPath ?? process.cwd());
}
if (options.isolation === "worktree") {
const sourcePath = options.path ?? (options.project ? undefined : process.cwd());
const sourcePath = callerPath ?? (options.project ? undefined : process.cwd());
return buildWorktreeWorkspaceSource(options, sourcePath);
}
throw new Error(`Unsupported workspace isolation: ${String(options.isolation)}`);
@@ -3473,6 +3473,101 @@ test("cancelAgentRun succeeds when the provider queues completion before rejecti
}
});
test.each([
{ binding: "foreground", agentId: "00000000-0000-4000-8000-000000000307" },
{ binding: "autonomous", agentId: "00000000-0000-4000-8000-000000000308" },
] as const)(
"cancelAgentRun settles a $binding run bound to an already finalized turn",
async ({ binding, agentId }) => {
const fixture = await createControlledInterruptFixture({
name: `interrupt-finalized-${binding}`,
agentId,
turnId: "finalized-turn",
interrupt: async () => {},
});
try {
await fixture.startForegroundRun();
await expect(fixture.manager.cancelAgentRun(fixture.agentId)).resolves.toEqual({
status: "settled",
});
if (binding === "foreground") {
await fixture.startForegroundRun();
} else {
const running = waitForAgentLifecycle(fixture.manager, fixture.agentId, "running");
fixture.session.pushEvent({
type: "turn_started",
provider: "codex",
turnId: "finalized-turn",
});
await running;
}
const cancellation = await Promise.race([
fixture.manager.cancelAgentRun(fixture.agentId),
new Promise<"pending">((resolve) => setTimeout(() => resolve("pending"), 3_000)),
]);
expect(cancellation).toEqual({ status: "settled" });
expect(fixture.manager.getAgent(fixture.agentId)).toMatchObject({
lifecycle: "idle",
activeForegroundTurnId: null,
});
await expect(fixture.manager.cancelAgentRun(fixture.agentId)).resolves.toEqual({
status: "not_running",
});
await fixture.startForegroundRun();
expect(fixture.manager.getAgent(fixture.agentId)).toMatchObject({
lifecycle: "running",
activeForegroundTurnId: "finalized-turn",
});
} finally {
await fixture.cleanup();
}
},
10_000,
);
test("the provider's terminal for a run bound to an already finalized turn settles the run", async () => {
const fixture = await createControlledInterruptFixture({
name: "interrupt-finalized-provider-terminal",
agentId: "00000000-0000-4000-8000-000000000309",
turnId: "finalized-provider-terminal-turn",
interrupt: async () => {},
});
try {
await fixture.startForegroundRun();
await expect(fixture.manager.cancelAgentRun(fixture.agentId)).resolves.toEqual({
status: "settled",
});
await fixture.startForegroundRun();
const idle = waitForAgentLifecycle(fixture.manager, fixture.agentId, "idle");
fixture.session.pushEvent({
type: "turn_completed",
provider: "codex",
turnId: "finalized-provider-terminal-turn",
});
const settlement = await Promise.race([
idle.then(() => "idle" as const),
new Promise<"pending">((resolve) => setTimeout(() => resolve("pending"), 1_000)),
]);
expect(settlement).toBe("idle");
expect(fixture.manager.getAgent(fixture.agentId)).toMatchObject({
lifecycle: "idle",
activeForegroundTurnId: null,
});
await expect(fixture.manager.cancelAgentRun(fixture.agentId)).resolves.toEqual({
status: "not_running",
});
} finally {
await fixture.cleanup();
}
}, 10_000);
test("listProviderAvailability uses registered client keys, including custom providers", async () => {
const customClient: AgentClient = {
provider: "zai",
@@ -5132,7 +5132,8 @@ export class AgentManager {
if (
eventTurnId &&
isTurnTerminalEvent(event) &&
this.runs.hasFinalizedTurn(agent, eventTurnId)
this.runs.hasFinalizedTurn(agent, eventTurnId) &&
this.runs.getTurnId(agent.id) !== eventTurnId
) {
return false;
}
@@ -123,7 +123,8 @@ test.each(["mode", "model", "commands"] as const)(
try {
await session.startTurn("Run the foreground command");
await running.promise;
expect(await session.setThinkingOption?.("medium")).toMatchObject({
// Ultracode is launched with the query, so the change waits for a restart.
expect(await session.setThinkingOption?.("ultracode")).toMatchObject({
message: "Thinking level applies next turn",
});
if (control === "mode") await session.setMode("acceptEdits");
@@ -149,7 +150,7 @@ test.each(["mode", "model", "commands"] as const)(
await session.startTurn("Run another command with the new thinking level");
queries[1].work.resolve();
expect(await terminal.promise).toBe("turn_completed");
expect(efforts).toEqual(["low", "medium"]);
expect(efforts).toEqual(["low", "xhigh"]);
} finally {
await session.close();
}
@@ -44,6 +44,7 @@ function createQueryMock(events: unknown[], options: QueryMockOptions = {}): Que
close: vi.fn(() => undefined),
setPermissionMode: vi.fn(async () => undefined),
setModel: vi.fn(async () => undefined),
applyFlagSettings: vi.fn(async () => undefined),
supportedModels: vi.fn(async () => [{ value: "opus", displayName: "Opus" }]),
supportedCommands: vi.fn(async () => []),
rewindFiles: vi.fn(async () => ({ canRewind: true })),
@@ -382,6 +383,84 @@ describe("Claude runtime exit", () => {
}
});
test("keeps the process and its background work when the effort level changes", async () => {
let capturedOptions: Options | undefined;
const child = createChildProcessStub();
const query = createQueryMock(BACKGROUND_SHELL_TURN_EVENTS, {
tail: new Promise<never>(() => undefined),
onReturn: () => child.emit("exit", 0, null),
});
const queryFactory = vi.fn(({ options }: ClaudeQueryInput) => {
capturedOptions = options;
return query;
});
vi.spyOn(spawnUtils, "spawnProcess").mockReturnValue(child);
const client = new ClaudeAgentClient({
logger: createTestLogger(),
queryFactory,
resolveBinary: async () => "/test/claude/bin",
});
const session = await client.createSession({
provider: "claude",
cwd: process.cwd(),
thinkingOptionId: "low",
});
try {
await session.run("start a background shell");
capturedOptions?.spawnClaudeCodeProcess?.(SPAWN_OPTIONS);
const events: AgentStreamEvent[] = [];
session.subscribe((event) => events.push(event));
await expect(session.setThinkingOption?.("high")).resolves.toBeUndefined();
// A pending restart would be carried out here.
await session.listCommands();
expect(query.applyFlagSettings).toHaveBeenCalledWith({ effortLevel: "high" });
expect(queryFactory).toHaveBeenCalledTimes(1);
expect(query.return).not.toHaveBeenCalled();
expect(child.killSignals).toEqual([]);
expect(events).not.toContainEqual(
expect.objectContaining({ type: "background_work", provider: "claude", items: null }),
);
} finally {
await session.close();
}
});
test("restarts with the new effort level when the running process does not take it", async () => {
const efforts: Options["effort"][] = [];
const queryFactory = vi.fn(({ options }: ClaudeQueryInput) => {
efforts.push(options.effort);
const query = createQueryMock(BACKGROUND_SHELL_TURN_EVENTS, {
tail: new Promise<never>(() => undefined),
});
vi.mocked(query.applyFlagSettings).mockRejectedValue(new Error("unsupported"));
return query;
});
vi.spyOn(spawnUtils, "spawnProcess").mockReturnValue(createChildProcessStub());
const client = new ClaudeAgentClient({
logger: createTestLogger(),
queryFactory,
resolveBinary: async () => "/test/claude/bin",
});
const session = await client.createSession({
provider: "claude",
cwd: process.cwd(),
thinkingOptionId: "low",
});
try {
await session.run("start a background shell");
await session.setThinkingOption?.("high");
await session.listCommands();
expect(efforts).toEqual(["low", "high"]);
} finally {
await session.close();
}
});
test("ignores background work a retired query reports after its restart", async () => {
let capturedOptions: Options | undefined;
let deliverLateEvent: ((event: unknown) => void) | undefined;
@@ -2859,6 +2859,7 @@ class ClaudeAgentSession implements AgentSession {
? thinkingOptionId
: null;
const previousThinkingOptionId = this.config.thinkingOptionId;
if (!normalizedThinkingOptionId || normalizedThinkingOptionId === "default") {
this.config.thinkingOptionId = undefined;
} else if (isClaudeThinkingOption(normalizedThinkingOptionId)) {
@@ -2867,12 +2868,35 @@ class ClaudeAgentSession implements AgentSession {
} else {
throw new Error(`Unknown thinking option: ${normalizedThinkingOptionId}`);
}
this.queryRestartNeeded = true;
if (!(await this.applyEffortToRunningQuery(previousThinkingOptionId))) {
this.queryRestartNeeded = true;
}
if (this.activeForegroundTurnId || this.autonomousTurn) {
return THINKING_APPLIES_NEXT_TURN_NOTICE;
}
}
// A move between two effort levels changes only the effort, which a running Claude process
// takes through flag settings, so the process and its background work stay. Switching thinking
// off, to ultracode or back to the default changes how the query is launched, so it still
// restarts the query. The recorded option feeds every later launch either way.
private async applyEffortToRunningQuery(
previousThinkingOptionId: string | undefined,
): Promise<boolean> {
const effort = this.config.thinkingOptionId;
if (!this.query || this.queryRestartNeeded) return false;
if (!isClaudeThinkingEffort(previousThinkingOptionId) || !isClaudeThinkingEffort(effort)) {
return false;
}
try {
await this.query.applyFlagSettings({ effortLevel: effort });
return true;
} catch (error) {
this.logger.warn({ err: error, effort }, "Claude did not take a live effort change");
return false;
}
}
async applyOptions(options: ProviderOptions): Promise<void> {
// Every option but Fast is read when the query is built, and replacing a started query would
// end its background work, so once it exists only Fast can change.
@@ -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 });
}, 60_000);
}, 20_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" | "restore-commit" }
{ kind: "restore" | "restore-from-base" }
>;
export interface ResolveWorktreeCreationIntentInput {
@@ -335,15 +335,11 @@ async function createBaseRecoveryFixture(baseBranch: string | null) {
await registry.update(record.workspaceId, (value) => ({ ...value, archivedAt: null }));
},
});
async function archiveAndRemove(legacy = false) {
if (legacy) {
await registry.archive(workspace.workspaceId, new Date().toISOString());
} else {
await archivePersistedWorkspaceRecord({
workspaceId: workspace.workspaceId,
workspaceRegistry: registry,
});
}
async function archiveAndRemove() {
await archivePersistedWorkspaceRecord({
workspaceId: workspace.workspaceId,
workspaceRegistry: registry,
});
await deletePaseoWorktree({ cwd: repoDir, worktreePath: workspace.cwd, paseoHome });
expect(existsSync(workspace.cwd)).toBe(false);
}
@@ -361,134 +357,6 @@ 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" });
@@ -500,7 +368,7 @@ test("restores a branchless workspace from its recorded base so work can continu
...workspace,
branch: null,
}));
await fixture.archiveAndRemove(true);
await fixture.archiveAndRemove();
await expect(fixture.service.inspect(fixture.workspace.workspaceId)).resolves.toMatchObject({
kind: "recoverable",
@@ -534,7 +402,7 @@ test("restores a branchless workspace from the repository default when its base
...workspace,
branch: null,
}));
await fixture.archiveAndRemove(true);
await fixture.archiveAndRemove();
await expect(fixture.service.restore(fixture.workspace.workspaceId)).resolves.toEqual({
workspaceId: fixture.workspace.workspaceId,
@@ -550,44 +418,6 @@ 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,27 +151,13 @@ export function createWorkspaceRecoveryService(deps: {
workspace: PersistedWorkspaceRecord,
sourceRepoRoot: string,
): Promise<void> {
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),
};
}
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 });
@@ -265,29 +251,16 @@ 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: checkout.kind === "branch" ? checkout.branch : null,
branch: input.workspace.branch,
};
if (input.action === "restore") {
return {
@@ -8,7 +8,6 @@ import type { WorkspaceGitService } from "./workspace-git-service.js";
import type { ForgeService } from "../services/forge-service.js";
import {
deletePaseoWorktree,
readWorktreeHeadReference,
isPaseoOwnedWorktreeCwd,
runWorktreeTeardownCommands,
WorktreeTeardownError,
@@ -708,15 +707,7 @@ export async function archivePersistedWorkspaceRecord(input: {
}
const archivedAt = input.archivedAt ?? new Date().toISOString();
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 } : {}),
});
await input.workspaceRegistry.archive(input.workspaceId, archivedAt, input.context);
return existingWorkspace;
}
@@ -151,40 +151,6 @@ 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,7 +72,6 @@ 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
@@ -127,7 +126,6 @@ export interface WorkspaceMutationContext {
export interface WorkspaceArchiveContext {
autoArchivedChangeRequestUrl?: string;
head?: string;
}
export interface ProjectMutation {
@@ -588,7 +586,6 @@ export class FileBackedWorkspaceRegistry
...existing,
updatedAt: archivedAt,
archivedAt,
head: context?.head,
...(context?.autoArchivedChangeRequestUrl
? { autoArchivedChangeRequestUrl: context.autoArchivedChangeRequestUrl }
: {}),
@@ -1406,32 +1406,6 @@ 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,7 +3,6 @@ import {
createWorktree as createWorktreePrimitive,
deriveWorktreeProjectHash,
deletePaseoWorktree,
readWorktreeHead,
isPaseoOwnedWorktreeCwd,
mapWorkspaceCwdToWorktree,
runWorktreeTeardownCommands,
@@ -303,29 +302,6 @@ 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",
+6 -69
View File
@@ -188,7 +188,6 @@ 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";
@@ -1154,32 +1153,6 @@ 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,
@@ -1235,12 +1208,6 @@ 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) {
@@ -1394,22 +1361,14 @@ export async function resolveDefaultWorktreePath(
/**
* Create a git worktree with proper naming conventions
*/
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({
export const createWorktree = async ({
cwd,
source,
worktreeSlug,
paseoHome,
worktreesRoot,
worktreePath: explicitWorktreePath,
}: CreateWorktreeOptions): Promise<
Omit<CreatedWorktree, "branchName"> & { branchName: string | null }
> {
}: CreateWorktreeOptions): Promise<CreatedWorktree> => {
const branchesBefore =
source.kind === "checkout-branch" ||
source.kind === "checkout-change-request" ||
@@ -1435,14 +1394,14 @@ export async function createWorktree({
});
worktreePath = await normalizePathForOwnership(worktreePath);
if (sourcePlan.pushRemote && sourcePlan.branchName) {
if (sourcePlan.pushRemote) {
await configureWorktreePushRemote({
cwd,
branchName: sourcePlan.branchName,
remote: sourcePlan.pushRemote,
});
}
if (sourcePlan.trackingRemote && sourcePlan.branchName) {
if (sourcePlan.trackingRemote) {
await configureWorktreeTrackingRemote({
cwd,
branchName: sourcePlan.branchName,
@@ -1475,7 +1434,7 @@ export async function createWorktree({
}
throw error;
}
}
};
interface ResolveWorktreeSourcePlanOptions {
cwd: string;
@@ -1484,7 +1443,7 @@ interface ResolveWorktreeSourcePlanOptions {
}
interface WorktreeSourcePlan {
branchName: string | null;
branchName: string;
// 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.
@@ -1533,26 +1492,6 @@ 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" }>,
@@ -1605,8 +1544,6 @@ 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": {