mirror of
https://github.com/getpaseo/paseo.git
synced 2026-11-18 14:25:25 +00:00
Compare commits
18
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2ee30f4164 | ||
|
|
ac54c07639 | ||
|
|
46bd5d8a3e | ||
|
|
9895e0c957 | ||
|
|
2e9921e0e0 | ||
|
|
b1a2a50d50 | ||
|
|
9493a4f436 | ||
|
|
a87bd7fc0c | ||
|
|
527be52f2b | ||
|
|
fa6c50063e | ||
|
|
d364dbecb5 | ||
|
|
8edd1f407d | ||
|
|
f284e9abe5 | ||
|
|
c5bfe79c33 | ||
|
|
8d66a7c52e | ||
|
|
7a5b8e68e3 | ||
|
|
d577594173 | ||
|
|
293fbf825d |
@@ -1,5 +1,26 @@
|
||||
# Changelog
|
||||
|
||||
## 0.16.2 - 2026-11-18
|
||||
|
||||
### Fixed
|
||||
|
||||
- Fixed Collapse turns hiding a finished reply when Claude answers a later background task notification ([#10092](https://github.com/getpaseo/paseo/pull/10092))
|
||||
- Fixed detached worktree commits getting lost when archiving a workspace ([#10009](https://github.com/getpaseo/paseo/pull/10009) by [@ragokan](https://github.com/ragokan))
|
||||
- Fixed Desktop updates leaving an older daemon running when an earlier Desktop session started it ([#10067](https://github.com/getpaseo/paseo/pull/10067))
|
||||
- Fixed daemons losing their Hub connection after execution permissions changed ([#10113](https://github.com/getpaseo/paseo/pull/10113))
|
||||
- Fixed saved hosts disappearing when one stored entry could not be read ([#9847](https://github.com/getpaseo/paseo/pull/9847) by [@ragokan](https://github.com/ragokan))
|
||||
- Fixed worktree creation timing out while scanning large ignored folders that `.worktreeinclude` does not name ([#10020](https://github.com/getpaseo/paseo/pull/10020) by [@mgranderath](https://github.com/mgranderath))
|
||||
- Fixed Steer cancelling a Claude compaction in progress ([#10028](https://github.com/getpaseo/paseo/pull/10028) by [@NightMachinery](https://github.com/NightMachinery))
|
||||
- Fixed agents getting stuck after a second Stop when the provider reused the cancelled turn ID ([#9774](https://github.com/getpaseo/paseo/pull/9774) by [@DAnaeto](https://github.com/DAnaeto))
|
||||
- Fixed Desktop staying blank after its renderer exited unexpectedly ([#10035](https://github.com/getpaseo/paseo/pull/10035))
|
||||
- Fixed failed file downloads taking over the app window on web and Desktop ([#9937](https://github.com/getpaseo/paseo/pull/9937) by [@panta82](https://github.com/panta82))
|
||||
- Fixed Import Session losing its scroll position when you select Load more ([#9974](https://github.com/getpaseo/paseo/pull/9974))
|
||||
- Fixed terminals failing to open when the home filesystem refuses Unix sockets, such as on AFS ([#9214](https://github.com/getpaseo/paseo/pull/9214) by [@bendavid](https://github.com/bendavid))
|
||||
- Fixed timed-out Git watchers repeatedly rescanning large repositories ([#9828](https://github.com/getpaseo/paseo/pull/9828) by [@Spshulem](https://github.com/Spshulem))
|
||||
- Fixed `paseo workspace create --path .` using the local daemon's directory instead of the caller's ([#10010](https://github.com/getpaseo/paseo/pull/10010))
|
||||
- Fixed MCP agent status and list responses omitting background work for idle agents ([#10022](https://github.com/getpaseo/paseo/pull/10022) by [@ortschun](https://github.com/ortschun))
|
||||
- Fixed the thinking selector showing an old level after OMP changes it ([#9841](https://github.com/getpaseo/paseo/pull/9841) by [@dsingal0](https://github.com/dsingal0))
|
||||
|
||||
## 0.16.1 - 2026-11-17
|
||||
|
||||
### Fixed
|
||||
|
||||
@@ -1,5 +1,26 @@
|
||||
# Changelog
|
||||
|
||||
## 0.16.2 - 2026-11-18
|
||||
|
||||
### 修复
|
||||
|
||||
- 修复启用“折叠轮次”时,Claude 回复后续后台任务通知导致上一条已完成的回复被折叠的问题 ([#10092](https://github.com/getpaseo/paseo/pull/10092))
|
||||
- 修复归档工作区时丢失分离 HEAD 的 worktree 提交的问题 ([#10009](https://github.com/getpaseo/paseo/pull/10009),贡献者:[@ragokan](https://github.com/ragokan))
|
||||
- 修复 Desktop 更新后,由上一次 Desktop 会话启动的旧版 daemon 仍在运行的问题 ([#10067](https://github.com/getpaseo/paseo/pull/10067))
|
||||
- 修复更改执行权限后 daemon 与 Hub 断开连接的问题 ([#10113](https://github.com/getpaseo/paseo/pull/10113))
|
||||
- 修复一条已保存的主机记录无法读取时,其他主机也消失的问题 ([#9847](https://github.com/getpaseo/paseo/pull/9847),贡献者:[@ragokan](https://github.com/ragokan))
|
||||
- 修复创建 worktree 时,扫描 `.worktreeinclude` 未指定的大型忽略目录导致超时的问题 ([#10020](https://github.com/getpaseo/paseo/pull/10020),贡献者:[@mgranderath](https://github.com/mgranderath))
|
||||
- 修复发送引导消息时取消 Claude 正在进行的上下文压缩的问题 ([#10028](https://github.com/getpaseo/paseo/pull/10028),贡献者:[@NightMachinery](https://github.com/NightMachinery))
|
||||
- 修复 Provider 重用已取消的轮次 ID 时,再次停止导致 Agent 卡住的问题 ([#9774](https://github.com/getpaseo/paseo/pull/9774),贡献者:[@DAnaeto](https://github.com/DAnaeto))
|
||||
- 修复 Desktop 渲染进程意外退出后窗口一直空白的问题 ([#10035](https://github.com/getpaseo/paseo/pull/10035))
|
||||
- 修复 Web 和 Desktop 上文件下载失败时,错误页面占据应用窗口的问题 ([#9937](https://github.com/getpaseo/paseo/pull/9937),贡献者:[@panta82](https://github.com/panta82))
|
||||
- 修复在“导入会话”中选择“加载更多”时丢失滚动位置的问题 ([#9974](https://github.com/getpaseo/paseo/pull/9974))
|
||||
- 修复主目录所在的文件系统拒绝 Unix 套接字时无法打开终端的问题,例如 AFS ([#9214](https://github.com/getpaseo/paseo/pull/9214),贡献者:[@bendavid](https://github.com/bendavid))
|
||||
- 修复 Git 监视器设置超时后反复扫描大型仓库的问题 ([#9828](https://github.com/getpaseo/paseo/pull/9828),贡献者:[@Spshulem](https://github.com/Spshulem))
|
||||
- 修复 `paseo workspace create --path .` 使用本地 daemon 的目录而非命令所在目录的问题 ([#10010](https://github.com/getpaseo/paseo/pull/10010))
|
||||
- 修复针对空闲 Agent 查询 MCP 状态或列表时漏报后台任务的问题 ([#10022](https://github.com/getpaseo/paseo/pull/10022),贡献者:[@ortschun](https://github.com/ortschun))
|
||||
- 修复 OMP 更改思考级别后,选择器仍显示旧级别的问题 ([#9841](https://github.com/getpaseo/paseo/pull/9841),贡献者:[@dsingal0](https://github.com/dsingal0))
|
||||
|
||||
## 0.16.1 - 2026-11-17
|
||||
|
||||
### 修复
|
||||
|
||||
@@ -506,5 +506,5 @@ Agent and terminal environments are unchanged. System proxy settings and SOCKS-o
|
||||
## Deployment models
|
||||
|
||||
1. **Local daemon** (default): `paseo daemon start` on `127.0.0.1:6767`
|
||||
2. **Managed desktop**: Electron uses the server package’s local-instance lifecycle capability for sanitized launch, published readiness, and captured-PID stop. Only a matching `{pid, startedAt}` from a spawn in the current Desktop session authorizes automatic stop or binary replacement. Preexisting instances, including legacy `desktopManaged` records, are attach-only. Keep-running survivors attach in the next session. Explicit attached Stop requires a confirmation naming the captured home/PID. Ordinary Restart uses the worker RPC on every app platform.
|
||||
2. **Managed desktop**: Electron uses the server package’s local-instance lifecycle capability for sanitized launch, published readiness, and captured-PID stop. Only Desktop's own launch writes `desktopManaged: true` to `paseo.pid`. The CLI launch path removes the flag. While Desktop manages the built-in daemon, an app update or a version mismatch replaces any `desktopManaged` daemon, including one that an earlier Desktop session left running. Bundled CLIs before v0.9.0 exported the flag, so a daemon that one of them started also carries it and is replaced. Quit, Settings, and host removal stop only a daemon that the current session launched, matched by `{pid, startedAt}`. A daemon that the user started through the CLI is attach-only. Explicit attached Stop requires a confirmation naming the captured home/PID. Ordinary Restart uses the worker RPC on every app platform.
|
||||
3. **Remote + relay**: Daemon behind firewall, relay bridges with E2E encryption
|
||||
|
||||
@@ -590,6 +590,16 @@ bookkeeping may scan opaque row sizes during a deferred write, never during host
|
||||
before a requested cache row can paint. The row store is not encrypted. A cached timeline can contain
|
||||
source code, prompts, and tool output; encrypted-at-rest storage is a separate security decision.
|
||||
|
||||
### Saved hosts
|
||||
|
||||
**AsyncStorage key:** `@paseo:daemon-registry`, an array of host profiles.
|
||||
|
||||
Every app build on a device shares this key, including an older build after a downgrade and a newer
|
||||
one that saves a connection kind this build doesn't know. The key holds every saved host and its
|
||||
password, so never remove it. Read each host and connection on its own, skip the ones this build
|
||||
can't read, and write them back on every save. A value that isn't a JSON array is copied to
|
||||
`@paseo:daemon-registry:unreadable` before the next save overwrites it.
|
||||
|
||||
### Draft Store
|
||||
|
||||
**AsyncStorage key:** `paseo-drafts` (version 2)
|
||||
|
||||
@@ -6,7 +6,7 @@ Do not replace the Linux implementation with `fs.watch({ recursive: true })`. No
|
||||
|
||||
Closing an observation must remain safe after its root is renamed or removed. Workspace archive removes owned worktrees while releasing observation references, so teardown cannot assume the watched path still exists.
|
||||
|
||||
`unsubscribe()` is an awaited barrier. Once it resolves, no scan, reconciliation, queued event, native handle, or callback may remain. `updateIgnore()` is the equivalent barrier for excluded paths: events queued below a newly excluded root cannot be delivered after it resolves. Treat path disappearance while scanning, attaching, or receiving a watcher error as rename/archive churn. Surface permission and resource errors so WorkspaceGit can enter bounded polling.
|
||||
`unsubscribe()` is an awaited barrier. Once it resolves, no scan, reconciliation, queued event, native handle, or callback may remain. `updateIgnore()` is the equivalent barrier for excluded paths: events queued below a newly excluded root cannot be delivered after it resolves. Treat path disappearance while scanning, attaching, or receiving a watcher error as rename/archive churn. Surface permission and resource errors so WorkspaceGit can enter bounded polling. `subscribe()` accepts an abort signal; aborting it before it resolves stops the startup scan and rejects. WorkspaceGit aborts every subscription that misses its setup deadline, because an abandoned scan otherwise keeps walking the tree. A timed-out directory retries on the recovery ladder (30 seconds doubling to five minutes), and each consecutive timeout keeps doubling the delay up to one hour. Under sustained CPU load the next scan misses the deadline too, and each attempt repeats the full scan. An accepted subscription resets the timeout streak. Degraded polling keeps its own cadence throughout.
|
||||
|
||||
Linux topology repair is trailing-debounced and scoped to the renamed path. A file rename needs one classification stat; a new or moved directory scans only its subtree. Full-tree scans are reserved for startup and ignore-set replacement. A subscription reports changes after `subscribe()` resolves, not the files that already existed. macOS FSEvents can still replay writes made moments before the stream started. Consumers read their initial state after `subscribe()` resolves; WorkspaceGit re-reads its checkout once observation setup completes, because its first refresh runs in parallel with setup. The Linux startup scan therefore emits nothing; only a scoped reconciliation of new topology reports files found before their directory's watcher was installed. Startup creates made every cold diff compute and discard a first revision. Benchmark startup cost with pre-populated trees.
|
||||
|
||||
|
||||
@@ -29,6 +29,7 @@ The worker writes `$PASEO_HOME/terminal-worker/<pid>.json` (owner-only) with its
|
||||
- Workers never query their own birth time or command line. Readers accept legacy identity fields but ignore them. Daemons through 0.15.1 report new records unreadable and cannot adopt them.
|
||||
- Windows terminal programs have no recorded birth time and terminal lifecycle operations never launch PowerShell. Linux and macOS retain program birth-time checks through `ps` with `LC_ALL=C`; Linux also walks sessions to find surviving jobs.
|
||||
- Unix socket paths have a byte budget (103 on macOS, 107 on Linux). Long dev homes use an owner-only fallback under `$TMPDIR/paseo-<uid>/` or `/tmp/paseo-<uid>/`. An existing directory must be a real `0700` directory owned by you; a shared root is never chmodded.
|
||||
- A home on a filesystem that refuses Unix sockets (AFS, some network mounts) passes those checks and then fails the bind with `EPERM`, `EACCES`, `EOPNOTSUPP` or `ENOTSUP`. The worker moves on to the next directory on those codes only; any other listen error fails the start. The record carries the path the worker bound, so nothing else recomputes it.
|
||||
- A kill cleanup that cannot confirm every process gone writes `closing-<recordId>.json` beside the worker record. The worker rewrites its own record whenever a terminal starts or exits, so the kill intent has to live in a file it never writes. A closing record is never adopted; the next stop or start retries it.
|
||||
- An unreadable record of either kind makes `daemon status` and a kill restart fail with its path: a kill cleanup that met it could not check what it names, and leaves nothing else behind. A read that fails with `EPERM`, `EBUSY` or `EACCES` is retried for 250ms first: on Windows, opening a record while the worker renames its new copy over it fails that way for a moment.
|
||||
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
Fixed
|
||||
- Fixed Collapse turns hiding a finished reply when Claude answers a later background task notification
|
||||
- Fixed detached worktree commits getting lost when archiving a workspace
|
||||
- Fixed Desktop updates leaving an older daemon running when an earlier Desktop session started it
|
||||
- Fixed daemons losing their Hub connection after execution permissions changed
|
||||
- Fixed saved hosts disappearing when one stored entry could not be read
|
||||
|
||||
Full notes: https://paseo.sh/changelog
|
||||
@@ -0,0 +1,8 @@
|
||||
Fixed
|
||||
- Fixed Collapse turns hiding a finished reply when Claude answers a later background task notification
|
||||
- Fixed detached worktree commits getting lost when archiving a workspace
|
||||
- Fixed Desktop updates leaving an older daemon running when an earlier Desktop session started it
|
||||
- Fixed daemons losing their Hub connection after execution permissions changed
|
||||
- Fixed saved hosts disappearing when one stored entry could not be read
|
||||
|
||||
Full notes: https://paseo.sh/changelog
|
||||
@@ -0,0 +1,8 @@
|
||||
Fixed
|
||||
- Fixed Collapse turns hiding a finished reply when Claude answers a later background task notification
|
||||
- Fixed detached worktree commits getting lost when archiving a workspace
|
||||
- Fixed Desktop updates leaving an older daemon running when an earlier Desktop session started it
|
||||
- Fixed daemons losing their Hub connection after execution permissions changed
|
||||
- Fixed saved hosts disappearing when one stored entry could not be read
|
||||
|
||||
Full notes: https://paseo.sh/changelog
|
||||
@@ -0,0 +1,8 @@
|
||||
Fixed
|
||||
- Fixed Collapse turns hiding a finished reply when Claude answers a later background task notification
|
||||
- Fixed detached worktree commits getting lost when archiving a workspace
|
||||
- Fixed Desktop updates leaving an older daemon running when an earlier Desktop session started it
|
||||
- Fixed daemons losing their Hub connection after execution permissions changed
|
||||
- Fixed saved hosts disappearing when one stored entry could not be read
|
||||
|
||||
Full notes: https://paseo.sh/changelog
|
||||
Generated
+28
-28
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "paseo",
|
||||
"version": "0.16.1",
|
||||
"version": "0.16.2",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "paseo",
|
||||
"version": "0.16.1",
|
||||
"version": "0.16.2",
|
||||
"hasInstallScript": true,
|
||||
"license": "Apache-2.0",
|
||||
"workspaces": [
|
||||
@@ -37468,7 +37468,7 @@
|
||||
},
|
||||
"packages/app": {
|
||||
"name": "@getpaseo/app",
|
||||
"version": "0.16.1",
|
||||
"version": "0.16.2",
|
||||
"dependencies": {
|
||||
"@codemirror/commands": "6.10.4",
|
||||
"@codemirror/language": "6.12.4",
|
||||
@@ -39637,13 +39637,13 @@
|
||||
},
|
||||
"packages/cli": {
|
||||
"name": "@getpaseo/cli",
|
||||
"version": "0.16.1",
|
||||
"version": "0.16.2",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@clack/prompts": "^1.0.0",
|
||||
"@getpaseo/client": "0.16.1",
|
||||
"@getpaseo/protocol": "0.16.1",
|
||||
"@getpaseo/server": "0.16.1",
|
||||
"@getpaseo/client": "0.16.2",
|
||||
"@getpaseo/protocol": "0.16.2",
|
||||
"@getpaseo/server": "0.16.2",
|
||||
"chalk": "^5.3.0",
|
||||
"commander": "^12.0.0",
|
||||
"mime-types": "^2.1.35",
|
||||
@@ -39890,11 +39890,11 @@
|
||||
},
|
||||
"packages/client": {
|
||||
"name": "@getpaseo/client",
|
||||
"version": "0.16.1",
|
||||
"version": "0.16.2",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@getpaseo/protocol": "0.16.1",
|
||||
"@getpaseo/relay": "0.16.1",
|
||||
"@getpaseo/protocol": "0.16.2",
|
||||
"@getpaseo/relay": "0.16.2",
|
||||
"ws": "^8.20.0",
|
||||
"zod": "^4.4.3"
|
||||
},
|
||||
@@ -39906,7 +39906,7 @@
|
||||
},
|
||||
"packages/desktop": {
|
||||
"name": "@getpaseo/desktop",
|
||||
"version": "0.16.1",
|
||||
"version": "0.16.2",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@getpaseo/cli": "*",
|
||||
@@ -40149,7 +40149,7 @@
|
||||
},
|
||||
"packages/expo-two-way-audio": {
|
||||
"name": "@getpaseo/expo-two-way-audio",
|
||||
"version": "0.16.1",
|
||||
"version": "0.16.2",
|
||||
"license": "MIT",
|
||||
"devDependencies": {
|
||||
"@types/jest": "^29.5.14",
|
||||
@@ -40195,7 +40195,7 @@
|
||||
},
|
||||
"packages/highlight": {
|
||||
"name": "@getpaseo/highlight",
|
||||
"version": "0.16.1",
|
||||
"version": "0.16.2",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@codemirror/language": "6.12.4",
|
||||
@@ -40225,7 +40225,7 @@
|
||||
},
|
||||
"packages/plugin": {
|
||||
"name": "@getpaseo/plugin",
|
||||
"version": "0.16.1",
|
||||
"version": "0.16.2",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@agentclientprotocol/sdk": "^1.4.0",
|
||||
@@ -40233,8 +40233,8 @@
|
||||
"use-sync-external-store": "^1.6.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@getpaseo/client": "0.16.1",
|
||||
"@getpaseo/protocol": "0.16.1",
|
||||
"@getpaseo/client": "0.16.2",
|
||||
"@getpaseo/protocol": "0.16.2",
|
||||
"@types/node": "^20.9.0",
|
||||
"@types/react": "~19.2.0",
|
||||
"react": "19.2.3",
|
||||
@@ -40244,8 +40244,8 @@
|
||||
"zod": "^4.4.3"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@getpaseo/client": "0.16.1",
|
||||
"@getpaseo/protocol": "0.16.1",
|
||||
"@getpaseo/client": "0.16.2",
|
||||
"@getpaseo/protocol": "0.16.2",
|
||||
"react": ">=19.1.0 <20",
|
||||
"react-native": ">=0.81.5",
|
||||
"zod": "^4.4.3"
|
||||
@@ -40267,7 +40267,7 @@
|
||||
},
|
||||
"packages/protocol": {
|
||||
"name": "@getpaseo/protocol",
|
||||
"version": "0.16.1",
|
||||
"version": "0.16.2",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"semver": "^7.8.5",
|
||||
@@ -40295,7 +40295,7 @@
|
||||
},
|
||||
"packages/relay": {
|
||||
"name": "@getpaseo/relay",
|
||||
"version": "0.16.1",
|
||||
"version": "0.16.2",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@noble/ciphers": "^2.4.0",
|
||||
@@ -40517,17 +40517,17 @@
|
||||
},
|
||||
"packages/server": {
|
||||
"name": "@getpaseo/server",
|
||||
"version": "0.16.1",
|
||||
"version": "0.16.2",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@agentclientprotocol/sdk": "^0.17.1",
|
||||
"@anthropic-ai/claude-agent-sdk": "0.3.326",
|
||||
"@anthropic-ai/sdk": "^0.104.2",
|
||||
"@getpaseo/client": "0.16.1",
|
||||
"@getpaseo/highlight": "0.16.1",
|
||||
"@getpaseo/plugin": "0.16.1",
|
||||
"@getpaseo/protocol": "0.16.1",
|
||||
"@getpaseo/relay": "0.16.1",
|
||||
"@getpaseo/client": "0.16.2",
|
||||
"@getpaseo/highlight": "0.16.2",
|
||||
"@getpaseo/plugin": "0.16.2",
|
||||
"@getpaseo/protocol": "0.16.2",
|
||||
"@getpaseo/relay": "0.16.2",
|
||||
"@isaacs/ttlcache": "^2.1.4",
|
||||
"@modelcontextprotocol/sdk": "1.29.0",
|
||||
"@opencode-ai/sdk": "1.14.46",
|
||||
@@ -41474,7 +41474,7 @@
|
||||
},
|
||||
"packages/website": {
|
||||
"name": "@getpaseo/website",
|
||||
"version": "0.16.1",
|
||||
"version": "0.16.2",
|
||||
"dependencies": {
|
||||
"@cloudflare/vite-plugin": "^1.29.1",
|
||||
"@cloudflare/workers-types": "^4.20260317.1",
|
||||
@@ -43084,7 +43084,7 @@
|
||||
},
|
||||
"plugins": {
|
||||
"name": "@getpaseo/builtin-plugins",
|
||||
"version": "0.16.1",
|
||||
"version": "0.16.2",
|
||||
"dependencies": {
|
||||
"@getpaseo/plugin": "*",
|
||||
"zod": "^4.4.3"
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "paseo",
|
||||
"version": "0.16.1",
|
||||
"version": "0.16.2",
|
||||
"private": true,
|
||||
"description": "Paseo: voice-controlled development environment for local AI coding agents",
|
||||
"keywords": [
|
||||
|
||||
@@ -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) => {
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
import { expect, type Page } from "@playwright/test";
|
||||
import { test } from "../support/fixtures";
|
||||
import { gotoAppShell, openSettings } from "../support/helpers/app";
|
||||
import { renameHostFromSettings } from "../support/helpers/hosts";
|
||||
import { getServerId } from "../support/helpers/server-id";
|
||||
import { openHostSection, selectSettingsHost } from "../support/helpers/settings";
|
||||
|
||||
const REGISTRY_KEY = "@paseo:daemon-registry";
|
||||
const SEED_NONCE_KEY = "@paseo:e2e-seed-nonce";
|
||||
const DISABLE_DEFAULT_SEED_ONCE_KEY = "@paseo:e2e-disable-default-seed-once";
|
||||
|
||||
// What a build with a connection kind this one doesn't know leaves in the registry: an extra
|
||||
// connection on a host this build can reach, and a host reached only through it.
|
||||
const UNKNOWN_CONNECTION = { id: "future:garage", type: "futureKind", address: "garage" };
|
||||
const UNKNOWN_HOST = {
|
||||
serverId: "srv_e2e_unknown_connection_host",
|
||||
label: "Unknown connection host",
|
||||
connections: [{ id: "future:roof", type: "futureKind", address: "roof" }],
|
||||
preferredConnectionId: "future:roof",
|
||||
};
|
||||
const OFFLINE_HOST = {
|
||||
serverId: "srv_e2e_saved_offline_host",
|
||||
label: "Saved offline host",
|
||||
password: "e2e-fake-password",
|
||||
connections: [{ id: "direct:127.0.0.1:59999", type: "directTcp", endpoint: "127.0.0.1:59999" }],
|
||||
preferredConnectionId: "direct:127.0.0.1:59999",
|
||||
};
|
||||
|
||||
interface StoredHost {
|
||||
serverId: string;
|
||||
label?: string;
|
||||
password?: string;
|
||||
connections: unknown[];
|
||||
}
|
||||
|
||||
async function addUnreadableEntriesAndReload(page: Page): Promise<void> {
|
||||
await page.evaluate(
|
||||
({ keys, primaryServerId, unknownConnection, offlineHost, unknownHost }) => {
|
||||
const nonce = localStorage.getItem(keys.nonce);
|
||||
if (!nonce) {
|
||||
throw new Error("Expected the e2e seed nonce before overriding the host registry.");
|
||||
}
|
||||
const registry: StoredHost[] = JSON.parse(localStorage.getItem(keys.registry) ?? "[]");
|
||||
registry
|
||||
.find((host) => host.serverId === primaryServerId)
|
||||
?.connections.push(unknownConnection);
|
||||
registry.push(offlineHost, unknownHost);
|
||||
localStorage.setItem(keys.registry, JSON.stringify(registry));
|
||||
localStorage.setItem(keys.disableSeedOnce, nonce);
|
||||
},
|
||||
{
|
||||
keys: {
|
||||
registry: REGISTRY_KEY,
|
||||
nonce: SEED_NONCE_KEY,
|
||||
disableSeedOnce: DISABLE_DEFAULT_SEED_ONCE_KEY,
|
||||
},
|
||||
primaryServerId: getServerId(),
|
||||
unknownConnection: UNKNOWN_CONNECTION,
|
||||
offlineHost: OFFLINE_HOST,
|
||||
unknownHost: UNKNOWN_HOST,
|
||||
},
|
||||
);
|
||||
await page.reload();
|
||||
}
|
||||
|
||||
async function readStoredRegistry(page: Page): Promise<StoredHost[] | null> {
|
||||
return page.evaluate((key) => JSON.parse(localStorage.getItem(key) ?? "null"), REGISTRY_KEY);
|
||||
}
|
||||
|
||||
async function readStoredHost(page: Page, serverId: string): Promise<StoredHost | undefined> {
|
||||
return (await readStoredRegistry(page))?.find((host) => host.serverId === serverId);
|
||||
}
|
||||
|
||||
test("saved hosts survive a registry entry this build can't read, and saving keeps it", async ({
|
||||
page,
|
||||
}) => {
|
||||
await gotoAppShell(page);
|
||||
await addUnreadableEntriesAndReload(page);
|
||||
|
||||
await test.step("both readable hosts are listed", async () => {
|
||||
await page.getByTestId("sidebar-hosts-trigger").click();
|
||||
await expect(page.getByTestId(`sidebar-host-row-${getServerId()}`)).toBeVisible();
|
||||
await expect(page.getByTestId(`sidebar-host-row-${OFFLINE_HOST.serverId}`)).toBeVisible();
|
||||
await expect(page.getByTestId(`sidebar-host-row-${UNKNOWN_HOST.serverId}`)).toHaveCount(0);
|
||||
await page.keyboard.press("Escape");
|
||||
});
|
||||
|
||||
await test.step("renaming a host keeps its password and the entries it can't read", async () => {
|
||||
await openSettings(page);
|
||||
await selectSettingsHost(page, OFFLINE_HOST.serverId);
|
||||
await openHostSection(page, OFFLINE_HOST.serverId, "host");
|
||||
await renameHostFromSettings(page, "Renamed offline host");
|
||||
|
||||
await expect
|
||||
.poll(() => readStoredHost(page, OFFLINE_HOST.serverId))
|
||||
.toMatchObject({ label: "Renamed offline host", password: OFFLINE_HOST.password });
|
||||
const stored = await readStoredRegistry(page);
|
||||
expect(stored?.map((host) => host.serverId)).toEqual([
|
||||
getServerId(),
|
||||
OFFLINE_HOST.serverId,
|
||||
UNKNOWN_HOST.serverId,
|
||||
]);
|
||||
expect(stored?.[0]?.connections).toContainEqual(UNKNOWN_CONNECTION);
|
||||
expect(stored?.[2]).toEqual(UNKNOWN_HOST);
|
||||
});
|
||||
});
|
||||
@@ -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);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@getpaseo/app",
|
||||
"version": "0.16.1",
|
||||
"version": "0.16.2",
|
||||
"private": true,
|
||||
"main": "index.ts",
|
||||
"scripts": {
|
||||
|
||||
@@ -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 });
|
||||
|
||||
@@ -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}}",
|
||||
},
|
||||
|
||||
@@ -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}}",
|
||||
},
|
||||
|
||||
@@ -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}}",
|
||||
},
|
||||
|
||||
@@ -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}}",
|
||||
},
|
||||
|
||||
@@ -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}}を共有",
|
||||
},
|
||||
|
||||
@@ -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}} 공유",
|
||||
},
|
||||
|
||||
@@ -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}}",
|
||||
},
|
||||
|
||||
@@ -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}}",
|
||||
},
|
||||
|
||||
@@ -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}}",
|
||||
},
|
||||
|
||||
@@ -2256,6 +2256,59 @@ describe("HostRuntimeController", () => {
|
||||
});
|
||||
});
|
||||
|
||||
const REGISTRY_KEY = "@paseo:daemon-registry";
|
||||
const futureConnection = { id: "future:1", type: "futureKind", address: "future.example.com" };
|
||||
const directA: HostConnection = {
|
||||
id: "direct:lan-a:6767",
|
||||
type: "directTcp",
|
||||
endpoint: "lan-a:6767",
|
||||
};
|
||||
const directB: HostConnection = {
|
||||
id: "direct:lan-b:6767",
|
||||
type: "directTcp",
|
||||
endpoint: "lan-b:6767",
|
||||
};
|
||||
// What a build with a connection kind this one doesn't know leaves behind: an extra connection
|
||||
// on a host this build can reach, and a host reached only through it.
|
||||
const storedWithUnreadableEntries = [
|
||||
{
|
||||
...makeHost({ serverId: "srv_a", password: "secret-a" }),
|
||||
connections: [futureConnection, directA],
|
||||
},
|
||||
makeHost({ serverId: "srv_b", password: "secret-b", connections: [directB] }),
|
||||
{ serverId: "srv_future", label: "future host", connections: [futureConnection] },
|
||||
];
|
||||
|
||||
async function bootWithRegistry(registry: string): Promise<{
|
||||
store: HostRuntimeStore;
|
||||
storage: HostRuntimeStorage;
|
||||
}> {
|
||||
const storage = createMemoryHostRuntimeStorage({
|
||||
[REGISTRY_KEY]: registry,
|
||||
"@paseo:e2e": "1",
|
||||
});
|
||||
const store = new HostRuntimeStore({
|
||||
storage,
|
||||
deps: {
|
||||
createClient: () => new FakeDaemonClient() as unknown as DaemonClient,
|
||||
connectToDaemon: async ({ host }) => ({
|
||||
client: makeConnectedProbeClient(5) as unknown as DaemonClient,
|
||||
serverId: host.serverId,
|
||||
hostname: host.label ?? null,
|
||||
}),
|
||||
getClientId: async () => "cid_test_runtime",
|
||||
},
|
||||
revokePushNotifications: async () => undefined,
|
||||
});
|
||||
await store.boot();
|
||||
return { store, storage };
|
||||
}
|
||||
|
||||
async function readRegistry(storage: HostRuntimeStorage): Promise<unknown> {
|
||||
const raw = await storage.getItem(REGISTRY_KEY);
|
||||
return raw === null ? null : JSON.parse(raw);
|
||||
}
|
||||
|
||||
describe("HostRuntimeStore", () => {
|
||||
function gatewayRecoveryFixture() {
|
||||
const parent = new FakeDaemonClient();
|
||||
@@ -2686,6 +2739,98 @@ describe("HostRuntimeStore", () => {
|
||||
session.clearSession(host.serverId);
|
||||
});
|
||||
|
||||
it("keeps readable hosts when the registry holds entries this build can't read", async () => {
|
||||
const { store, storage } = await bootWithRegistry(JSON.stringify(storedWithUnreadableEntries));
|
||||
|
||||
expect(store.getHosts().map((host) => [host.serverId, host.password])).toEqual([
|
||||
["srv_a", "secret-a"],
|
||||
["srv_b", "secret-b"],
|
||||
]);
|
||||
expect(store.getHosts()[0]?.connections.map((connection) => connection.id)).toEqual([
|
||||
directA.id,
|
||||
]);
|
||||
expect(await readRegistry(storage)).toEqual(storedWithUnreadableEntries);
|
||||
|
||||
store.syncHosts([]);
|
||||
});
|
||||
|
||||
it("keeps the entries it can't read when it saves the registry", async () => {
|
||||
const { store, storage } = await bootWithRegistry(JSON.stringify(storedWithUnreadableEntries));
|
||||
|
||||
await store.renameHost("srv_b", "renamed");
|
||||
|
||||
expect(await readRegistry(storage)).toMatchObject([
|
||||
{
|
||||
serverId: "srv_a",
|
||||
password: "secret-a",
|
||||
connections: [{ id: directA.id }, futureConnection],
|
||||
},
|
||||
{ serverId: "srv_b", password: "secret-b", label: "renamed" },
|
||||
storedWithUnreadableEntries[2],
|
||||
]);
|
||||
|
||||
store.syncHosts([]);
|
||||
});
|
||||
|
||||
it("moves a stored connection password to its host and keeps the connection it can't read", async () => {
|
||||
const { store, storage } = await bootWithRegistry(
|
||||
JSON.stringify([
|
||||
{
|
||||
serverId: "srv_legacy",
|
||||
connections: [
|
||||
{ type: "directTcp", endpoint: "lan-a:6767", password: "old-secret" },
|
||||
futureConnection,
|
||||
],
|
||||
},
|
||||
]),
|
||||
);
|
||||
|
||||
expect(store.getHosts().map((host) => [host.serverId, host.password])).toEqual([
|
||||
["srv_legacy", "old-secret"],
|
||||
]);
|
||||
await vi.waitFor(async () =>
|
||||
expect(await readRegistry(storage)).toMatchObject([
|
||||
{ serverId: "srv_legacy", password: "old-secret" },
|
||||
]),
|
||||
);
|
||||
expect(await readRegistry(storage)).toMatchObject([
|
||||
{ connections: [{ ...directA, useTls: false }, futureConnection] },
|
||||
]);
|
||||
const [written] = (await readRegistry(storage)) as Array<{ connections: unknown[] }>;
|
||||
expect(written?.connections[0]).not.toHaveProperty("password");
|
||||
|
||||
store.syncHosts([]);
|
||||
});
|
||||
|
||||
it("forgets an entry it can't read once that host is paired again and removed", async () => {
|
||||
const { store, storage } = await bootWithRegistry(
|
||||
JSON.stringify([{ serverId: "srv_future", connections: [futureConnection] }]),
|
||||
);
|
||||
expect(store.getHosts()).toEqual([]);
|
||||
|
||||
await store.upsertDirectConnection({ serverId: "srv_future", endpoint: directA.endpoint });
|
||||
await vi.waitFor(async () =>
|
||||
expect(await readRegistry(storage)).toMatchObject([
|
||||
{ serverId: "srv_future", connections: [{ id: directA.id }] },
|
||||
]),
|
||||
);
|
||||
|
||||
await store.removeHost("srv_future");
|
||||
expect(await readRegistry(storage)).toEqual([]);
|
||||
|
||||
store.syncHosts([]);
|
||||
});
|
||||
|
||||
it("copies a registry that isn't JSON aside instead of deleting it", async () => {
|
||||
const { store, storage } = await bootWithRegistry("{not json");
|
||||
|
||||
expect(store.getHosts()).toEqual([]);
|
||||
expect(await storage.getItem(`${REGISTRY_KEY}:unreadable`)).toBe("{not json");
|
||||
expect(await storage.getItem(REGISTRY_KEY)).toBe("{not json");
|
||||
|
||||
store.syncHosts([]);
|
||||
});
|
||||
|
||||
it("marks the host registry loaded after boot reads storage", async () => {
|
||||
const previousOverride = process.env.EXPO_PUBLIC_LOCAL_DAEMON;
|
||||
process.env.EXPO_PUBLIC_LOCAL_DAEMON = "not-an-endpoint";
|
||||
|
||||
@@ -17,14 +17,16 @@ import {
|
||||
import {
|
||||
connectionFromListen,
|
||||
createRemoteSshHostConnection,
|
||||
normalizeStoredHostProfile,
|
||||
forgetUnreadableHost,
|
||||
pinRelayProtectedSecurityInProfiles,
|
||||
readHostRegistry,
|
||||
upsertHostConnectionInProfiles,
|
||||
registryHasConnection,
|
||||
relayConnectionFromOffer,
|
||||
StoredHostRegistrySchema,
|
||||
writeHostRegistry,
|
||||
type HostConnection,
|
||||
type HostProfile,
|
||||
type UnreadableHostEntries,
|
||||
} from "@/types/host-connection";
|
||||
import { defaultHostAppearance, type HostBadgeDisplay, type HostColor } from "@/hosts/appearance";
|
||||
import {
|
||||
@@ -43,7 +45,7 @@ import { isWeb } from "@/constants/platform";
|
||||
import { connectToDaemon, getConnectionAuthFailureReason } from "@/utils/test-daemon-connection";
|
||||
import { getOrCreateClientId } from "@/utils/client-id";
|
||||
import { z } from "zod";
|
||||
import { readValidatedJson, readValidatedString } from "@/storage/validated-storage";
|
||||
import { readValidatedString } from "@/storage/validated-storage";
|
||||
import {
|
||||
selectBestConnection,
|
||||
type ConnectionCandidate,
|
||||
@@ -1692,6 +1694,7 @@ export class HostRuntimeStore {
|
||||
private hostListVersion = 0;
|
||||
private hostRegistryLoaded = false;
|
||||
private hosts: HostProfile[] = [];
|
||||
private unreadableHosts: UnreadableHostEntries = { hosts: [], connectionsByServerId: new Map() };
|
||||
private hostAppearanceMutationTail: Promise<void> = Promise.resolve();
|
||||
private hostRegistryStatus: HostRegistryStatus = "loading";
|
||||
private deps: HostRuntimeControllerDeps;
|
||||
@@ -1799,32 +1802,17 @@ export class HostRuntimeStore {
|
||||
let shouldPersistHosts = false;
|
||||
let profiles: HostProfile[] = [];
|
||||
try {
|
||||
const stored = await readValidatedJson(
|
||||
this.storage,
|
||||
REGISTRY_STORAGE_KEY,
|
||||
StoredHostRegistrySchema,
|
||||
);
|
||||
const stored = await this.readStoredRegistry();
|
||||
if (stored) {
|
||||
const normalizedProfiles: HostProfile[] = [];
|
||||
for (const entry of stored) {
|
||||
const profile = normalizeStoredHostProfile(entry);
|
||||
if (!profile) {
|
||||
await this.storage.removeItem(REGISTRY_STORAGE_KEY);
|
||||
normalizedProfiles.length = 0;
|
||||
break;
|
||||
}
|
||||
// COMPAT(connectionPassword): added in v0.9.1, remove after 2027-03-24 with stored-password migration.
|
||||
if (
|
||||
entry.connections.some(
|
||||
(connection) => connection.type === "directTcp" && connection.password,
|
||||
)
|
||||
) {
|
||||
shouldPersistHosts = true;
|
||||
}
|
||||
normalizedProfiles.push(profile);
|
||||
// An entry this build can't read skips only that host or connection, and stays stored.
|
||||
const registry = readHostRegistry(stored);
|
||||
this.unreadableHosts = registry.unreadable;
|
||||
// COMPAT(connectionPassword): added in v0.9.1, remove after 2027-03-24 with stored-password migration.
|
||||
if (registry.movedConnectionPassword) {
|
||||
shouldPersistHosts = true;
|
||||
}
|
||||
profiles = normalizedProfiles.filter((entry) => !isPlaceholderServerId(entry.serverId));
|
||||
if (profiles.length !== normalizedProfiles.length) {
|
||||
profiles = registry.hosts.filter((entry) => !isPlaceholderServerId(entry.serverId));
|
||||
if (profiles.length !== registry.hosts.length) {
|
||||
shouldPersistHosts = true;
|
||||
}
|
||||
}
|
||||
@@ -2320,6 +2308,7 @@ export class HostRuntimeStore {
|
||||
async removeHost(serverId: string): Promise<void> {
|
||||
await this.revokePushNotifications({ client: this.getClient(serverId), serverId });
|
||||
const remaining = this.hosts.filter((daemon) => daemon.serverId !== serverId);
|
||||
this.unreadableHosts = forgetUnreadableHost(this.unreadableHosts, serverId);
|
||||
this.setHostsAndSync(remaining);
|
||||
await this.persistHosts();
|
||||
}
|
||||
@@ -2408,7 +2397,27 @@ export class HostRuntimeStore {
|
||||
}
|
||||
|
||||
private async persistHosts(hosts = this.hosts): Promise<void> {
|
||||
await this.storage.setItem(REGISTRY_STORAGE_KEY, JSON.stringify(hosts));
|
||||
await this.storage.setItem(
|
||||
REGISTRY_STORAGE_KEY,
|
||||
JSON.stringify(writeHostRegistry(hosts, this.unreadableHosts)),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the stored registry without removing it. A value that isn't a JSON array is copied to
|
||||
* `<key>:unreadable` first, because the next save overwrites the key.
|
||||
*/
|
||||
private async readStoredRegistry(): Promise<unknown[] | null> {
|
||||
const raw = await this.storage.getItem(REGISTRY_STORAGE_KEY);
|
||||
if (raw === null) return null;
|
||||
try {
|
||||
const value: unknown = JSON.parse(raw);
|
||||
if (Array.isArray(value)) return value;
|
||||
} catch {
|
||||
// Not JSON: copied aside below.
|
||||
}
|
||||
await this.storage.setItem(`${REGISTRY_STORAGE_KEY}:unreadable`, raw);
|
||||
return null;
|
||||
}
|
||||
|
||||
private emitHostList(): void {
|
||||
|
||||
@@ -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");
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -5,9 +5,11 @@ import {
|
||||
normalizeStoredHostProfile,
|
||||
orderHostsLocalFirst,
|
||||
pinRelayProtectedSecurityInProfiles,
|
||||
readHostRegistry,
|
||||
relayConnectionFromOffer,
|
||||
resolveActiveHostServerId,
|
||||
upsertHostConnectionInProfiles,
|
||||
writeHostRegistry,
|
||||
type HostConnection,
|
||||
type HostProfile,
|
||||
} from "./host-connection";
|
||||
@@ -87,6 +89,25 @@ describe("normalizeStoredHostProfile", () => {
|
||||
expect(profile?.connections[0]).not.toHaveProperty("password");
|
||||
});
|
||||
|
||||
it("drops a connection kind this build doesn't know and keeps the host", () => {
|
||||
const profile = normalizeStoredHostProfile({
|
||||
serverId: "srv_mixed",
|
||||
password: "secret",
|
||||
connections: [
|
||||
{ id: "future:1", type: "futureKind", address: "future.example.com" },
|
||||
{ id: "direct:lan:6767", type: "directTcp", endpoint: "lan:6767", futureField: true },
|
||||
{ id: "direct:remote:6767", type: "directTcp", endpoint: "remote:6767" },
|
||||
],
|
||||
preferredConnectionId: "direct:remote:6767",
|
||||
});
|
||||
|
||||
expect(profile?.password).toBe("secret");
|
||||
expect(profile?.connections).toEqual([
|
||||
{ id: "direct:remote:6767", type: "directTcp", endpoint: "remote:6767", useTls: false },
|
||||
]);
|
||||
expect(profile?.preferredConnectionId).toBe("direct:remote:6767");
|
||||
});
|
||||
|
||||
it("preserves legacy relay ids when TLS is absent", () => {
|
||||
const profile = normalizeStoredHostProfile({
|
||||
serverId: "srv_relay",
|
||||
@@ -177,6 +198,59 @@ describe("normalizeStoredHostProfile", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("readHostRegistry and writeHostRegistry", () => {
|
||||
const direct: HostConnection = {
|
||||
id: "direct:lan:6767",
|
||||
type: "directTcp",
|
||||
endpoint: "lan:6767",
|
||||
useTls: false,
|
||||
};
|
||||
const future = { id: "future:1", type: "futureKind", address: "future.example.com" };
|
||||
|
||||
it("writes back every entry it could not read", () => {
|
||||
const unreadableHost = { serverId: "srv_future", connections: [future] };
|
||||
const hostWithFutureField = { serverId: "srv_field", connections: [direct], futureField: 1 };
|
||||
const stored = [
|
||||
{ ...makeHost("srv_a"), connections: [direct, future] },
|
||||
unreadableHost,
|
||||
hostWithFutureField,
|
||||
"not a host",
|
||||
];
|
||||
|
||||
const { hosts, unreadable } = readHostRegistry(stored);
|
||||
expect(hosts.map((host) => host.serverId)).toEqual(["srv_a"]);
|
||||
expect(hosts[0]?.connections).toEqual([direct]);
|
||||
|
||||
expect(writeHostRegistry(hosts, unreadable)).toEqual([
|
||||
{ ...hosts[0], connections: [direct, future] },
|
||||
unreadableHost,
|
||||
hostWithFutureField,
|
||||
"not a host",
|
||||
]);
|
||||
});
|
||||
|
||||
it("writes a host saved again by this build in place of the entry it could not read", () => {
|
||||
const { hosts, unreadable } = readHostRegistry([{ serverId: "srv_a", connections: [future] }]);
|
||||
expect(hosts).toEqual([]);
|
||||
|
||||
const saved = { ...makeHost("srv_a"), connections: [direct] };
|
||||
expect(writeHostRegistry([saved], unreadable)).toEqual([saved]);
|
||||
});
|
||||
|
||||
it("moves a stored direct TCP password to its host next to a connection it can't read", () => {
|
||||
const registry = readHostRegistry([
|
||||
{
|
||||
serverId: "srv_legacy",
|
||||
connections: [future, { type: "directTcp", endpoint: "lan:6767", password: "old-secret" }],
|
||||
},
|
||||
]);
|
||||
|
||||
expect(registry.movedConnectionPassword).toBe(true);
|
||||
expect(registry.hosts[0]?.password).toBe("old-secret");
|
||||
expect(registry.hosts[0]?.connections).toEqual([direct]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("createRemoteSshHostConnection", () => {
|
||||
it("keeps optional SSH settings absent", () => {
|
||||
expect(createRemoteSshHostConnection({ host: "build-box" })).toEqual({
|
||||
|
||||
@@ -522,12 +522,12 @@ const StoredHostProfileSchema = z.strictObject({
|
||||
label: z.string().optional(),
|
||||
appearance: HostAppearanceSchema.optional(),
|
||||
lifecycle: z.strictObject({}).optional(),
|
||||
connections: z.array(StoredHostConnectionSchema).min(1),
|
||||
// Read one by one, so a connection kind another build wrote skips only that connection.
|
||||
connections: z.array(z.unknown()).min(1),
|
||||
preferredConnectionId: z.string().nullable().optional(),
|
||||
createdAt: z.string().datetime({ offset: true }).optional(),
|
||||
updatedAt: z.string().datetime({ offset: true }).optional(),
|
||||
});
|
||||
export const StoredHostRegistrySchema = z.array(StoredHostProfileSchema);
|
||||
type StoredHostConnection = z.infer<typeof StoredHostConnectionSchema>;
|
||||
|
||||
function normalizeStoredConnection(connection: StoredHostConnection): HostConnection | null {
|
||||
@@ -590,20 +590,37 @@ function normalizeStoredConnection(connection: StoredHostConnection): HostConnec
|
||||
}
|
||||
|
||||
export function normalizeStoredHostProfile(entry: unknown): HostProfile | null {
|
||||
return readStoredHost(entry)?.profile ?? null;
|
||||
}
|
||||
|
||||
interface StoredHostRead {
|
||||
profile: HostProfile;
|
||||
unreadableConnections: unknown[];
|
||||
movedConnectionPassword: boolean;
|
||||
}
|
||||
|
||||
function readStoredHost(entry: unknown): StoredHostRead | null {
|
||||
const result = StoredHostProfileSchema.safeParse(entry);
|
||||
if (!result.success) {
|
||||
return null;
|
||||
}
|
||||
const record = result.data;
|
||||
const serverId = record.serverId;
|
||||
const storedConnections: StoredHostConnection[] = [];
|
||||
const unreadableConnections: unknown[] = [];
|
||||
for (const stored of record.connections) {
|
||||
const parsed = StoredHostConnectionSchema.safeParse(stored);
|
||||
if (parsed.success) storedConnections.push(parsed.data);
|
||||
else unreadableConnections.push(stored);
|
||||
}
|
||||
// COMPAT(connectionPassword): added in v0.9.1, remove after 2027-03-24 once stored direct passwords have migrated.
|
||||
const legacyPassword = record.connections.find(
|
||||
const legacyPassword = storedConnections.find(
|
||||
(connection) => connection.type === "directTcp" && connection.password,
|
||||
);
|
||||
const password =
|
||||
record.password ?? (legacyPassword?.type === "directTcp" ? legacyPassword.password : undefined);
|
||||
|
||||
const connections = record.connections
|
||||
const connections = storedConnections
|
||||
.map((connection) => normalizeStoredConnection(connection))
|
||||
.filter((connection): connection is HostConnection => connection !== null);
|
||||
if (connections.length === 0) {
|
||||
@@ -620,18 +637,90 @@ export function normalizeStoredHostProfile(entry: unknown): HostProfile | null {
|
||||
: (connections[0]?.id ?? null);
|
||||
|
||||
return {
|
||||
serverId,
|
||||
...(password ? { password } : {}),
|
||||
label,
|
||||
appearance: record.appearance ?? defaultHostAppearance(),
|
||||
lifecycle: defaultLifecycle(),
|
||||
connections,
|
||||
preferredConnectionId,
|
||||
createdAt: record.createdAt ?? now,
|
||||
updatedAt: record.updatedAt ?? now,
|
||||
profile: {
|
||||
serverId,
|
||||
...(password ? { password } : {}),
|
||||
label,
|
||||
appearance: record.appearance ?? defaultHostAppearance(),
|
||||
lifecycle: defaultLifecycle(),
|
||||
connections,
|
||||
preferredConnectionId,
|
||||
createdAt: record.createdAt ?? now,
|
||||
updatedAt: record.updatedAt ?? now,
|
||||
},
|
||||
unreadableConnections,
|
||||
movedConnectionPassword: legacyPassword !== undefined,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Stored registry entries this build can't read, such as a connection kind added by a newer
|
||||
* build. `writeHostRegistry` writes them back so that build still finds them.
|
||||
*/
|
||||
export interface UnreadableHostEntries {
|
||||
hosts: unknown[];
|
||||
connectionsByServerId: Map<string, unknown[]>;
|
||||
}
|
||||
|
||||
export function readHostRegistry(stored: unknown[]): {
|
||||
hosts: HostProfile[];
|
||||
unreadable: UnreadableHostEntries;
|
||||
// COMPAT(connectionPassword): added in v0.9.1, remove after 2027-03-24 with stored-password migration.
|
||||
movedConnectionPassword: boolean;
|
||||
} {
|
||||
const hosts: HostProfile[] = [];
|
||||
const unreadable: UnreadableHostEntries = { hosts: [], connectionsByServerId: new Map() };
|
||||
let movedConnectionPassword = false;
|
||||
for (const entry of stored) {
|
||||
const read = readStoredHost(entry);
|
||||
if (!read) {
|
||||
unreadable.hosts.push(entry);
|
||||
continue;
|
||||
}
|
||||
hosts.push(read.profile);
|
||||
if (read.unreadableConnections.length > 0) {
|
||||
unreadable.connectionsByServerId.set(read.profile.serverId, read.unreadableConnections);
|
||||
}
|
||||
movedConnectionPassword ||= read.movedConnectionPassword;
|
||||
}
|
||||
return { hosts, unreadable, movedConnectionPassword };
|
||||
}
|
||||
|
||||
export function writeHostRegistry(
|
||||
hosts: HostProfile[],
|
||||
unreadable: UnreadableHostEntries,
|
||||
): unknown[] {
|
||||
const savedServerIds = new Set(hosts.map((host) => host.serverId));
|
||||
const written: unknown[] = hosts.map((host) => {
|
||||
const kept = unreadable.connectionsByServerId.get(host.serverId);
|
||||
return kept ? { ...host, connections: [...host.connections, ...kept] } : host;
|
||||
});
|
||||
for (const entry of unreadable.hosts) {
|
||||
// A host this build saved again replaces the entry it couldn't read.
|
||||
const serverId = readStoredServerId(entry);
|
||||
if (serverId === null || !savedServerIds.has(serverId)) written.push(entry);
|
||||
}
|
||||
return written;
|
||||
}
|
||||
|
||||
/** Drops the entries this build couldn't read for a host you removed. */
|
||||
export function forgetUnreadableHost(
|
||||
unreadable: UnreadableHostEntries,
|
||||
serverId: string,
|
||||
): UnreadableHostEntries {
|
||||
const connectionsByServerId = new Map(unreadable.connectionsByServerId);
|
||||
connectionsByServerId.delete(serverId);
|
||||
return {
|
||||
hosts: unreadable.hosts.filter((entry) => readStoredServerId(entry) !== serverId),
|
||||
connectionsByServerId,
|
||||
};
|
||||
}
|
||||
|
||||
function readStoredServerId(entry: unknown): string | null {
|
||||
if (typeof entry !== "object" || entry === null || !("serverId" in entry)) return null;
|
||||
return typeof entry.serverId === "string" ? entry.serverId.trim() : null;
|
||||
}
|
||||
|
||||
export function hostHasConnection(host: HostProfile, connection: HostConnection): boolean {
|
||||
return host.connections.some((existing) => hostConnectionEquals(existing, connection));
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@getpaseo/cli",
|
||||
"version": "0.16.1",
|
||||
"version": "0.16.2",
|
||||
"description": "Paseo CLI - control your AI coding agents from the command line",
|
||||
"license": "Apache-2.0",
|
||||
"bin": {
|
||||
@@ -29,9 +29,9 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@clack/prompts": "^1.0.0",
|
||||
"@getpaseo/client": "0.16.1",
|
||||
"@getpaseo/protocol": "0.16.1",
|
||||
"@getpaseo/server": "0.16.1",
|
||||
"@getpaseo/client": "0.16.2",
|
||||
"@getpaseo/protocol": "0.16.2",
|
||||
"@getpaseo/server": "0.16.2",
|
||||
"chalk": "^5.3.0",
|
||||
"commander": "^12.0.0",
|
||||
"mime-types": "^2.1.35",
|
||||
|
||||
@@ -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({
|
||||
|
||||
@@ -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)}`);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@getpaseo/client",
|
||||
"version": "0.16.1",
|
||||
"version": "0.16.2",
|
||||
"description": "Paseo client SDK package",
|
||||
"license": "Apache-2.0",
|
||||
"files": [
|
||||
@@ -49,8 +49,8 @@
|
||||
"measure:diff-materialization": "tsx scripts/measure-diff-materialization.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"@getpaseo/protocol": "0.16.1",
|
||||
"@getpaseo/relay": "0.16.1",
|
||||
"@getpaseo/protocol": "0.16.2",
|
||||
"@getpaseo/relay": "0.16.2",
|
||||
"ws": "^8.20.0",
|
||||
"zod": "^4.4.3"
|
||||
},
|
||||
|
||||
@@ -11,9 +11,6 @@ if not exist "%APP_EXECUTABLE%" (
|
||||
|
||||
set "ELECTRON_RUN_AS_NODE=1"
|
||||
set "PASEO_NODE_ENV=production"
|
||||
rem PASEO_DESKTOP_MANAGED marks daemons started through this bundled CLI as
|
||||
rem desktop-managed, so the desktop app restarts them when it upgrades.
|
||||
set "PASEO_DESKTOP_MANAGED=1"
|
||||
set "PASEO_CLI=%~f0"
|
||||
"%APP_EXECUTABLE%" --disable-warning=DEP0040 "%RESOURCES_DIR%\app.asar.unpacked\dist\daemon\node-entrypoint-runner.js" node-script "%RESOURCES_DIR%\app.asar\node_modules\@getpaseo\cli\dist\index.js" %*
|
||||
exit /b %errorlevel%
|
||||
|
||||
@@ -41,16 +41,24 @@ savePersistedConfig(home, {
|
||||
},
|
||||
});
|
||||
const main = path.join(root, "main.cjs");
|
||||
const updatedMain = path.join(root, "updated-main.cjs");
|
||||
const managerPath = path.join(repo, "packages/desktop/dist/daemon/daemon-manager.js");
|
||||
const desktopMain = (setup) =>
|
||||
`const { app } = require("electron"); ${setup} app.setPath("userData", ${JSON.stringify(path.join(root, "user-data"))}); app.whenReady().then(() => { global.lifecycle = require(${JSON.stringify(managerPath)}); });`;
|
||||
await writeFile(main, desktopMain(""));
|
||||
// An unpackaged Desktop reads its version from packages/desktop/package.json. This entry
|
||||
// reports a newer version, standing in for the Desktop an update installs.
|
||||
await writeFile(
|
||||
main,
|
||||
`const { app } = require("electron"); app.setPath("userData", ${JSON.stringify(path.join(root, "user-data"))}); app.whenReady().then(() => { global.lifecycle = require(${JSON.stringify(managerPath)}); });`,
|
||||
updatedMain,
|
||||
desktopMain(
|
||||
`const fs = require("node:fs"); const path = require("node:path"); const readFileSync = fs.readFileSync; fs.readFileSync = (file, ...rest) => typeof file === "string" && path.relative(${JSON.stringify(path.join(repo, "packages/desktop"))}, file) === "package.json" ? JSON.stringify({ version: "999.0.0" }) : readFileSync(file, ...rest);`,
|
||||
),
|
||||
);
|
||||
let desktop;
|
||||
let captured;
|
||||
async function openDesktop() {
|
||||
async function openDesktop(entry = main) {
|
||||
desktop = await electron.launch({
|
||||
args: ["--no-sandbox", "--ozone-platform=headless", main],
|
||||
args: ["--no-sandbox", "--ozone-platform=headless", entry],
|
||||
env: {
|
||||
...env,
|
||||
PASEO_LISTEN: "127.0.0.1:1",
|
||||
@@ -78,27 +86,31 @@ async function command(name, args) {
|
||||
);
|
||||
}
|
||||
try {
|
||||
// Simulate a legacy independent launch that carries the old Desktop flag.
|
||||
// A daemon the user started through the CLI, which Desktop must never stop on its own.
|
||||
// Older bundled CLIs exported PASEO_DESKTOP_MANAGED, and the CLI launch must not record it.
|
||||
const launch = await startDaemonInstance({
|
||||
home,
|
||||
command: process.execPath,
|
||||
args: [path.join(repo, "packages/server/dist/scripts/supervisor-entrypoint.js")],
|
||||
env,
|
||||
env: { ...env, PASEO_DESKTOP_MANAGED: "1" },
|
||||
mode: "deployment",
|
||||
desktopManaged: true,
|
||||
timeoutMs: 30_000,
|
||||
});
|
||||
captured = launch.instance;
|
||||
await openDesktop();
|
||||
const attached = await command("start_desktop_daemon");
|
||||
assert.equal(attached.pid, captured.pid);
|
||||
assert.equal(attached.desktopManaged, true);
|
||||
assert.equal(attached.desktopManaged, false);
|
||||
assert.equal(attached.ownedByDesktop, false);
|
||||
for (const reason of ["quit", "settings", "app_update", "host_remove", "version_mismatch"]) {
|
||||
const status = await command("stop_desktop_daemon", { reason });
|
||||
assert.equal(status.pid, captured.pid, `${reason} stopped an attached daemon`);
|
||||
process.kill(captured.pid, 0);
|
||||
}
|
||||
await closeDesktop();
|
||||
await openDesktop(updatedMain);
|
||||
const afterUpdate = await command("start_desktop_daemon");
|
||||
assert.equal(afterUpdate.pid, captured.pid, "a newer Desktop replaced a daemon the user started");
|
||||
const restarted = await command("restart_desktop_daemon");
|
||||
assert.equal(restarted.pid, captured.pid);
|
||||
await assert.rejects(
|
||||
@@ -134,18 +146,37 @@ try {
|
||||
desktop = null;
|
||||
process.kill(captured.pid, 0);
|
||||
await openDesktop();
|
||||
assert.equal((await command("start_desktop_daemon")).ownedByDesktop, false);
|
||||
await command("stop_desktop_daemon", { reason: "quit" });
|
||||
// The next session attaches to the daemon Desktop launched before it quit.
|
||||
const survivor = await command("start_desktop_daemon");
|
||||
assert.equal(survivor.pid, captured.pid);
|
||||
assert.equal(survivor.desktopManaged, true);
|
||||
assert.equal(survivor.ownedByDesktop, false);
|
||||
for (const reason of ["quit", "settings", "host_remove"]) {
|
||||
await command("stop_desktop_daemon", { reason });
|
||||
process.kill(captured.pid, 0);
|
||||
}
|
||||
// With management off, Desktop leaves the daemon running through an update.
|
||||
await command("patch_desktop_settings", { daemon: { manageBuiltInDaemon: false } });
|
||||
await command("stop_desktop_daemon", { reason: "app_update" });
|
||||
process.kill(captured.pid, 0);
|
||||
await command("stop_desktop_daemon", {
|
||||
reason: "manual_ipc",
|
||||
pid: captured.pid,
|
||||
startedAt: captured.startedAt,
|
||||
});
|
||||
await command("patch_desktop_settings", { daemon: { manageBuiltInDaemon: true } });
|
||||
// Installing an update stops it, so the updated Desktop starts its own daemon.
|
||||
const beforeInstall = await command("stop_desktop_daemon", { reason: "app_update" });
|
||||
assert.equal(beforeInstall.status, "stopped", "app_update left Desktop's daemon running");
|
||||
captured = null;
|
||||
const next = await command("start_desktop_daemon");
|
||||
captured = await readDaemonInstance(home);
|
||||
assert.equal(next.ownedByDesktop, true);
|
||||
await closeDesktop();
|
||||
process.kill(captured.pid, 0);
|
||||
// A newer Desktop replaces the daemon an older Desktop launched and kept running.
|
||||
const outdated = captured;
|
||||
await openDesktop(updatedMain);
|
||||
const replaced = await command("start_desktop_daemon");
|
||||
captured = await readDaemonInstance(home);
|
||||
assert.notEqual(replaced.pid, outdated.pid, "a newer Desktop kept the outdated daemon");
|
||||
assert.equal(replaced.ownedByDesktop, true);
|
||||
assert.throws(() => process.kill(outdated.pid, 0), "the outdated daemon is still running");
|
||||
await command("stop_desktop_daemon", { reason: "quit" });
|
||||
assert.equal(await readDaemonInstance(home), null);
|
||||
captured = null;
|
||||
@@ -195,7 +226,7 @@ try {
|
||||
);
|
||||
}
|
||||
console.log(
|
||||
"PASS: attached legacy daemon survives automatic actions; explicit captured stop, owned launch, managed settings, worker restart, and next-session attachment.",
|
||||
"PASS: a user-started daemon survives automatic actions and updates; explicit captured stop, owned launch, managed settings, worker restart, next-session attachment, and update replacement of an earlier session's daemon.",
|
||||
);
|
||||
} finally {
|
||||
await closeDesktop();
|
||||
|
||||
@@ -5,18 +5,25 @@ import { fileURLToPath } from "node:url";
|
||||
import { _electron as electron, expect } from "playwright/test";
|
||||
|
||||
const root = await mkdtemp(path.join(tmpdir(), "paseo-window-startup-"));
|
||||
const modulePath = fileURLToPath(new URL("../dist/window/show-when-ready.js", import.meta.url));
|
||||
const showWhenReadyPath = fileURLToPath(
|
||||
new URL("../dist/window/show-when-ready.js", import.meta.url),
|
||||
);
|
||||
const rendererRecoveryPath = fileURLToPath(
|
||||
new URL("../dist/window/renderer-recovery.js", import.meta.url),
|
||||
);
|
||||
|
||||
async function launchWindowWithoutHiddenFrames() {
|
||||
async function launchDesktopWindow() {
|
||||
const main = path.join(root, "main.cjs");
|
||||
await writeFile(
|
||||
main,
|
||||
`const { app, BrowserWindow } = require("electron");
|
||||
const { showWindowWhenReady } = require(${JSON.stringify(modulePath)});
|
||||
const { showWindowWhenReady } = require(${JSON.stringify(showWhenReadyPath)});
|
||||
const { reloadWhenRendererExits } = require(${JSON.stringify(rendererRecoveryPath)});
|
||||
app.setPath("userData", ${JSON.stringify(path.join(root, "user-data"))});
|
||||
app.whenReady().then(async () => {
|
||||
const win = global.mainWindow = new BrowserWindow({ show: false, paintWhenInitiallyHidden: false });
|
||||
showWindowWhenReady(win, { showOnLoad: true });
|
||||
reloadWhenRendererExits(win);
|
||||
await win.loadURL("data:text/html,<h1>Desktop ready</h1>");
|
||||
global.visibleAfterLoad = win.isVisible();
|
||||
});`,
|
||||
@@ -37,11 +44,32 @@ async function expectLoadedDesktopIsShown(desktop) {
|
||||
await expect(page.getByRole("heading", { name: "Desktop ready" })).toBeVisible();
|
||||
}
|
||||
|
||||
function rendererPid(desktop) {
|
||||
return desktop.evaluate(() => global.mainWindow.webContents.getOSProcessId());
|
||||
}
|
||||
|
||||
async function expectDesktopReloadsAfterRendererIsTerminated(desktop) {
|
||||
const terminated = await rendererPid(desktop);
|
||||
process.kill(terminated, "SIGTERM");
|
||||
await expect.poll(() => rendererPid(desktop), { timeout: 15_000 }).not.toBe(terminated);
|
||||
await expect
|
||||
.poll(
|
||||
() =>
|
||||
desktop.evaluate(() =>
|
||||
global.mainWindow.webContents.executeJavaScript("document.body.textContent"),
|
||||
),
|
||||
{ timeout: 15_000 },
|
||||
)
|
||||
.toBe("Desktop ready");
|
||||
}
|
||||
|
||||
let desktop;
|
||||
try {
|
||||
desktop = await launchWindowWithoutHiddenFrames();
|
||||
desktop = await launchDesktopWindow();
|
||||
await expectLoadedDesktopIsShown(desktop);
|
||||
console.log("Loaded desktop is visible without hidden compositor frames");
|
||||
await expectDesktopReloadsAfterRendererIsTerminated(desktop);
|
||||
console.log("Desktop reloads its window after the renderer is terminated");
|
||||
} finally {
|
||||
await desktop?.close();
|
||||
await rm(root, { recursive: true, force: true });
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@getpaseo/desktop",
|
||||
"version": "0.16.1",
|
||||
"version": "0.16.2",
|
||||
"private": true,
|
||||
"description": "Paseo desktop app (Electron wrapper)",
|
||||
"homepage": "https://paseo.sh",
|
||||
|
||||
@@ -269,7 +269,7 @@ function normalizeVersion(version: string | null): string | null {
|
||||
}
|
||||
|
||||
function shouldRestartForVersion(current: DesktopDaemonStatus): boolean {
|
||||
if (!current.ownedByDesktop) return false;
|
||||
if (!current.desktopManaged) return false;
|
||||
const appVersion = normalizeVersion(resolveDesktopAppVersion());
|
||||
const daemonVersion = normalizeVersion(current.version);
|
||||
return Boolean(appVersion && daemonVersion && appVersion !== daemonVersion);
|
||||
@@ -336,12 +336,13 @@ export async function stopDesktopDaemon(
|
||||
): Promise<DesktopDaemonStatus> {
|
||||
const home = getPaseoHome();
|
||||
const instance = await readDaemonInstance(home);
|
||||
const owned = Boolean(
|
||||
const launchedThisSession = Boolean(
|
||||
instance &&
|
||||
ownedLaunch &&
|
||||
ownedLaunch.home === home &&
|
||||
isSameDaemonInstance(instance, ownedLaunch.instance),
|
||||
);
|
||||
const owned = launchedThisSession || (await replacesDesktopDaemon(reason, instance));
|
||||
const explicit =
|
||||
reason === "manual_ipc" &&
|
||||
confirmedInstance &&
|
||||
@@ -361,10 +362,28 @@ export async function stopDesktopDaemon(
|
||||
keepTerminals,
|
||||
});
|
||||
await stopCapturedDaemon({ home, instance, reason, keepTerminals });
|
||||
if (owned) ownedLaunch = null;
|
||||
if (launchedThisSession) ownedLaunch = null;
|
||||
return resolveDesktopDaemonStatus();
|
||||
}
|
||||
|
||||
/** An app update or a version mismatch replaces the daemon with the one this Desktop bundles. */
|
||||
function isReplacement(reason: DesktopDaemonStopReason): boolean {
|
||||
return reason === "app_update" || reason === "version_mismatch";
|
||||
}
|
||||
|
||||
/**
|
||||
* While Desktop manages the built-in daemon, a replacement applies to every daemon Desktop
|
||||
* launched, which `paseo.pid` records as `desktopManaged`. That includes one an earlier Desktop
|
||||
* session left running. Other automatic stops apply only to a daemon this session launched.
|
||||
*/
|
||||
async function replacesDesktopDaemon(
|
||||
reason: DesktopDaemonStopReason,
|
||||
instance: DaemonInstance | null,
|
||||
): Promise<boolean> {
|
||||
if (!isReplacement(reason) || instance?.desktopManaged !== true) return false;
|
||||
return (await getDesktopSettingsStore().get()).daemon.manageBuiltInDaemon;
|
||||
}
|
||||
|
||||
export interface StopCapturedDaemonInput {
|
||||
home: string;
|
||||
instance: DaemonInstance;
|
||||
@@ -428,7 +447,7 @@ export function keepsTerminalsOnStop(
|
||||
platform: NodeJS.Platform,
|
||||
): boolean {
|
||||
if (platform === "win32") return false;
|
||||
return reason === "app_update" || reason === "version_mismatch";
|
||||
return isReplacement(reason);
|
||||
}
|
||||
|
||||
async function restartDaemon(): Promise<DesktopDaemonStatus> {
|
||||
|
||||
@@ -46,6 +46,7 @@ import {
|
||||
buildStandardContextMenuItems,
|
||||
} from "./window/window-manager.js";
|
||||
import { setupDarwinCompositorWatchdog } from "./window/compositor-watchdog/index.js";
|
||||
import { reloadWhenRendererExits } from "./window/renderer-recovery.js";
|
||||
import { showWindowWhenReady } from "./window/show-when-ready.js";
|
||||
import { resolveDesktopWindowChromeMode, windowChromeModeArgument } from "./window/chrome.js";
|
||||
import { registerDialogHandlers } from "./features/dialogs.js";
|
||||
@@ -734,6 +735,7 @@ async function createWindow(
|
||||
}
|
||||
|
||||
setupDarwinCompositorWatchdog(mainWindow);
|
||||
reloadWhenRendererExits(mainWindow);
|
||||
setupWindowResizeEvents(mainWindow);
|
||||
if (windowStateStore) {
|
||||
setupWindowStatePersistence(mainWindow, windowStateStore);
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
import { EventEmitter } from "node:events";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { reloadWhenRendererExits } from "./renderer-recovery.js";
|
||||
|
||||
class Contents extends EventEmitter {
|
||||
reloads = 0;
|
||||
url = "paseo://app/";
|
||||
getURL() {
|
||||
return this.url;
|
||||
}
|
||||
reload() {
|
||||
this.reloads += 1;
|
||||
}
|
||||
exit(reason: string) {
|
||||
this.emit("render-process-gone", {}, { reason, exitCode: reason === "clean-exit" ? 0 : 15 });
|
||||
}
|
||||
}
|
||||
|
||||
class Window {
|
||||
webContents = new Contents();
|
||||
destroyed = false;
|
||||
isDestroyed() {
|
||||
return this.destroyed;
|
||||
}
|
||||
}
|
||||
|
||||
function recoverableWindow() {
|
||||
const win = new Window();
|
||||
let time = 0;
|
||||
reloadWhenRendererExits(win, { now: () => time });
|
||||
return {
|
||||
win,
|
||||
advance(ms: number) {
|
||||
time += ms;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe("reloadWhenRendererExits", () => {
|
||||
it("reloads the window when its renderer is killed", () => {
|
||||
const { win } = recoverableWindow();
|
||||
win.webContents.exit("killed");
|
||||
expect(win.webContents.reloads).toBe(1);
|
||||
});
|
||||
|
||||
it("reloads after a renderer crash or out-of-memory exit", () => {
|
||||
const { win, advance } = recoverableWindow();
|
||||
win.webContents.exit("crashed");
|
||||
advance(120_000);
|
||||
win.webContents.exit("oom");
|
||||
expect(win.webContents.reloads).toBe(2);
|
||||
});
|
||||
|
||||
it("leaves a renderer that exited cleanly alone", () => {
|
||||
const { win } = recoverableWindow();
|
||||
win.webContents.exit("clean-exit");
|
||||
expect(win.webContents.reloads).toBe(0);
|
||||
});
|
||||
|
||||
it("leaves a renderer that exits before the first page commits to Chromium", () => {
|
||||
const { win } = recoverableWindow();
|
||||
win.webContents.url = "";
|
||||
win.webContents.exit("killed");
|
||||
expect(win.webContents.reloads).toBe(0);
|
||||
});
|
||||
|
||||
it("leaves a closed window closed", () => {
|
||||
const { win } = recoverableWindow();
|
||||
win.destroyed = true;
|
||||
win.webContents.exit("killed");
|
||||
expect(win.webContents.reloads).toBe(0);
|
||||
});
|
||||
|
||||
it("stops reloading a renderer that keeps exiting, and recovers again later", () => {
|
||||
const { win, advance } = recoverableWindow();
|
||||
for (let exit = 0; exit < 5; exit += 1) {
|
||||
win.webContents.exit("crashed");
|
||||
advance(1_000);
|
||||
}
|
||||
expect(win.webContents.reloads).toBe(3);
|
||||
|
||||
advance(60_000);
|
||||
win.webContents.exit("killed");
|
||||
expect(win.webContents.reloads).toBe(4);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,56 @@
|
||||
import log from "electron-log/main";
|
||||
|
||||
// A window whose renderer exits keeps its frame but shows nothing until it is
|
||||
// reloaded. Reload it, but stop when the renderer keeps exiting so a page that
|
||||
// crashes on load does not restart in a loop.
|
||||
const MAX_RELOADS_PER_WINDOW = 3;
|
||||
const RELOAD_WINDOW_MS = 60_000;
|
||||
|
||||
interface RendererExit {
|
||||
reason: string;
|
||||
exitCode: number;
|
||||
}
|
||||
|
||||
interface RecoverableWindow {
|
||||
isDestroyed(): boolean;
|
||||
webContents: {
|
||||
on(
|
||||
event: "render-process-gone",
|
||||
listener: (event: unknown, details: RendererExit) => void,
|
||||
): unknown;
|
||||
getURL(): string;
|
||||
reload(): void;
|
||||
};
|
||||
}
|
||||
|
||||
export function reloadWhenRendererExits(
|
||||
win: RecoverableWindow,
|
||||
options: { now?: () => number } = {},
|
||||
): void {
|
||||
const now = options.now ?? Date.now;
|
||||
let reloadTimes: number[] = [];
|
||||
|
||||
win.webContents.on("render-process-gone", (_event, details) => {
|
||||
if (details.reason === "clean-exit" || win.isDestroyed()) return;
|
||||
// Before the first page commits, Chromium finishes the navigation in a new
|
||||
// renderer by itself. Reloading then would abort the window's initial load.
|
||||
if (win.webContents.getURL() === "") return;
|
||||
|
||||
const time = now();
|
||||
reloadTimes = reloadTimes.filter((reloadTime) => time - reloadTime < RELOAD_WINDOW_MS);
|
||||
if (reloadTimes.length >= MAX_RELOADS_PER_WINDOW) {
|
||||
log.error(
|
||||
`[renderer-recovery] Renderer exited (${details.reason}, code ${details.exitCode}); ` +
|
||||
`not reloading after ${reloadTimes.length} reloads in the last minute`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
reloadTimes.push(time);
|
||||
log.warn(
|
||||
`[renderer-recovery] Renderer exited (${details.reason}, code ${details.exitCode}); ` +
|
||||
`reloading the window (reload ${reloadTimes.length} in the last minute)`,
|
||||
);
|
||||
win.webContents.reload();
|
||||
});
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@getpaseo/expo-two-way-audio",
|
||||
"version": "0.16.1",
|
||||
"version": "0.16.2",
|
||||
"description": "Native module for two way audio streaming",
|
||||
"keywords": [
|
||||
"ExpoTwoWayAudio",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@getpaseo/highlight",
|
||||
"version": "0.16.1",
|
||||
"version": "0.16.2",
|
||||
"license": "Apache-2.0",
|
||||
"files": [
|
||||
"dist",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@getpaseo/plugin",
|
||||
"version": "0.16.1",
|
||||
"version": "0.16.2",
|
||||
"description": "Paseo plugin SDK package",
|
||||
"license": "Apache-2.0",
|
||||
"files": [
|
||||
@@ -78,8 +78,8 @@
|
||||
"use-sync-external-store": "^1.6.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@getpaseo/client": "0.16.1",
|
||||
"@getpaseo/protocol": "0.16.1",
|
||||
"@getpaseo/client": "0.16.2",
|
||||
"@getpaseo/protocol": "0.16.2",
|
||||
"@types/node": "^20.9.0",
|
||||
"@types/react": "~19.2.0",
|
||||
"react": "19.2.3",
|
||||
@@ -89,8 +89,8 @@
|
||||
"zod": "^4.4.3"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@getpaseo/client": "0.16.1",
|
||||
"@getpaseo/protocol": "0.16.1",
|
||||
"@getpaseo/client": "0.16.2",
|
||||
"@getpaseo/protocol": "0.16.2",
|
||||
"react": ">=19.1.0 <20",
|
||||
"react-native": ">=0.81.5",
|
||||
"zod": "^4.4.3"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@getpaseo/protocol",
|
||||
"version": "0.16.1",
|
||||
"version": "0.16.2",
|
||||
"description": "Paseo shared protocol schemas and wire types",
|
||||
"license": "Apache-2.0",
|
||||
"files": [
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@getpaseo/relay",
|
||||
"version": "0.16.1",
|
||||
"version": "0.16.2",
|
||||
"description": "Paseo relay for bridging daemon and client connections",
|
||||
"license": "Apache-2.0",
|
||||
"files": [
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@getpaseo/server",
|
||||
"version": "0.16.1",
|
||||
"version": "0.16.2",
|
||||
"description": "Paseo backend server",
|
||||
"license": "Apache-2.0",
|
||||
"files": [
|
||||
@@ -109,11 +109,11 @@
|
||||
"@agentclientprotocol/sdk": "^0.17.1",
|
||||
"@anthropic-ai/claude-agent-sdk": "0.3.326",
|
||||
"@anthropic-ai/sdk": "^0.104.2",
|
||||
"@getpaseo/client": "0.16.1",
|
||||
"@getpaseo/highlight": "0.16.1",
|
||||
"@getpaseo/plugin": "0.16.1",
|
||||
"@getpaseo/protocol": "0.16.1",
|
||||
"@getpaseo/relay": "0.16.1",
|
||||
"@getpaseo/client": "0.16.2",
|
||||
"@getpaseo/highlight": "0.16.2",
|
||||
"@getpaseo/plugin": "0.16.2",
|
||||
"@getpaseo/protocol": "0.16.2",
|
||||
"@getpaseo/relay": "0.16.2",
|
||||
"@isaacs/ttlcache": "^2.1.4",
|
||||
"@modelcontextprotocol/sdk": "1.29.0",
|
||||
"@opencode-ai/sdk": "1.14.46",
|
||||
|
||||
@@ -3426,6 +3426,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",
|
||||
|
||||
@@ -5069,7 +5069,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;
|
||||
}
|
||||
|
||||
@@ -264,6 +264,7 @@ function buildAgentManagerSpies() {
|
||||
archiveAgent: vi.fn().mockResolvedValue({ archivedAt: new Date().toISOString() }),
|
||||
notifyAgentState: vi.fn(),
|
||||
getAgent: vi.fn(),
|
||||
getAgentBackgroundWorkSummary: vi.fn().mockReturnValue(undefined),
|
||||
listAgents: vi.fn().mockReturnValue([]),
|
||||
getTimeline: vi.fn().mockReturnValue([]),
|
||||
resumeAgentFromPersistence: vi.fn(),
|
||||
@@ -6181,6 +6182,36 @@ describe("agent snapshot MCP serialization", () => {
|
||||
expect(structured.agents[0]).not.toHaveProperty("pendingPermissions");
|
||||
});
|
||||
|
||||
it("reports an idle agent's background work from get_agent_status and list_agents", async () => {
|
||||
const { agentManager, agentStorage, spies } = createTestDeps();
|
||||
const agent = createManagedAgent({ id: "agent-with-shell", cwd: REPO_CWD });
|
||||
spies.agentManager.getAgent.mockReturnValue(agent);
|
||||
spies.agentManager.listAgents.mockReturnValue([agent]);
|
||||
spies.agentManager.getAgentBackgroundWorkSummary.mockReturnValue({ count: 1 });
|
||||
|
||||
const server = await createAgentMcpServer({
|
||||
agentManager,
|
||||
agentStorage,
|
||||
providerSnapshotManager: createOpenCodeManager().manager,
|
||||
logger,
|
||||
});
|
||||
const status = await registeredTool(server, "get_agent_status").handler({
|
||||
agentId: "agent-with-shell",
|
||||
});
|
||||
const list = await registeredTool(server, "list_agents").handler({});
|
||||
|
||||
expect(status.structuredContent).toEqual({
|
||||
status: "idle",
|
||||
snapshot: expect.objectContaining({ status: "idle", backgroundWork: { count: 1 } }),
|
||||
});
|
||||
expect(list.structuredContent).toEqual({
|
||||
agents: [expect.objectContaining({ status: "idle", backgroundWork: { count: 1 } })],
|
||||
});
|
||||
expect(spies.agentManager.getAgentBackgroundWorkSummary).toHaveBeenCalledWith(
|
||||
"agent-with-shell",
|
||||
);
|
||||
});
|
||||
|
||||
it("returns archived agent snapshots from storage for get_agent_status", async () => {
|
||||
const { agentManager, agentStorage, spies } = createTestDeps();
|
||||
const record = createStoredRecord({
|
||||
|
||||
@@ -2070,3 +2070,212 @@ test("does not use stream_event uuid as assistant message identity when message_
|
||||
|
||||
await session.close();
|
||||
});
|
||||
|
||||
// A background command's notification starts a turn. When Claude responds, the notification and
|
||||
// the response are one turn. When Claude does not respond, the notification is a turn in itself.
|
||||
// The frame sequences below are the ones Claude Code 2.1.321 sent on the wire.
|
||||
|
||||
function backgroundCommandNotification(taskId: string, status: "completed" | "stopped") {
|
||||
return {
|
||||
type: "system",
|
||||
subtype: "task_notification",
|
||||
task_id: taskId,
|
||||
tool_use_id: `toolu_${taskId}`,
|
||||
status,
|
||||
summary: `Background command ${status}`,
|
||||
output_file: `/tmp/${taskId}.output`,
|
||||
uuid: `uuid-${taskId}-${status}`,
|
||||
session_id: "sess-1",
|
||||
};
|
||||
}
|
||||
|
||||
const backgroundTasksChanged = {
|
||||
type: "system",
|
||||
subtype: "background_tasks_changed",
|
||||
tasks: [],
|
||||
uuid: "uuid-background-tasks-changed",
|
||||
session_id: "sess-1",
|
||||
};
|
||||
|
||||
function notificationRowTurnIds(events: AgentStreamEvent[]): (string | undefined)[] {
|
||||
return events
|
||||
.filter(
|
||||
(event): event is Extract<AgentStreamEvent, { type: "timeline" }> =>
|
||||
event.type === "timeline" &&
|
||||
event.item.type === "tool_call" &&
|
||||
event.item.name === "task_notification",
|
||||
)
|
||||
.map((event) => event.turnId);
|
||||
}
|
||||
|
||||
function startedTurnIds(events: AgentStreamEvent[]): (string | undefined)[] {
|
||||
return events
|
||||
.filter((event) => event.type === "turn_started")
|
||||
.map((event) => (event.type === "turn_started" ? event.turnId : undefined));
|
||||
}
|
||||
|
||||
async function createObservedSession() {
|
||||
sdkQueryFactory.mockImplementation(() => createPendingQueryMock());
|
||||
const session = await createSession();
|
||||
const internal: SessionStateInternals = asInternals(session);
|
||||
const queryMock = createPendingQueryMock();
|
||||
const events: AgentStreamEvent[] = [];
|
||||
session.subscribe((event) => events.push(event));
|
||||
async function route(...frames: Record<string, unknown>[]) {
|
||||
for (const frame of frames) await internal.routeSdkMessageFromPump(frame, queryMock);
|
||||
}
|
||||
return { session, internal, events, route };
|
||||
}
|
||||
|
||||
test("a completed command's notification and Claude's response to it are one turn", async () => {
|
||||
const { session, internal, events, route } = await createObservedSession();
|
||||
|
||||
await route(backgroundCommandNotification("sleep-40", "completed"), backgroundTasksChanged);
|
||||
const [notificationTurnId] = notificationRowTurnIds(events);
|
||||
expect(notificationTurnId).toEqual(expect.any(String));
|
||||
expect(startedTurnIds(events)).toEqual([]);
|
||||
expect(internal.turnState).toBe("idle");
|
||||
|
||||
await route(sessionState("running"), claudeTurnInit(), unboundTextDelta("SECOND REPLY"));
|
||||
expect(startedTurnIds(events)).toEqual([notificationTurnId]);
|
||||
expect(internal.turnState).toBe("autonomous");
|
||||
|
||||
await route(successResult(), sessionState("idle"));
|
||||
expect(internal.turnState).toBe("idle");
|
||||
|
||||
await session.close();
|
||||
});
|
||||
|
||||
test("a stopped command Claude does not respond to is a turn in itself, and the next notification starts the next turn", async () => {
|
||||
const { session, internal, events, route } = await createObservedSession();
|
||||
|
||||
await route(backgroundCommandNotification("sleep-300", "stopped"), backgroundTasksChanged);
|
||||
const [stoppedTurnId] = notificationRowTurnIds(events);
|
||||
expect(stoppedTurnId).toEqual(expect.any(String));
|
||||
expect(startedTurnIds(events)).toEqual([]);
|
||||
expect(internal.turnState).toBe("idle");
|
||||
|
||||
await route(backgroundCommandNotification("sleep-60", "completed"), backgroundTasksChanged);
|
||||
const [, completedTurnId] = notificationRowTurnIds(events);
|
||||
expect(completedTurnId).toEqual(expect.any(String));
|
||||
expect(completedTurnId).not.toBe(stoppedTurnId);
|
||||
|
||||
await route(sessionState("running"), claudeTurnInit(), successResult(), sessionState("idle"));
|
||||
expect(startedTurnIds(events)).toEqual([completedTurnId]);
|
||||
|
||||
await session.close();
|
||||
});
|
||||
|
||||
test("a run Claude announces as a queued command does not belong to the notification before it", async () => {
|
||||
const { session, events, route } = await createObservedSession();
|
||||
|
||||
await route(backgroundCommandNotification("sleep-300", "stopped"), backgroundTasksChanged);
|
||||
const [stoppedTurnId] = notificationRowTurnIds(events);
|
||||
|
||||
// A scheduled wake-up: Claude announces the queued command it starts before the run's init.
|
||||
await route(
|
||||
sessionState("running"),
|
||||
commandLifecycle("cron-prompt", "started"),
|
||||
claudeTurnInit(),
|
||||
);
|
||||
const [runTurnId] = startedTurnIds(events);
|
||||
expect(runTurnId).toEqual(expect.any(String));
|
||||
expect(runTurnId).not.toBe(stoppedTurnId);
|
||||
|
||||
await session.close();
|
||||
});
|
||||
|
||||
test("a run Claude starts for a finished background subagent does not belong to the notification before it", async () => {
|
||||
const { session, events, route } = await createObservedSession();
|
||||
|
||||
await route(helperTaskStarted);
|
||||
await route(backgroundCommandNotification("sleep-300", "stopped"), backgroundTasksChanged);
|
||||
const [stoppedTurnId] = notificationRowTurnIds(events);
|
||||
|
||||
await route(helperCompleted, claudeTurnInit());
|
||||
const [runTurnId] = startedTurnIds(events);
|
||||
expect(runTurnId).toEqual(expect.any(String));
|
||||
expect(runTurnId).not.toBe(stoppedTurnId);
|
||||
|
||||
await session.close();
|
||||
});
|
||||
|
||||
test("the user's next message starts its own turn after a notification Claude did not respond to", async () => {
|
||||
const { session, internal, events, route } = await createObservedSession();
|
||||
|
||||
await route(backgroundCommandNotification("sleep-300", "stopped"), backgroundTasksChanged);
|
||||
const [stoppedTurnId] = notificationRowTurnIds(events);
|
||||
|
||||
const { turnId } = await session.startTurn("PING");
|
||||
expect(turnId).not.toBe(stoppedTurnId);
|
||||
await route(claudeTurnInit(), successResult());
|
||||
expect(internal.activeForegroundTurnId).toBeNull();
|
||||
|
||||
// A run Claude starts later, with nothing announced, is not the stopped command's turn either.
|
||||
await route(claudeTurnInit());
|
||||
expect(startedTurnIds(events).at(-1)).not.toBe(stoppedTurnId);
|
||||
|
||||
await session.close();
|
||||
});
|
||||
|
||||
test("a run Claude starts without announcing anything belongs to the last notification", async () => {
|
||||
const { session, events, route } = await createObservedSession();
|
||||
|
||||
// Claude sends no frame for a Monitor event, so its wake-up reads as the response to the stop.
|
||||
await route(backgroundCommandNotification("sleep-300", "stopped"), backgroundTasksChanged);
|
||||
const [stoppedTurnId] = notificationRowTurnIds(events);
|
||||
|
||||
await route(sessionState("running"), claudeTurnInit());
|
||||
expect(startedTurnIds(events)).toEqual([stoppedTurnId]);
|
||||
|
||||
await session.close();
|
||||
});
|
||||
|
||||
test("a notification during a turn belongs to that turn", async () => {
|
||||
const { session, events, route } = await createObservedSession();
|
||||
|
||||
await route(claudeTurnInit());
|
||||
const [runTurnId] = startedTurnIds(events);
|
||||
await route(backgroundCommandNotification("sleep-40", "completed"));
|
||||
expect(notificationRowTurnIds(events)).toEqual([runTurnId]);
|
||||
await route(successResult(), claudeTurnInit());
|
||||
expect(startedTurnIds(events)).toHaveLength(2);
|
||||
expect(startedTurnIds(events)[1]).not.toBe(runTurnId);
|
||||
|
||||
await session.close();
|
||||
});
|
||||
|
||||
test("a background subagent's own job notification does not start a main-session turn", async () => {
|
||||
const { session, events, route } = await createObservedSession();
|
||||
|
||||
// The helper runs a background Bash of its own; its notification reports to the helper.
|
||||
await route(helperTaskStarted, {
|
||||
type: "assistant",
|
||||
parent_tool_use_id: "toolu_helper",
|
||||
session_id: "sess-1",
|
||||
message: {
|
||||
id: "msg-helper-bash",
|
||||
role: "assistant",
|
||||
model: "opus",
|
||||
content: [{ type: "tool_use", id: "toolu_subagent_bash", name: "Bash", input: {} }],
|
||||
},
|
||||
});
|
||||
|
||||
await route(backgroundCommandNotification("sleep-40", "completed"), backgroundTasksChanged);
|
||||
const [notificationTurnId] = notificationRowTurnIds(events);
|
||||
await route(subagentOwnedTaskNotification);
|
||||
expect(
|
||||
events.some(
|
||||
(event) =>
|
||||
event.type === "provider_subagent" &&
|
||||
event.event.type === "timeline" &&
|
||||
event.event.item.type === "tool_call" &&
|
||||
event.event.item.name === "task_notification",
|
||||
),
|
||||
).toBe(true);
|
||||
|
||||
await route(claudeTurnInit());
|
||||
expect(startedTurnIds(events)).toEqual([notificationTurnId]);
|
||||
|
||||
await session.close();
|
||||
});
|
||||
|
||||
@@ -1544,6 +1544,60 @@ describe("ClaudeAgentSession features", () => {
|
||||
}
|
||||
});
|
||||
|
||||
test("accepts a steer while Claude compacts, so the compaction is not interrupted", async () => {
|
||||
const { queryFactory, push } = createStreamingQueryMock();
|
||||
const client = new ClaudeAgentClient({
|
||||
logger,
|
||||
queryFactory,
|
||||
resolveBinary: async () => "/test/claude/bin",
|
||||
});
|
||||
const session = await client.createSession({ provider: "claude", cwd: process.cwd() });
|
||||
const events: AgentStreamEvent[] = [];
|
||||
const unsubscribe = session.subscribe((event) => events.push(event));
|
||||
try {
|
||||
const { turnId } = await session.startTurn("/compact");
|
||||
const input = queryFactory.mock.calls[0]?.[0].prompt as AsyncIterable<SDKUserMessage>;
|
||||
const iterator = input[Symbol.asyncIterator]();
|
||||
await expect(iterator.next()).resolves.toMatchObject({ value: { type: "user" } });
|
||||
await vi.waitFor(() =>
|
||||
expect(events).toContainEqual(
|
||||
expect.objectContaining({
|
||||
type: "timeline",
|
||||
item: expect.objectContaining({ type: "user_message" }),
|
||||
}),
|
||||
),
|
||||
);
|
||||
push({
|
||||
type: "system",
|
||||
subtype: "status",
|
||||
status: "compacting",
|
||||
session_id: "session-1",
|
||||
} as unknown as SDKMessage);
|
||||
await vi.waitFor(() =>
|
||||
expect(events).toContainEqual(
|
||||
expect.objectContaining({
|
||||
type: "timeline",
|
||||
item: { type: "compaction", status: "loading" },
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const admission = await session.steerActiveTurn?.("message during compaction", {
|
||||
expectedTurnId: turnId,
|
||||
});
|
||||
|
||||
// Claude Code holds a `next` message until the compaction finishes. Refusing it makes the
|
||||
// manager replace the turn, and the interrupt cancels the compaction.
|
||||
expect(admission).toEqual({ status: "accepted", providerMessageId: expect.any(String) });
|
||||
await expect(iterator.next()).resolves.toMatchObject({
|
||||
value: { type: "user", priority: "next" },
|
||||
});
|
||||
} finally {
|
||||
unsubscribe();
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("a human steer supersedes blocking permissions until Claude reads it", async () => {
|
||||
const { queryFactory } = createQueryMock();
|
||||
const client = new ClaudeAgentClient({
|
||||
|
||||
@@ -2339,6 +2339,14 @@ class ClaudeAgentSession implements AgentSession {
|
||||
private pendingPermissions = new Map<string, PendingPermission>();
|
||||
private activeForegroundTurnId: string | null = null;
|
||||
private autonomousTurn: AutonomousTurnState | null = null;
|
||||
/**
|
||||
* The turn the last background task notification started. A notification that arrives while no
|
||||
* turn runs starts a turn, and Claude's next run belongs to it unless Claude announces another
|
||||
* start first: a later notification starts the next turn, and a queued command (the user's
|
||||
* message, a scheduled wake-up) starts its own. When Claude does not respond, the notification is
|
||||
* a turn in itself. See observeNotificationTurn.
|
||||
*/
|
||||
private notificationTurnId: string | null = null;
|
||||
private readonly subscribers = new Set<(event: AgentStreamEvent) => void>();
|
||||
private readonly timelineAssembler = new TimelineAssembler();
|
||||
private readonly taskState = new ClaudeTaskState();
|
||||
@@ -2559,6 +2567,7 @@ class ClaudeAgentSession implements AgentSession {
|
||||
this.rememberRewindUserAnchor(sdkUserMessageId);
|
||||
const turnId = this.createTurnId("foreground");
|
||||
this.activeForegroundTurnId = turnId;
|
||||
this.notificationTurnId = null;
|
||||
this.foregroundHasVisibleActivity = false;
|
||||
this.activeTurnHasAssistantText = false;
|
||||
this.withheldErrorReply = [];
|
||||
@@ -2637,7 +2646,10 @@ class ClaudeAgentSession implements AgentSession {
|
||||
return { status: "unavailable" };
|
||||
}
|
||||
const activeTurnId = this.activeForegroundTurnId ?? this.autonomousTurn?.id;
|
||||
if (this.compacting || activeTurnId !== options.expectedTurnId) {
|
||||
// A compacting turn still takes a steer: Claude Code holds a `next` message until the
|
||||
// compaction finishes. Refusing it makes the manager replace the turn, and that interrupt
|
||||
// cancels the compaction.
|
||||
if (activeTurnId !== options.expectedTurnId) {
|
||||
return { status: "unavailable" };
|
||||
}
|
||||
|
||||
@@ -3096,6 +3108,7 @@ class ClaudeAgentSession implements AgentSession {
|
||||
this.activeForegroundQuery = null;
|
||||
this.activeForegroundInput = null;
|
||||
this.autonomousTurn = null;
|
||||
this.notificationTurnId = null;
|
||||
this.cancelCurrentTurn = null;
|
||||
this.turnState = "idle";
|
||||
this.sidechainTracker.clear();
|
||||
@@ -4136,8 +4149,9 @@ class ClaudeAgentSession implements AgentSession {
|
||||
return;
|
||||
}
|
||||
this.autonomousTurn = {
|
||||
id: this.createTurnId("autonomous"),
|
||||
id: this.notificationTurnId ?? this.createTurnId("autonomous"),
|
||||
};
|
||||
this.notificationTurnId = null;
|
||||
this.activeForegroundQuery = this.query;
|
||||
this.activeForegroundInput = this.input;
|
||||
this.activeTurnHasAssistantText = false;
|
||||
@@ -4407,6 +4421,20 @@ class ClaudeAgentSession implements AgentSession {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Tracks notificationTurnId from the starts Claude announces between turns. A task a subagent
|
||||
* started reports to that subagent, so its notification starts no main-session turn.
|
||||
*/
|
||||
private observeNotificationTurn(message: SDKMessage): void {
|
||||
if (this.activeForegroundTurnId || this.autonomousTurn) return;
|
||||
if (message.type === "system" && message.subtype === "task_notification") {
|
||||
if (this.taskProtocolSource.resolveTaskOwner(message.task_id, message.tool_use_id)) return;
|
||||
this.notificationTurnId = this.createTurnId("autonomous");
|
||||
} else if (readClaudeCommandLifecycle(message)?.state === "started") {
|
||||
this.notificationTurnId = null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Only the main session's own turn start opens an autonomous turn. Everything a background
|
||||
* subagent emits (its task frames, its own background jobs' notifications, rate limit events)
|
||||
@@ -4425,6 +4453,7 @@ class ClaudeAgentSession implements AgentSession {
|
||||
return;
|
||||
}
|
||||
this.observeMainTurnBracket(message);
|
||||
this.observeNotificationTurn(message);
|
||||
if (this.shouldSuppressStaleResult(message)) {
|
||||
return;
|
||||
}
|
||||
@@ -4975,6 +5004,7 @@ class ClaudeAgentSession implements AgentSession {
|
||||
type: "timeline",
|
||||
item: taskNotificationItem,
|
||||
provider: "claude",
|
||||
...(this.notificationTurnId ? { turnId: this.notificationTurnId } : {}),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -590,6 +590,36 @@ describe("OMP agent client and session", () => {
|
||||
);
|
||||
});
|
||||
|
||||
test("follows the thinking level OMP switches to on its own", async () => {
|
||||
const omp = new OmpHarness();
|
||||
await omp.start({ thinkingOptionId: "low" });
|
||||
const runtime = omp.runtime();
|
||||
|
||||
runtime.emit(
|
||||
OmpRuntimeEventSchema.parse({ type: "thinking_level_changed", thinkingLevel: "high" }),
|
||||
);
|
||||
await waitForImmediate();
|
||||
expect((await omp.requireSession().getRuntimeInfo()).thinkingOptionId).toBe("high");
|
||||
|
||||
runtime.emit(
|
||||
OmpRuntimeEventSchema.parse({
|
||||
type: "thinking_level_changed",
|
||||
thinkingLevel: "medium",
|
||||
configured: "auto",
|
||||
}),
|
||||
);
|
||||
runtime.emit(
|
||||
OmpRuntimeEventSchema.parse({
|
||||
type: "thinking_level_changed",
|
||||
thinkingLevel: "medium",
|
||||
configured: "auto",
|
||||
}),
|
||||
);
|
||||
await waitForImmediate();
|
||||
expect((await omp.requireSession().getRuntimeInfo()).thinkingOptionId).toBe("auto");
|
||||
expect(omp.eventTypes().filter((type) => type === "thinking_option_changed")).toHaveLength(2);
|
||||
});
|
||||
|
||||
test("shows OMP's fallback model without persisting it as the selected model", async () => {
|
||||
const omp = new OmpHarness();
|
||||
await omp.start({ model: "openrouter/google/gemini-3.8-flash" });
|
||||
|
||||
@@ -1660,7 +1660,30 @@ export class OmpAgentSession implements AgentSession {
|
||||
});
|
||||
}
|
||||
|
||||
// OMP changes the level on its own, e.g. `/switch @role` or a model switch that carries a level.
|
||||
private handleThinkingLevelChanged(event: OmpRuntimeEvent): boolean {
|
||||
if (event.type !== "thinking_level_changed") {
|
||||
return false;
|
||||
}
|
||||
const thinkingLevel = normalizeOmpThinkingOption(event.configured ?? event.thinkingLevel);
|
||||
if (!thinkingLevel || thinkingLevel === this.lastKnownThinkingOptionId) {
|
||||
return true;
|
||||
}
|
||||
this.lastKnownThinkingOptionId = thinkingLevel;
|
||||
this.config.thinkingOptionId = thinkingLevel;
|
||||
this.state = { ...this.state, thinkingLevel };
|
||||
this.emit({
|
||||
type: "thinking_option_changed",
|
||||
provider: this.provider,
|
||||
thinkingOptionId: thinkingLevel,
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
private handleExtraRuntimeEvent(event: OmpRuntimeEvent): boolean {
|
||||
if (this.handleThinkingLevelChanged(event)) {
|
||||
return true;
|
||||
}
|
||||
if (event.type === "model_changed") {
|
||||
void this.refreshState()
|
||||
.then(() =>
|
||||
|
||||
@@ -528,6 +528,14 @@ export const OmpRuntimeEventSchema = z.discriminatedUnion("type", [
|
||||
OmpRpcHostToolCancelRequestSchema,
|
||||
OmpRpcHostToolUpdateSchema,
|
||||
z.object({ type: z.literal("model_changed") }).passthrough(),
|
||||
z
|
||||
.object({
|
||||
type: z.literal("thinking_level_changed"),
|
||||
thinkingLevel: z.string().optional(),
|
||||
// The user's selector ("auto") when it differs from the level OMP runs.
|
||||
configured: z.string().optional(),
|
||||
})
|
||||
.passthrough(),
|
||||
]);
|
||||
|
||||
const OmpCommandBase = { id: z.string().optional() };
|
||||
|
||||
@@ -15,7 +15,7 @@ import { ensureValidJson } from "../../json-utils.js";
|
||||
import type { Logger } from "pino";
|
||||
|
||||
import type { AgentMode, AgentProvider, AgentSessionConfig } from "../agent-sdk-types.js";
|
||||
import type { AgentManager } from "../agent-manager.js";
|
||||
import type { AgentManager, ManagedAgent } from "../agent-manager.js";
|
||||
import { ActiveTurnBehaviorSchema, AgentProfileSchema } from "@getpaseo/protocol/messages";
|
||||
import type { DaemonConfigStore } from "../../daemon-config-store.js";
|
||||
import { featuresFromControls } from "@getpaseo/protocol/option-controls";
|
||||
@@ -2096,6 +2096,13 @@ function createToolCatalog(
|
||||
},
|
||||
);
|
||||
|
||||
// Match the WebSocket snapshot: idle agents can still own background work.
|
||||
async function projectLiveAgent(agent: ManagedAgent) {
|
||||
const snapshot = await serializeSnapshotWithMetadata(agentStorage, agent, childLogger);
|
||||
const backgroundWork = agentManager.getAgentBackgroundWorkSummary(agent.id);
|
||||
return backgroundWork ? { ...snapshot, backgroundWork } : snapshot;
|
||||
}
|
||||
|
||||
registerTool(
|
||||
"get_agent_status",
|
||||
{
|
||||
@@ -2113,11 +2120,7 @@ function createToolCatalog(
|
||||
async ({ agentId }) => {
|
||||
const snapshot = agentManager.getAgent(agentId);
|
||||
if (snapshot) {
|
||||
const structuredSnapshot = await serializeSnapshotWithMetadata(
|
||||
agentStorage,
|
||||
snapshot,
|
||||
childLogger,
|
||||
);
|
||||
const structuredSnapshot = await projectLiveAgent(snapshot);
|
||||
return {
|
||||
content: [],
|
||||
structuredContent: ensureValidJson({
|
||||
@@ -2185,8 +2188,7 @@ function createToolCatalog(
|
||||
manager: agentManager,
|
||||
storage: agentStorage,
|
||||
workspaces: options.workspaceRegistry,
|
||||
projectLive: (snapshot) =>
|
||||
serializeSnapshotWithMetadata(agentStorage, snapshot, childLogger),
|
||||
projectLive: projectLiveAgent,
|
||||
projectStored: (record) =>
|
||||
buildStoredAgentPayload(
|
||||
record,
|
||||
|
||||
@@ -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");
|
||||
|
||||
+122
@@ -0,0 +1,122 @@
|
||||
import { beforeAll, beforeEach, describe, expect, test } from "vitest";
|
||||
import { mkdtempSync, rmSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import pino from "pino";
|
||||
|
||||
import { ClaudeAgentClient } from "../agent/providers/claude/agent.js";
|
||||
import { DaemonClient } from "../test-utils/daemon-client.js";
|
||||
import { createTestPaseoDaemon } from "../test-utils/paseo-daemon.js";
|
||||
import { canRunRealProvider, getRealProviderConfig } from "./real-provider-test-config.js";
|
||||
|
||||
function tmpCwd(): string {
|
||||
return mkdtempSync(path.join(tmpdir(), "daemon-real-claude-steer-compaction-"));
|
||||
}
|
||||
|
||||
type TimelineItem = Awaited<
|
||||
ReturnType<DaemonClient["fetchAgentTimeline"]>
|
||||
>["entries"][number]["item"];
|
||||
|
||||
// The steer must land while the compaction is still running, or it takes the idle path.
|
||||
function isCompacting(items: TimelineItem[]): boolean {
|
||||
const statuses = new Set(
|
||||
items.flatMap((item) => (item.type === "compaction" ? [item.status] : [])),
|
||||
);
|
||||
return statuses.has("loading") && !statuses.has("completed");
|
||||
}
|
||||
|
||||
function hasAssistantText(items: TimelineItem[], text: string): boolean {
|
||||
return items.some((item) => item.type === "assistant_message" && item.text.includes(text));
|
||||
}
|
||||
|
||||
async function timelineItems(client: DaemonClient, agentId: string): Promise<TimelineItem[]> {
|
||||
const timeline = await client.fetchAgentTimeline(agentId, {
|
||||
direction: "tail",
|
||||
limit: 200,
|
||||
});
|
||||
return timeline.entries.map((entry) => entry.item);
|
||||
}
|
||||
|
||||
async function waitForTimeline(
|
||||
client: DaemonClient,
|
||||
agentId: string,
|
||||
check: (items: TimelineItem[]) => boolean,
|
||||
timeoutMs: number,
|
||||
label: string,
|
||||
): Promise<TimelineItem[]> {
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
for (;;) {
|
||||
const items = await timelineItems(client, agentId);
|
||||
if (check(items)) return items;
|
||||
if (Date.now() > deadline) {
|
||||
throw new Error(`Timed out: ${label}: ${JSON.stringify(items.slice(-6)).slice(0, 2000)}`);
|
||||
}
|
||||
await new Promise((resolve) => setTimeout(resolve, 100));
|
||||
}
|
||||
}
|
||||
|
||||
describe("daemon E2E (real claude) - steer during compaction", () => {
|
||||
let canRun = false;
|
||||
|
||||
beforeAll(async () => {
|
||||
canRun = await canRunRealProvider("claude");
|
||||
});
|
||||
|
||||
beforeEach((context) => {
|
||||
if (!canRun) context.skip();
|
||||
});
|
||||
|
||||
test("a steered message waits for a running /compact instead of cancelling it", async () => {
|
||||
const logger = pino({ level: "silent" });
|
||||
const cwd = tmpCwd();
|
||||
const daemon = await createTestPaseoDaemon({
|
||||
agentClients: { claude: new ClaudeAgentClient({ logger }) },
|
||||
logger,
|
||||
});
|
||||
const client = new DaemonClient({
|
||||
url: `ws://127.0.0.1:${daemon.port}/ws`,
|
||||
});
|
||||
try {
|
||||
await client.connect();
|
||||
await client.fetchAgents({ subscribe: {} });
|
||||
const agent = await client.createAgent({
|
||||
cwd,
|
||||
title: "claude-steer-during-compaction",
|
||||
...getRealProviderConfig("claude"),
|
||||
});
|
||||
await client.sendAgentMessage(
|
||||
agent.id,
|
||||
`Remember this list for later and reply exactly: NOTED. ${Array.from(
|
||||
{ length: 400 },
|
||||
(_, index) => `item-${index}`,
|
||||
).join(" ")}`,
|
||||
);
|
||||
const firstFinish = await client.waitForFinish(agent.id, 120_000);
|
||||
expect(firstFinish.status, firstFinish.error).toBe("idle");
|
||||
|
||||
await client.sendAgentMessage(agent.id, "/compact");
|
||||
await waitForTimeline(client, agent.id, isCompacting, 60_000, "Claude reports compacting");
|
||||
|
||||
await client.sendAgentMessage(agent.id, "Reply exactly: AFTER_COMPACT", {
|
||||
activeTurnBehavior: "steer",
|
||||
});
|
||||
await waitForTimeline(
|
||||
client,
|
||||
agent.id,
|
||||
(items) => hasAssistantText(items, "AFTER_COMPACT"),
|
||||
180_000,
|
||||
"Claude answers the steered message",
|
||||
);
|
||||
await client.waitForFinish(agent.id, 120_000);
|
||||
const finalItems = await timelineItems(client, agent.id);
|
||||
expect(
|
||||
finalItems.filter((item) => item.type === "compaction").map((item) => item.status),
|
||||
).toContain("completed");
|
||||
expect(hasAssistantText(finalItems, "Compaction canceled")).toBe(false);
|
||||
} finally {
|
||||
await client.close().catch(() => undefined);
|
||||
await daemon.close().catch(() => undefined);
|
||||
rmSync(cwd, { recursive: true, force: true });
|
||||
}
|
||||
}, 420_000);
|
||||
});
|
||||
@@ -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 () => {
|
||||
|
||||
@@ -327,6 +327,39 @@ test("unsubscribe cancels reconciliation queued by a write burst", async () => {
|
||||
expect(callback).toHaveBeenCalledTimes(callsAtClose);
|
||||
}, 20_000);
|
||||
|
||||
test("aborting a pending subscription stops its startup scan and rejects", async () => {
|
||||
const root = await createRoot();
|
||||
// More directories than the Linux backend watches: a scan that keeps walking after the abort
|
||||
// fails on the directory limit instead of rejecting with the abort reason.
|
||||
await Promise.all(
|
||||
Array.from({ length: 80 }, (_, outer) =>
|
||||
Promise.all(
|
||||
Array.from({ length: 70 }, (__, inner) =>
|
||||
mkdir(join(root, `dir-${outer}`, `nested-${inner}`), { recursive: true }),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
const observer = createObserver();
|
||||
const controller = new AbortController();
|
||||
const reason = new Error("setup deadline passed");
|
||||
const callback = vi.fn();
|
||||
|
||||
const subscription = observer.subscribe(root, callback, { signal: controller.signal });
|
||||
await new Promise((resolve) => setTimeout(resolve, 10));
|
||||
controller.abort(reason);
|
||||
|
||||
await expect(subscription).rejects.toBe(reason);
|
||||
expect(observer.getDiagnostics()).toMatchObject({
|
||||
activeObservationCount: 0,
|
||||
nativeHandleCount: 0,
|
||||
pendingReconciliationWorkCount: 0,
|
||||
});
|
||||
await writeFile(join(root, "dir-0", "after-abort.txt"), "late");
|
||||
await new Promise((resolve) => setTimeout(resolve, 100));
|
||||
expect(callback).not.toHaveBeenCalled();
|
||||
}, 20_000);
|
||||
|
||||
test("aggregate diagnostics return to their lifecycle baseline", async () => {
|
||||
const root = await createRoot();
|
||||
const observer = createObserver();
|
||||
|
||||
@@ -14,6 +14,8 @@ export interface FileChange {
|
||||
|
||||
export interface FileObserverOptions {
|
||||
ignore?: string[];
|
||||
// Aborting before `subscribe()` resolves stops the startup scan and rejects with the reason.
|
||||
signal?: AbortSignal;
|
||||
}
|
||||
|
||||
export type FileObserverCallback = (error: Error | null, events: FileChange[]) => void;
|
||||
@@ -105,7 +107,19 @@ class FileObserverService implements FileObserver {
|
||||
createBackend: this.createBackend,
|
||||
onClosed: () => state.observations.delete(observation),
|
||||
});
|
||||
await observation.start();
|
||||
const { signal } = options;
|
||||
signal?.throwIfAborted();
|
||||
const abort = () => void observation.close();
|
||||
signal?.addEventListener("abort", abort, { once: true });
|
||||
try {
|
||||
await observation.start();
|
||||
} finally {
|
||||
signal?.removeEventListener("abort", abort);
|
||||
}
|
||||
if (signal?.aborted) {
|
||||
await observation.close();
|
||||
throw signal.reason;
|
||||
}
|
||||
if (this.closePromise) {
|
||||
await observation.close();
|
||||
throw new Error("File observer is closed");
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
import { mkdtemp, rm } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { expect, test } from "vitest";
|
||||
import { createFileObserver } from "../index.js";
|
||||
import { createNativeRecursiveBackend } from "./native-recursive.js";
|
||||
import { createManagedObservation } from "./observation.js";
|
||||
import { createObserverPaths } from "./paths.js";
|
||||
|
||||
// Aborting a subscription closes its observation while start() may still be
|
||||
// reading the root, before the backend has started.
|
||||
test("closing an observation before its backend starts leaves no native watcher open", async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), "observation-close-"));
|
||||
const paths = createObserverPaths(process.platform);
|
||||
let openWatchers = 0;
|
||||
const observation = createManagedObservation({
|
||||
root,
|
||||
callback: () => {},
|
||||
options: {},
|
||||
paths,
|
||||
metrics: createFileObserver().getDiagnostics(),
|
||||
createBackend: (host) =>
|
||||
createNativeRecursiveBackend(host, paths, () => {
|
||||
openWatchers += 1;
|
||||
let open = true;
|
||||
return {
|
||||
close: () => {
|
||||
if (open) openWatchers -= 1;
|
||||
open = false;
|
||||
},
|
||||
on: () => {},
|
||||
};
|
||||
}),
|
||||
onClosed: () => {},
|
||||
});
|
||||
try {
|
||||
const started = observation.start();
|
||||
const closed = observation.close();
|
||||
await started;
|
||||
await closed;
|
||||
|
||||
expect(openWatchers).toBe(0);
|
||||
} finally {
|
||||
await rm(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
@@ -69,6 +69,9 @@ class Observation implements ManagedObservation, ObservationHost {
|
||||
if (!rootStats.isDirectory()) {
|
||||
throw new Error(`File observation requires a directory: ${this.root}`);
|
||||
}
|
||||
// An aborted subscription can close the observation while the root is being read; the backend
|
||||
// must not start after its close has already finished.
|
||||
if (!this.isActive()) return;
|
||||
try {
|
||||
await this.backend.start();
|
||||
} catch (error) {
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -153,6 +153,40 @@ describe("Hub relationship", () => {
|
||||
});
|
||||
});
|
||||
|
||||
test.each([false, true])(
|
||||
"reconnect advertises the current execution grant (initially %s)",
|
||||
async (initiallyGranted) => {
|
||||
relationship = await HubRelationshipHarness.start();
|
||||
await relationship.beginConnect("token", "https://hub.example", initiallyGranted).result;
|
||||
relationship.connectLatestSocket();
|
||||
if (initiallyGranted) await relationship.revokePermission("hub.execute");
|
||||
else await relationship.grantPermission("hub.execute");
|
||||
relationship.closeLatestSocket(1006);
|
||||
await relationship.retry();
|
||||
relationship.connectLatestSocket();
|
||||
|
||||
expect(relationship.serverInfoPermissions().at(-1)).toEqual(
|
||||
initiallyGranted ? [] : ["hub.execute"],
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
test("a permission mismatch retries the handshake with the same enrollment", async () => {
|
||||
relationship = await HubRelationshipHarness.start();
|
||||
await relationship.beginConnect().result;
|
||||
relationship.connectLatestSocket();
|
||||
const reason = "daemon session permissions do not match enrollment";
|
||||
relationship.closeLatestSocket(4403, reason);
|
||||
expect(await relationship.status()).toMatchObject({
|
||||
state: "reconnecting",
|
||||
lastError: expect.stringContaining("paseo hub permissions"),
|
||||
});
|
||||
await relationship.retry();
|
||||
await relationship.revokePermission("hub.execute");
|
||||
relationship.connectLatestSocket();
|
||||
expect(relationship.serverInfoPermissions().at(-1)).toEqual([]);
|
||||
});
|
||||
|
||||
test("Hub enrollment cannot widen the daemon's locally granted permissions", async () => {
|
||||
relationship = await HubRelationshipHarness.start();
|
||||
relationship.returnEnrollmentPermissions(["hub.execute", "daemon.manage"]);
|
||||
|
||||
@@ -246,7 +246,7 @@ export class HubRelationshipController implements HubRelationshipManagement {
|
||||
}
|
||||
|
||||
async start(): Promise<void> {
|
||||
if (this.record?.state === "active") this.openSocket(this.record, false);
|
||||
if (this.record?.state === "active") this.openSocket(false);
|
||||
if (this.record?.state === "pending") {
|
||||
const enrollmentGeneration = this.beginEnrollmentAttempt();
|
||||
try {
|
||||
@@ -441,7 +441,7 @@ export class HubRelationshipController implements HubRelationshipManagement {
|
||||
this.record = active;
|
||||
this.retry = null;
|
||||
this.retryAttempt = 0;
|
||||
this.openSocket(active, false);
|
||||
this.openSocket(false);
|
||||
} catch (error) {
|
||||
if (enrollmentGeneration !== this.enrollmentGeneration) return;
|
||||
if (error instanceof HubEnrollmentRejectedError) {
|
||||
@@ -455,15 +455,17 @@ export class HubRelationshipController implements HubRelationshipManagement {
|
||||
}
|
||||
}
|
||||
|
||||
private openSocket(record: ActiveRecord, reconnecting: boolean): void {
|
||||
private openSocket(reconnecting: boolean): void {
|
||||
const record = this.record;
|
||||
if (record?.state !== "active") return;
|
||||
const generation = ++this.generation;
|
||||
this.state = reconnecting ? "reconnecting" : "connecting";
|
||||
const events: HubSocketEvents = {
|
||||
connected: (socket, sessionProtocol) =>
|
||||
this.socketConnected(generation, record, socket, sessionProtocol),
|
||||
this.socketConnected(generation, socket, sessionProtocol),
|
||||
rejected: (statusCode) => this.socketRejected(generation, statusCode),
|
||||
closed: (code) => this.socketClosed(generation, record, code),
|
||||
failed: (error) => this.socketFailed(generation, record, error),
|
||||
closed: (code, reason) => this.socketClosed(generation, code, reason),
|
||||
failed: (error) => this.socketFailed(generation, error),
|
||||
};
|
||||
this.socket = this.options.remote.openSocket(
|
||||
{
|
||||
@@ -477,15 +479,14 @@ export class HubRelationshipController implements HubRelationshipManagement {
|
||||
|
||||
private socketConnected(
|
||||
generation: number,
|
||||
record: ActiveRecord,
|
||||
socket: WebSocketLike,
|
||||
sessionProtocol: "legacy" | "session-v1",
|
||||
): void {
|
||||
if (generation !== this.generation) {
|
||||
const record = this.record;
|
||||
if (generation !== this.generation || record?.state !== "active") {
|
||||
socket.close();
|
||||
return;
|
||||
}
|
||||
this.retryAttempt = 0;
|
||||
this.state = "connected";
|
||||
this.connectedAt = this.clock.now().toISOString();
|
||||
this.lastError = null;
|
||||
@@ -516,24 +517,31 @@ export class HubRelationshipController implements HubRelationshipManagement {
|
||||
this.revoke(`Hub rejected socket authentication (${statusCode})`);
|
||||
}
|
||||
|
||||
private socketClosed(generation: number, record: ActiveRecord, code: number): void {
|
||||
private socketClosed(generation: number, code: number, reason?: string): void {
|
||||
if (generation !== this.generation) return;
|
||||
if (code === 4403 && reason === "daemon session permissions do not match enrollment") {
|
||||
this.lastError =
|
||||
"Hub and daemon permissions differ. Run `paseo hub permissions grant <permission>` or `paseo hub permissions revoke <permission>` on this daemon to reapply your intended permissions.";
|
||||
this.scheduleSocket(true);
|
||||
return;
|
||||
}
|
||||
if (code === 4403) {
|
||||
this.revoke("Hub revoked this relationship");
|
||||
return;
|
||||
}
|
||||
if (this.record?.state === "active") this.scheduleSocket(record);
|
||||
if (this.record?.state === "active") this.scheduleSocket();
|
||||
}
|
||||
|
||||
private socketFailed(generation: number, record: ActiveRecord, error: Error): void {
|
||||
private socketFailed(generation: number, error: Error): void {
|
||||
if (generation !== this.generation) return;
|
||||
this.lastError = error.message;
|
||||
if (this.record?.state === "active") this.scheduleSocket(record);
|
||||
if (this.record?.state === "active") this.scheduleSocket();
|
||||
}
|
||||
|
||||
private scheduleSocket(record: ActiveRecord): void {
|
||||
private scheduleSocket(permissionMismatch = false): void {
|
||||
if (this.state === "connected" && !permissionMismatch) this.retryAttempt = 0;
|
||||
this.state = "reconnecting";
|
||||
this.schedule(() => this.openSocket(record, true));
|
||||
this.schedule(() => this.openSocket(true));
|
||||
}
|
||||
|
||||
private scheduleEnrollment(record: PendingRecord, enrollmentGeneration: number): void {
|
||||
|
||||
@@ -330,6 +330,27 @@ test.each([401, 403] as const)(
|
||||
},
|
||||
);
|
||||
|
||||
test("repeated permission mismatch closes back off until the Hub accepts the permissions", async () => {
|
||||
const mismatch = {
|
||||
closeCode: 4403,
|
||||
reason: "daemon session permissions do not match enrollment",
|
||||
};
|
||||
const hub = await UpgradeRejectingHub.start([
|
||||
mismatch,
|
||||
mismatch,
|
||||
{ closeCode: 1001, reason: "shutdown" },
|
||||
]);
|
||||
const clock = new ManualRelationshipClock();
|
||||
const controller = await connectController(hub, clock);
|
||||
await expect.poll(() => clock.scheduledAttempts()).toEqual([0]);
|
||||
clock.runNext();
|
||||
await expect.poll(() => clock.scheduledAttempts()).toEqual([0, 1]);
|
||||
expect(controller.status().state).toBe("reconnecting");
|
||||
clock.runNext();
|
||||
await expect.poll(() => clock.scheduledAttempts()).toEqual([0, 1, 0]);
|
||||
await controller.stop();
|
||||
});
|
||||
|
||||
test("controller redials after a transient socket response and releases both failed upgrades", async () => {
|
||||
const hub = await UpgradeRejectingHub.start([503, 401]);
|
||||
const clock = new ManualRelationshipClock();
|
||||
@@ -475,6 +496,8 @@ class SocketOutcomes {
|
||||
}
|
||||
}
|
||||
|
||||
type UpgradeOutcome = number | "stall" | { closeCode: number; reason: string };
|
||||
|
||||
class UpgradeRejectingHub {
|
||||
private readonly server = createServer(async (request, response) => {
|
||||
let body = "";
|
||||
@@ -493,8 +516,8 @@ class UpgradeRejectingHub {
|
||||
private attemptObserved = deferred<void>();
|
||||
private attempts = 0;
|
||||
|
||||
private constructor(private readonly statuses: Array<number | "stall">) {
|
||||
this.server.on("upgrade", (_request, socket) => {
|
||||
private constructor(private readonly statuses: UpgradeOutcome[]) {
|
||||
this.server.on("upgrade", (request, socket, head) => {
|
||||
const attempt = ++this.attempts;
|
||||
this.attemptObserved.resolve();
|
||||
this.attemptObserved = deferred<void>();
|
||||
@@ -506,6 +529,14 @@ class UpgradeRejectingHub {
|
||||
released.resolve();
|
||||
});
|
||||
const status = this.statuses[attempt - 1] ?? this.statuses.at(-1) ?? 503;
|
||||
if (typeof status === "object") {
|
||||
const ws = new WebSocketServer({ noServer: true });
|
||||
ws.handleUpgrade(request, socket, head, (peer) =>
|
||||
peer.close(status.closeCode, status.reason),
|
||||
);
|
||||
ws.close();
|
||||
return;
|
||||
}
|
||||
if (status === "stall") {
|
||||
socket.resume();
|
||||
return;
|
||||
@@ -520,7 +551,7 @@ class UpgradeRejectingHub {
|
||||
});
|
||||
}
|
||||
|
||||
static async start(statuses: Array<number | "stall">): Promise<UpgradeRejectingHub> {
|
||||
static async start(statuses: UpgradeOutcome[]): Promise<UpgradeRejectingHub> {
|
||||
const hub = new UpgradeRejectingHub(statuses);
|
||||
openUpgradeHubs.push(hub);
|
||||
openServers.push(hub.server);
|
||||
|
||||
@@ -46,7 +46,7 @@ export interface HubSocketCredentials {
|
||||
export interface HubSocketEvents {
|
||||
connected(socket: WebSocketLike, sessionProtocol: "legacy" | "session-v1"): void;
|
||||
rejected(statusCode: 401 | 403): void;
|
||||
closed(code: number): void;
|
||||
closed(code: number, reason?: string): void;
|
||||
failed(error: Error): void;
|
||||
}
|
||||
|
||||
@@ -227,11 +227,11 @@ export class DirectHubRelationshipRemote implements HubRelationshipRemote {
|
||||
}
|
||||
events.closed(1006);
|
||||
});
|
||||
socket.once("close", (code) => {
|
||||
socket.once("close", (code, reason) => {
|
||||
stopHeartbeat();
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
events.closed(code);
|
||||
events.closed(code, reason.toString());
|
||||
});
|
||||
socket.once("error", fail);
|
||||
return socket;
|
||||
|
||||
@@ -720,9 +720,9 @@ export class HubRelationshipHarness {
|
||||
this.rejectLatestSocket(code);
|
||||
}
|
||||
|
||||
closeLatestSocket(code: number): void {
|
||||
closeLatestSocket(code: number, reason?: string): void {
|
||||
const socket = this.latestSocket();
|
||||
socket.events.closed(code);
|
||||
socket.events.closed(code, reason);
|
||||
socket.socket.close(code);
|
||||
}
|
||||
|
||||
|
||||
@@ -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 {
|
||||
|
||||
+177
-7
@@ -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"], {
|
||||
|
||||
+35
-8
@@ -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 {
|
||||
|
||||
@@ -982,9 +982,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");
|
||||
@@ -3251,6 +3249,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 () => {
|
||||
|
||||
@@ -2195,6 +2195,7 @@ describe("WorkspaceGitServiceImpl D2 read methods", () => {
|
||||
expect(subscribe).toHaveBeenCalledTimes(1);
|
||||
expect(subscribe).toHaveBeenCalledWith(repoDir, expect.any(Function), {
|
||||
ignore: [join(repoDir, ".git"), ignoredRoot],
|
||||
signal: expect.any(AbortSignal),
|
||||
});
|
||||
|
||||
subscription.unsubscribe();
|
||||
|
||||
@@ -477,6 +477,56 @@ async function advanceThroughWorkingTreeRecoveryAttempts(
|
||||
}
|
||||
}
|
||||
|
||||
// Stalls every subscription for `watchPath` the way a CPU-starved startup scan does, until the
|
||||
// service aborts it at the subscribe deadline. Other paths subscribe immediately.
|
||||
function createStallingWatchSetup(watchPath: string) {
|
||||
const signals: AbortSignal[] = [];
|
||||
let acceptNext = false;
|
||||
let acceptedCallback: WatchCallback | null = null;
|
||||
const subscribe = vi.fn(
|
||||
async (directory: string, callback: WatchCallback, options?: { signal?: AbortSignal }) => {
|
||||
if (directory !== watchPath) {
|
||||
return createAsyncSubscription();
|
||||
}
|
||||
const signal = options?.signal ?? new AbortController().signal;
|
||||
signals.push(signal);
|
||||
if (acceptNext) {
|
||||
acceptNext = false;
|
||||
acceptedCallback = callback;
|
||||
return createAsyncSubscription();
|
||||
}
|
||||
return new Promise<ReturnType<typeof createAsyncSubscription>>((_resolve, reject) => {
|
||||
signal.addEventListener("abort", () => reject(signal.reason), { once: true });
|
||||
});
|
||||
},
|
||||
);
|
||||
return {
|
||||
subscribe,
|
||||
signals,
|
||||
acceptNextAttempt() {
|
||||
acceptNext = true;
|
||||
},
|
||||
failAcceptedWatcher() {
|
||||
acceptedCallback?.(new Error("accepted watcher stopped"), []);
|
||||
},
|
||||
async expectAttemptAbortedAtDeadline() {
|
||||
const signal = signals.at(-1);
|
||||
expect(signal?.aborted).toBe(false);
|
||||
await vi.advanceTimersByTimeAsync(WORKSPACE_GIT_WATCHER_SUBSCRIBE_TIMEOUT_MS);
|
||||
expect(signal?.aborted).toBe(true);
|
||||
expect(signal?.reason).toMatchObject({ name: "WorkspaceGitWatcherSubscriptionTimeoutError" });
|
||||
},
|
||||
async expectNextAttemptAfter(delayMs: number, service: WorkspaceGitServiceImpl) {
|
||||
const attempts = signals.length;
|
||||
await vi.advanceTimersByTimeAsync(delayMs - 1);
|
||||
await waitForRefreshesToSettle(service);
|
||||
expect(signals).toHaveLength(attempts);
|
||||
await vi.advanceTimersByTimeAsync(1);
|
||||
await settle(() => expect(signals).toHaveLength(attempts + 1));
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe("WorkspaceGitServiceImpl", () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
@@ -1573,6 +1623,7 @@ describe("WorkspaceGitServiceImpl", () => {
|
||||
expect(subscribe).toHaveBeenCalledTimes(1);
|
||||
expect(subscribe).toHaveBeenCalledWith(REPO_CWD, expect.any(Function), {
|
||||
ignore: [join(REPO_CWD, ".git")],
|
||||
signal: expect.any(AbortSignal),
|
||||
});
|
||||
|
||||
subscription.unsubscribe();
|
||||
@@ -1648,6 +1699,67 @@ describe("WorkspaceGitServiceImpl", () => {
|
||||
15_000,
|
||||
);
|
||||
|
||||
test.each(["repository metadata", "working tree"])(
|
||||
"aborts each timed-out %s watcher setup and backs retries off toward an hour",
|
||||
async (kind) => {
|
||||
const watchPath = kind === "repository metadata" ? join(REPO_CWD, ".git") : REPO_CWD;
|
||||
const setup = createStallingWatchSetup(watchPath);
|
||||
const getCheckoutStatus = vi.fn(async (cwd: string) => createCheckoutStatus(cwd));
|
||||
const service = createService({ subscribe: setup.subscribe, getCheckoutStatus });
|
||||
const subscription = service.registerWorkspace({ cwd: REPO_CWD }, vi.fn());
|
||||
try {
|
||||
await settle(() => expect(setup.signals).toHaveLength(1));
|
||||
await setup.expectAttemptAbortedAtDeadline();
|
||||
await waitForObservationToSettle(service, 1);
|
||||
for (const delayMs of [
|
||||
30_000, 60_000, 120_000, 240_000, 480_000, 960_000, 1_920_000, 3_600_000,
|
||||
]) {
|
||||
await setup.expectNextAttemptAfter(delayMs, service);
|
||||
await setup.expectAttemptAbortedAtDeadline();
|
||||
}
|
||||
// Degraded polling keeps the checkout fresh while the watcher waits out an hour.
|
||||
const readsBeforeCappedWait = getCheckoutStatus.mock.calls.length;
|
||||
await setup.expectNextAttemptAfter(3_600_000, service);
|
||||
expect(getCheckoutStatus.mock.calls.length).toBeGreaterThanOrEqual(
|
||||
readsBeforeCappedWait + 59,
|
||||
);
|
||||
} finally {
|
||||
subscription.unsubscribe();
|
||||
await service.dispose();
|
||||
}
|
||||
},
|
||||
30_000,
|
||||
);
|
||||
|
||||
test.each(["repository metadata", "working tree"])(
|
||||
"an accepted %s watcher subscription resets the setup-timeout backoff",
|
||||
async (kind) => {
|
||||
const watchPath = kind === "repository metadata" ? join(REPO_CWD, ".git") : REPO_CWD;
|
||||
const setup = createStallingWatchSetup(watchPath);
|
||||
const service = createService({ subscribe: setup.subscribe });
|
||||
const subscription = service.registerWorkspace({ cwd: REPO_CWD }, vi.fn());
|
||||
try {
|
||||
await settle(() => expect(setup.signals).toHaveLength(1));
|
||||
await setup.expectAttemptAbortedAtDeadline();
|
||||
for (const delayMs of [30_000, 60_000, 120_000, 240_000, 480_000]) {
|
||||
await setup.expectNextAttemptAfter(delayMs, service);
|
||||
await setup.expectAttemptAbortedAtDeadline();
|
||||
}
|
||||
setup.acceptNextAttempt();
|
||||
await setup.expectNextAttemptAfter(960_000, service);
|
||||
setup.failAcceptedWatcher();
|
||||
// The ordinary recovery ladder's ceiling applies again, not the 32-minute timeout step.
|
||||
await setup.expectNextAttemptAfter(300_000, service);
|
||||
await setup.expectAttemptAbortedAtDeadline();
|
||||
await setup.expectNextAttemptAfter(300_000, service);
|
||||
} finally {
|
||||
subscription.unsubscribe();
|
||||
await service.dispose();
|
||||
}
|
||||
},
|
||||
30_000,
|
||||
);
|
||||
|
||||
test.each(["repository metadata", "working tree"])(
|
||||
"ignores expired %s watcher callbacks after recovery",
|
||||
async (kind) => {
|
||||
@@ -1873,6 +1985,7 @@ describe("WorkspaceGitServiceImpl", () => {
|
||||
expect(subscription.repoRoot).toBeNull();
|
||||
expect(subscribe).toHaveBeenCalledWith(plainCwd, expect.any(Function), {
|
||||
ignore: [join(plainCwd, ".git")],
|
||||
signal: expect.any(AbortSignal),
|
||||
});
|
||||
expect(vi.getTimerCount()).toBe(1);
|
||||
|
||||
|
||||
@@ -123,6 +123,11 @@ const WATCH_RECOVERY_BASE_DELAY_MS = 30_000;
|
||||
// restart, which kills running agents. Back off, but keep trying.
|
||||
const WATCH_RECOVERY_MAX_DELAY_MS = 300_000;
|
||||
const WATCH_RECOVERY_MAX_BACKOFF_STEPS = 4;
|
||||
// A startup scan that missed the subscribe deadline on a CPU-starved host misses it again on the
|
||||
// next attempt, and every attempt repeats the full scan. Consecutive setup timeouts therefore
|
||||
// keep doubling the recovery delay past the ladder cap, up to an hour.
|
||||
const WATCH_SETUP_TIMEOUT_RECOVERY_MAX_DELAY_MS = 3_600_000;
|
||||
const WATCH_SETUP_TIMEOUT_MAX_BACKOFF_STEPS = 7;
|
||||
// Auxiliary reads may reuse cached values within this window; snapshots do not expire on read.
|
||||
const WORKSPACE_GIT_AUXILIARY_READ_TTL_MS = 15_000;
|
||||
// Non-forced refresh triggers share this minimum gap to absorb watcher/self-heal bursts; force bypasses it.
|
||||
@@ -574,6 +579,10 @@ interface WatchRecoveryState {
|
||||
// use (SMB/NFS, Docker virtiofs, some FUSE) resets the ladder on every
|
||||
// attempt and the backoff never engages.
|
||||
establishedAt: number | null;
|
||||
// Setup attempts that hit WORKSPACE_GIT_WATCHER_SUBSCRIBE_TIMEOUT_MS since the last accepted
|
||||
// subscription. Reset on acceptance: finishing the startup scan in time is the proof that
|
||||
// the next attempt is affordable.
|
||||
setupTimeoutCount: number;
|
||||
}
|
||||
|
||||
function setsEqual(left: ReadonlySet<string>, right: ReadonlySet<string>): boolean {
|
||||
@@ -1519,7 +1528,7 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
|
||||
fallbackPolling: false,
|
||||
fallbackPollTimer: null,
|
||||
fallbackPollQuietTickCount: 0,
|
||||
recovery: { attemptCount: 0, timer: null, establishedAt: null },
|
||||
recovery: { attemptCount: 0, timer: null, establishedAt: null, setupTimeoutCount: 0 },
|
||||
listeners: new Set(),
|
||||
closed: false,
|
||||
};
|
||||
@@ -1549,9 +1558,12 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
|
||||
let removeAbortListener = () => {};
|
||||
let unsubscribePromise: Promise<void> | null = null;
|
||||
let subscriptionPromise: Promise<FileObserverSubscription>;
|
||||
// Abandoning the race is not enough: the observer's startup scan would keep walking the
|
||||
// tree after the deadline. Abort it so a timed-out attempt stops costing CPU.
|
||||
const setupController = new AbortController();
|
||||
try {
|
||||
subscriptionPromise = this.deps
|
||||
.subscribe(watchPath, callback, options)
|
||||
.subscribe(watchPath, callback, { ...options, signal: setupController.signal })
|
||||
.finally(onSubscribeSettled);
|
||||
} catch (error) {
|
||||
onSubscribeSettled();
|
||||
@@ -1570,12 +1582,15 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
|
||||
const timeoutPromise = new Promise<never>((_resolve, reject) => {
|
||||
timeout = setTimeout(() => {
|
||||
outcome = "expired";
|
||||
reject(new WorkspaceGitWatcherSubscriptionTimeoutError(watchPath));
|
||||
const error = new WorkspaceGitWatcherSubscriptionTimeoutError(watchPath);
|
||||
setupController.abort(error);
|
||||
reject(error);
|
||||
}, WORKSPACE_GIT_WATCHER_SUBSCRIBE_TIMEOUT_MS);
|
||||
});
|
||||
const disposalPromise = new Promise<never>((_resolve, reject) => {
|
||||
const rejectForDisposal = () => {
|
||||
outcome = "expired";
|
||||
setupController.abort(signal.reason);
|
||||
reject(signal.reason);
|
||||
};
|
||||
if (signal.aborted) {
|
||||
@@ -1710,6 +1725,7 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
|
||||
// `scheduleWorkingTreeWatchRecovery` only resets the ladder once this
|
||||
// one has survived long enough to prove itself durable.
|
||||
target.recovery.establishedAt = this.deps.now().getTime();
|
||||
target.recovery.setupTimeoutCount = 0;
|
||||
if (options?.replaceFallback && target.repoRoot !== null) {
|
||||
target.fallbackPolling = false;
|
||||
if (target.fallbackPollTimer) {
|
||||
@@ -1730,6 +1746,7 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
|
||||
{ err: error, cwd: target.cwd },
|
||||
"Failed to start working tree watcher; using degraded polling",
|
||||
);
|
||||
this.noteWatchSetupFailure(target.recovery, error);
|
||||
if (!options?.replaceFallback) {
|
||||
this.startWorkingTreeWatchFallback(target, "watcher_setup_failed");
|
||||
}
|
||||
@@ -1952,11 +1969,26 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
|
||||
}
|
||||
recovery.establishedAt = null;
|
||||
recovery.attemptCount += 1;
|
||||
return Math.min(
|
||||
const ladderDelayMs = Math.min(
|
||||
WATCH_RECOVERY_BASE_DELAY_MS *
|
||||
2 ** Math.min(recovery.attemptCount - 1, WATCH_RECOVERY_MAX_BACKOFF_STEPS),
|
||||
WATCH_RECOVERY_MAX_DELAY_MS,
|
||||
);
|
||||
if (recovery.setupTimeoutCount === 0) {
|
||||
return ladderDelayMs;
|
||||
}
|
||||
const setupTimeoutDelayMs = Math.min(
|
||||
WATCH_RECOVERY_BASE_DELAY_MS *
|
||||
2 ** Math.min(recovery.setupTimeoutCount - 1, WATCH_SETUP_TIMEOUT_MAX_BACKOFF_STEPS),
|
||||
WATCH_SETUP_TIMEOUT_RECOVERY_MAX_DELAY_MS,
|
||||
);
|
||||
return Math.max(ladderDelayMs, setupTimeoutDelayMs);
|
||||
}
|
||||
|
||||
private noteWatchSetupFailure(recovery: WatchRecoveryState, error: unknown): void {
|
||||
if (error instanceof WorkspaceGitWatcherSubscriptionTimeoutError) {
|
||||
recovery.setupTimeoutCount += 1;
|
||||
}
|
||||
}
|
||||
|
||||
private scheduleWorkingTreeWatchRecovery(target: WorkingTreeWatchTarget): void {
|
||||
@@ -2430,7 +2462,7 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
|
||||
fallbackPolling: false,
|
||||
fallbackPollTimer: null,
|
||||
fallbackPollQuietTickCount: 0,
|
||||
recovery: { attemptCount: 0, timer: null, establishedAt: null },
|
||||
recovery: { attemptCount: 0, timer: null, establishedAt: null, setupTimeoutCount: 0 },
|
||||
intervalId: null,
|
||||
fetchInFlight: false,
|
||||
bufferedFetchMetadataEvents: [],
|
||||
@@ -2580,6 +2612,7 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
|
||||
// subscribe success alone, only record when this subscription was
|
||||
// established.
|
||||
target.recovery.establishedAt = this.deps.now().getTime();
|
||||
target.recovery.setupTimeoutCount = 0;
|
||||
if (options?.replaceFallback) {
|
||||
target.fallbackPolling = false;
|
||||
if (target.fallbackPollTimer) {
|
||||
@@ -2603,6 +2636,7 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
|
||||
{ err: error, repoGitRoot: target.repoGitRoot },
|
||||
"Failed to start repository metadata watcher; using degraded polling",
|
||||
);
|
||||
this.noteWatchSetupFailure(target.recovery, error);
|
||||
if (!options?.replaceFallback) {
|
||||
this.startRepoMetadataFallback(target);
|
||||
}
|
||||
|
||||
@@ -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 }
|
||||
: {}),
|
||||
|
||||
@@ -19,7 +19,7 @@ import {
|
||||
type TerminalWorkerRecord,
|
||||
} from "./terminal-worker-record.js";
|
||||
import { createTerminalWorkerRecordPublisher } from "./terminal-worker-record-publisher.js";
|
||||
import { resolveTerminalWorkerSocketPath } from "./terminal-worker-socket-path.js";
|
||||
import { listenOnTerminalWorkerSocket } from "./terminal-worker-socket-path.js";
|
||||
import {
|
||||
TERMINAL_WORKER_PROTOCOL_OVERRIDE_ENV,
|
||||
TERMINAL_WORKER_PROTOCOL_VERSION,
|
||||
@@ -700,23 +700,25 @@ function runWorker(argv: string[]): void {
|
||||
}
|
||||
|
||||
async function start(): Promise<void> {
|
||||
const socketPath = resolveTerminalWorkerSocketPath({
|
||||
const { socketPath, listener } = await listenOnTerminalWorkerSocket({
|
||||
paseoHome: args.paseoHome,
|
||||
workerPid: process.pid,
|
||||
recordId: args.recordId,
|
||||
listen: (candidatePath) => {
|
||||
if (process.platform !== "win32") {
|
||||
rmSync(candidatePath, { force: true });
|
||||
}
|
||||
const listening = createServer(handleConnection);
|
||||
return new Promise<Server>((resolve, reject) => {
|
||||
listening.once("error", reject);
|
||||
listening.listen(candidatePath, () => {
|
||||
listening.off("error", reject);
|
||||
resolve(listening);
|
||||
});
|
||||
});
|
||||
},
|
||||
});
|
||||
if (process.platform !== "win32") {
|
||||
rmSync(socketPath, { force: true });
|
||||
}
|
||||
const listening = createServer(handleConnection);
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
listening.once("error", reject);
|
||||
listening.listen(socketPath, () => {
|
||||
listening.off("error", reject);
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
server = listening;
|
||||
server = listener;
|
||||
if (process.platform !== "win32") {
|
||||
chmodSync(socketPath, PRIVATE_FILE_MODE);
|
||||
}
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { chmodSync, mkdirSync, mkdtempSync, rmSync, symlinkSync } from "node:fs";
|
||||
import { createServer } from "node:net";
|
||||
import { createServer, type Server } from "node:net";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { isPlatform } from "../test-utils/platform.js";
|
||||
import {
|
||||
listenOnTerminalWorkerSocket,
|
||||
resolveTerminalWorkerSocketPath,
|
||||
TerminalWorkerSocketPathError,
|
||||
} from "./terminal-worker-socket-path.js";
|
||||
@@ -25,7 +26,36 @@ function longHome(root: string): string {
|
||||
return home;
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
const openServers: Server[] = [];
|
||||
|
||||
function listenFor(socketPath: string): Promise<Server> {
|
||||
const server = createServer();
|
||||
return new Promise((resolve, reject) => {
|
||||
server.once("error", reject);
|
||||
server.listen(socketPath, () => {
|
||||
openServers.push(server);
|
||||
resolve(server);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// Stands in for a filesystem that passes the directory checks but refuses AF_UNIX bind, as AFS
|
||||
// does with EPERM.
|
||||
function refuseBindUnder(directory: string, code: string) {
|
||||
return (socketPath: string): Promise<Server> => {
|
||||
if (socketPath.startsWith(directory + path.sep)) {
|
||||
return Promise.reject(
|
||||
Object.assign(new Error(`listen ${code}: ${socketPath}`), { code, syscall: "listen" }),
|
||||
);
|
||||
}
|
||||
return listenFor(socketPath);
|
||||
};
|
||||
}
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(
|
||||
openServers.splice(0).map((server) => new Promise((resolve) => server.close(resolve))),
|
||||
);
|
||||
for (const dir of temporaryDirs.splice(0)) {
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
@@ -142,6 +172,66 @@ describe.skipIf(isPlatform("win32"))("terminal worker socket path", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe.skipIf(isPlatform("win32"))("terminal worker socket listen", () => {
|
||||
it("falls back to the next directory when the home's filesystem refuses the bind", async () => {
|
||||
const home = makeDir("tw-b-", "/tmp");
|
||||
const tmpDir = makeDir("tw-t-", "/tmp");
|
||||
const homeSocketDirectory = path.join(home, "terminal-worker", "sock");
|
||||
const { socketPath, listener } = await listenOnTerminalWorkerSocket({
|
||||
paseoHome: home,
|
||||
recordId: "test",
|
||||
workerPid: 11,
|
||||
tmpDir,
|
||||
listen: refuseBindUnder(homeSocketDirectory, "EPERM"),
|
||||
});
|
||||
expect(path.dirname(socketPath)).toBe(path.join(tmpDir, `paseo-${process.getuid!()}`));
|
||||
expect(listener.address()).toBe(socketPath);
|
||||
});
|
||||
|
||||
it("throws a listen error that does not mean the filesystem refuses sockets", async () => {
|
||||
const home = makeDir("tw-u-", "/tmp");
|
||||
const homeSocketDirectory = path.join(home, "terminal-worker", "sock");
|
||||
await expect(
|
||||
listenOnTerminalWorkerSocket({
|
||||
paseoHome: home,
|
||||
recordId: "test",
|
||||
workerPid: 12,
|
||||
tmpDir: makeDir("tw-t-", "/tmp"),
|
||||
listen: refuseBindUnder(homeSocketDirectory, "EADDRINUSE"),
|
||||
}),
|
||||
).rejects.toMatchObject({ code: "EADDRINUSE" });
|
||||
});
|
||||
|
||||
it("names every candidate's bind error when no directory accepts a socket", async () => {
|
||||
const home = makeDir("tw-n-", "/tmp");
|
||||
const tmpDir = makeDir("tw-t-", "/tmp");
|
||||
let caught: unknown;
|
||||
try {
|
||||
await listenOnTerminalWorkerSocket({
|
||||
paseoHome: home,
|
||||
recordId: "test",
|
||||
workerPid: 13,
|
||||
tmpDir,
|
||||
listen: refuseBindUnder("", "EPERM"),
|
||||
});
|
||||
} catch (error) {
|
||||
caught = error;
|
||||
}
|
||||
expect(caught).toBeInstanceOf(TerminalWorkerSocketPathError);
|
||||
const rejected = (caught as TerminalWorkerSocketPathError).rejected;
|
||||
expect(rejected.slice(0, 2)).toEqual([
|
||||
expect.objectContaining({
|
||||
path: expect.stringContaining(path.join(home, "terminal-worker", "sock")),
|
||||
reason: "cannot bind a socket here (EPERM)",
|
||||
}),
|
||||
expect.objectContaining({
|
||||
path: expect.stringContaining(path.join(tmpDir, `paseo-${process.getuid!()}`)),
|
||||
reason: "cannot bind a socket here (EPERM)",
|
||||
}),
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
it("uses a separate socket for each record even when its pid is reused", () => {
|
||||
const paseoHome = makeDir("tw-id-");
|
||||
const first = resolveTerminalWorkerSocketPath({ paseoHome, workerPid: 42, recordId: "old" });
|
||||
|
||||
@@ -14,6 +14,9 @@ const SOCKET_PATH_BYTE_BUDGET: Partial<Record<NodeJS.Platform, number>> = {
|
||||
};
|
||||
const DEFAULT_SOCKET_PATH_BYTE_BUDGET = 103;
|
||||
const OWNER_ONLY_MODE = 0o700;
|
||||
// Bind errors that mean the directory's filesystem cannot hold a Unix socket. AFS and some other
|
||||
// network filesystems pass the directory checks and then refuse AF_UNIX bind with EPERM.
|
||||
const SOCKET_UNSUPPORTED_BIND_CODES = new Set(["EPERM", "EACCES", "EOPNOTSUPP", "ENOTSUP"]);
|
||||
|
||||
export interface TerminalWorkerSocketPathInput {
|
||||
paseoHome: string;
|
||||
@@ -24,6 +27,16 @@ export interface TerminalWorkerSocketPathInput {
|
||||
uid?: number;
|
||||
}
|
||||
|
||||
export interface TerminalWorkerSocketListenInput<T> extends TerminalWorkerSocketPathInput {
|
||||
/** Binds a fresh listener at the path, removing any stale socket there first. */
|
||||
listen: (socketPath: string) => Promise<T>;
|
||||
}
|
||||
|
||||
export interface TerminalWorkerSocketListener<T> {
|
||||
socketPath: string;
|
||||
listener: T;
|
||||
}
|
||||
|
||||
export interface RejectedSocketCandidate {
|
||||
path: string;
|
||||
byteLength: number;
|
||||
@@ -36,7 +49,7 @@ export class TerminalWorkerSocketPathError extends Error {
|
||||
constructor(rejected: RejectedSocketCandidate[], budget: number) {
|
||||
super(
|
||||
[
|
||||
`No terminal worker socket path fits ${budget} bytes in an owner-only directory:`,
|
||||
`No terminal worker socket path fits ${budget} bytes in an owner-only directory that accepts a socket:`,
|
||||
...rejected.map(
|
||||
(candidate) => ` ${candidate.path} (${candidate.byteLength} bytes): ${candidate.reason}`,
|
||||
),
|
||||
@@ -57,18 +70,73 @@ export function terminalWorkerSocketId(paseoHome: string, workerPid: number): st
|
||||
* Picks (and creates) the socket path a worker listens on. Windows uses a named pipe; POSIX
|
||||
* tries $PASEO_HOME/terminal-worker/sock, then <tmpdir>/paseo-<uid>, then /tmp/paseo-<uid>.
|
||||
* A shared root is never chmodded: an existing directory there is used only when it is a real
|
||||
* directory owned by this user with mode 0700.
|
||||
* directory owned by this user with mode 0700. It does not bind; the worker listens through
|
||||
* `listenOnTerminalWorkerSocket`, which also skips directories that refuse a socket.
|
||||
*/
|
||||
export function resolveTerminalWorkerSocketPath(input: TerminalWorkerSocketPathInput): string {
|
||||
const platform = input.platform ?? process.platform;
|
||||
const id = terminalWorkerSocketId(input.paseoHome, input.workerPid) + "-" + input.recordId;
|
||||
if (platform === "win32") {
|
||||
return `\\\\.\\pipe\\paseo-tw-${id}`;
|
||||
return windowsPipePath(input);
|
||||
}
|
||||
const budget = socketPathByteBudget(platform);
|
||||
const rejected: RejectedSocketCandidate[] = [];
|
||||
for (const candidate of eligibleUnixSocketPaths(input, budget, rejected)) {
|
||||
return candidate.path;
|
||||
}
|
||||
throw new TerminalWorkerSocketPathError(rejected, budget);
|
||||
}
|
||||
|
||||
/**
|
||||
* Listens on the first candidate path that accepts a socket. A bind refused by the filesystem
|
||||
* moves on to the next candidate; any other listen error (EADDRINUSE, ...) is thrown as is.
|
||||
*/
|
||||
export async function listenOnTerminalWorkerSocket<T>(
|
||||
input: TerminalWorkerSocketListenInput<T>,
|
||||
): Promise<TerminalWorkerSocketListener<T>> {
|
||||
const { listen } = input;
|
||||
const platform = input.platform ?? process.platform;
|
||||
if (platform === "win32") {
|
||||
const socketPath = windowsPipePath(input);
|
||||
return { socketPath, listener: await listen(socketPath) };
|
||||
}
|
||||
const budget = socketPathByteBudget(platform);
|
||||
const rejected: RejectedSocketCandidate[] = [];
|
||||
for (const candidate of eligibleUnixSocketPaths(input, budget, rejected)) {
|
||||
try {
|
||||
return { socketPath: candidate.path, listener: await listen(candidate.path) };
|
||||
} catch (error) {
|
||||
const code = (error as NodeJS.ErrnoException).code;
|
||||
if (!code || !SOCKET_UNSUPPORTED_BIND_CODES.has(code)) throw error;
|
||||
rejected.push({
|
||||
path: candidate.path,
|
||||
byteLength: candidate.byteLength,
|
||||
reason: `cannot bind a socket here (${code})`,
|
||||
});
|
||||
}
|
||||
}
|
||||
throw new TerminalWorkerSocketPathError(rejected, budget);
|
||||
}
|
||||
|
||||
function windowsPipePath(input: TerminalWorkerSocketPathInput): string {
|
||||
return `\\\\.\\pipe\\paseo-tw-${socketFileId(input)}`;
|
||||
}
|
||||
|
||||
function socketFileId(input: TerminalWorkerSocketPathInput): string {
|
||||
return terminalWorkerSocketId(input.paseoHome, input.workerPid) + "-" + input.recordId;
|
||||
}
|
||||
|
||||
function socketPathByteBudget(platform: NodeJS.Platform): number {
|
||||
return SOCKET_PATH_BYTE_BUDGET[platform] ?? DEFAULT_SOCKET_PATH_BYTE_BUDGET;
|
||||
}
|
||||
|
||||
/** Yields each candidate that fits the budget in an owner-only directory, in order. */
|
||||
function* eligibleUnixSocketPaths(
|
||||
input: TerminalWorkerSocketPathInput,
|
||||
budget: number,
|
||||
rejected: RejectedSocketCandidate[],
|
||||
): Generator<{ path: string; byteLength: number }> {
|
||||
const uid = input.uid ?? process.getuid?.() ?? 0;
|
||||
const budget = SOCKET_PATH_BYTE_BUDGET[platform] ?? DEFAULT_SOCKET_PATH_BYTE_BUDGET;
|
||||
const fileName = `tw-${id}.sock`;
|
||||
const fileName = `tw-${socketFileId(input)}.sock`;
|
||||
const homeSocketDirectory = path.join(terminalWorkerDirectory(input.paseoHome), "sock");
|
||||
const candidates: Array<{ directory: string; prepare: () => string | null }> = [
|
||||
{
|
||||
@@ -87,7 +155,6 @@ export function resolveTerminalWorkerSocketPath(input: TerminalWorkerSocketPathI
|
||||
}),
|
||||
];
|
||||
|
||||
const rejected: RejectedSocketCandidate[] = [];
|
||||
const seen = new Set<string>();
|
||||
for (const candidate of candidates) {
|
||||
const socketPath = path.join(candidate.directory, fileName);
|
||||
@@ -108,9 +175,8 @@ export function resolveTerminalWorkerSocketPath(input: TerminalWorkerSocketPathI
|
||||
rejected.push({ path: socketPath, byteLength, reason: problem });
|
||||
continue;
|
||||
}
|
||||
return socketPath;
|
||||
yield { path: socketPath, byteLength };
|
||||
}
|
||||
throw new TerminalWorkerSocketPathError(rejected, budget);
|
||||
}
|
||||
|
||||
function prepareSharedRootDirectory(directory: string, uid: number): string | null {
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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": {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@getpaseo/website",
|
||||
"version": "0.16.1",
|
||||
"version": "0.16.2",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@getpaseo/builtin-plugins",
|
||||
"version": "0.16.1",
|
||||
"version": "0.16.2",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
|
||||
@@ -0,0 +1,291 @@
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { existsSync } from "node:fs";
|
||||
import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { dirname, join } from "node:path";
|
||||
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
||||
import { copyWorktreeIncludes } from "./copy.js";
|
||||
|
||||
let root: string;
|
||||
let source: string;
|
||||
let worktree: string;
|
||||
|
||||
async function writeSource(files: Record<string, string>): Promise<void> {
|
||||
for (const [file, contents] of Object.entries(files)) {
|
||||
await mkdir(dirname(join(source, file)), { recursive: true });
|
||||
await writeFile(join(source, file), contents);
|
||||
}
|
||||
}
|
||||
|
||||
// Total directories Git visits while listing files, read from its trace2 events.
|
||||
async function directoriesVisited(run: () => Promise<unknown>): Promise<number> {
|
||||
const trace = join(root, "trace.json");
|
||||
process.env.GIT_TRACE2_EVENT = trace;
|
||||
try {
|
||||
await run();
|
||||
} finally {
|
||||
delete process.env.GIT_TRACE2_EVENT;
|
||||
}
|
||||
return (await readFile(trace, "utf8"))
|
||||
.split("\n")
|
||||
.filter(Boolean)
|
||||
.map((line) => JSON.parse(line) as { event: string; key?: string; value?: string })
|
||||
.filter((event) => event.event === "data" && event.key === "directories-visited")
|
||||
.reduce((total, event) => total + Number(event.value), 0);
|
||||
}
|
||||
|
||||
async function copied(): Promise<string[]> {
|
||||
const result = await copyWorktreeIncludes(worktree, source);
|
||||
if (result.kind !== "copied") throw new Error(`expected a copy, got ${result.kind}`);
|
||||
return [...result.copied].sort();
|
||||
}
|
||||
|
||||
beforeEach(async () => {
|
||||
root = await mkdtemp(join(tmpdir(), "worktree-include-"));
|
||||
source = join(root, "source");
|
||||
worktree = join(root, "worktree");
|
||||
await mkdir(source);
|
||||
await mkdir(worktree);
|
||||
execFileSync("git", ["init", "-q", source]);
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await rm(root, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
describe("copyWorktreeIncludes", () => {
|
||||
it("does not search inside an ignored directory that no pattern names", async () => {
|
||||
await writeSource({
|
||||
".gitignore": "node_modules/\n.env\n",
|
||||
".worktreeinclude": ".env\n",
|
||||
".env": "SECRET=root",
|
||||
"apps/web/.env": "SECRET=web",
|
||||
"node_modules/pkg/.env": "SECRET=package",
|
||||
});
|
||||
|
||||
expect(await copied()).toEqual([".env", "apps/web/.env"]);
|
||||
expect(existsSync(join(worktree, "node_modules"))).toBe(false);
|
||||
});
|
||||
|
||||
it("searches inside ignored directories for a pattern that starts with **/", async () => {
|
||||
await writeSource({
|
||||
".gitignore": "node_modules/\n.env\n",
|
||||
".worktreeinclude": "**/.env\n",
|
||||
".env": "SECRET=root",
|
||||
"node_modules/pkg/.env": "SECRET=package",
|
||||
});
|
||||
|
||||
expect(await copied()).toEqual([".env", "node_modules/pkg/.env"]);
|
||||
});
|
||||
|
||||
it("copies a file in an untracked directory once when a **/ pattern also searches it", async () => {
|
||||
await writeSource({
|
||||
".gitignore": ".env\n",
|
||||
".worktreeinclude": "**/.env\nnew-package/.env\n",
|
||||
"new-package/.env": "SECRET=new",
|
||||
});
|
||||
|
||||
const result = await copyWorktreeIncludes(worktree, source);
|
||||
expect(result).toEqual({
|
||||
kind: "copied",
|
||||
copied: ["new-package/.env"],
|
||||
skipped: [],
|
||||
});
|
||||
});
|
||||
|
||||
it("copies a path a pattern names inside an ignored directory", async () => {
|
||||
await writeSource({
|
||||
".gitignore": "node_modules/\n",
|
||||
".worktreeinclude": "node_modules/pkg/.env\n",
|
||||
"node_modules/pkg/.env": "SECRET=package",
|
||||
"node_modules/other/.env": "SECRET=other",
|
||||
});
|
||||
|
||||
expect(await copied()).toEqual(["node_modules/pkg/.env"]);
|
||||
});
|
||||
|
||||
it("copies an ignored directory that a pattern names", async () => {
|
||||
await writeSource({
|
||||
".gitignore": ".secrets/\nbuild/\n",
|
||||
".worktreeinclude": ".secrets/\n",
|
||||
".secrets/a.key": "a",
|
||||
".secrets/nested/b.key": "b",
|
||||
"build/out.js": "built",
|
||||
});
|
||||
|
||||
expect(await copied()).toEqual([".secrets/a.key", ".secrets/nested/b.key"]);
|
||||
});
|
||||
|
||||
it("searches inside an ignored directory for a path a pattern names", async () => {
|
||||
await writeSource({
|
||||
".gitignore": "config/\n",
|
||||
".worktreeinclude": "config/*.local.json\n!config/production.local.json\n",
|
||||
"config/dev.local.json": "dev",
|
||||
"config/production.local.json": "production",
|
||||
"config/defaults.json": "defaults",
|
||||
});
|
||||
|
||||
expect(await copied()).toEqual(["config/dev.local.json"]);
|
||||
expect(await readFile(join(worktree, "config/dev.local.json"), "utf8")).toBe("dev");
|
||||
});
|
||||
|
||||
it("copies ignored files inside an untracked directory", async () => {
|
||||
await writeSource({
|
||||
".gitignore": ".env\n",
|
||||
".worktreeinclude": ".env\n",
|
||||
"new-package/.env": "SECRET=new",
|
||||
});
|
||||
|
||||
expect(await copied()).toEqual(["new-package/.env"]);
|
||||
});
|
||||
|
||||
it("copies nothing that is tracked or not ignored", async () => {
|
||||
await writeSource({
|
||||
".gitignore": ".env\n",
|
||||
".worktreeinclude": ".env\nnotes.txt\n",
|
||||
"notes.txt": "not ignored",
|
||||
});
|
||||
|
||||
expect(await copied()).toEqual([]);
|
||||
});
|
||||
|
||||
it("searches only the path a glob-free pattern names directly inside an ignored directory", async () => {
|
||||
const packages: Record<string, string> = {};
|
||||
for (let i = 0; i < 20; i++) packages[`node_modules/pkg${i}/lib/index.js`] = "code";
|
||||
await writeSource({
|
||||
".gitignore": "node_modules/\n",
|
||||
".worktreeinclude": "node_modules/.cache\n",
|
||||
"node_modules/.cache/state.json": "cache",
|
||||
...packages,
|
||||
});
|
||||
|
||||
let result: Awaited<ReturnType<typeof copyWorktreeIncludes>> | undefined;
|
||||
const visited = await directoriesVisited(async () => {
|
||||
result = await copyWorktreeIncludes(worktree, source);
|
||||
});
|
||||
|
||||
expect(result).toEqual({
|
||||
kind: "copied",
|
||||
copied: ["node_modules/.cache/state.json"],
|
||||
skipped: [],
|
||||
});
|
||||
expect(visited).toBeLessThan(10);
|
||||
});
|
||||
|
||||
it.skipIf(process.platform === "win32")(
|
||||
"copies includes when an ignored file is named like a Git pathspec",
|
||||
async () => {
|
||||
await writeSource({
|
||||
".gitignore": "*.log\n.env\n",
|
||||
".worktreeinclude": ".env\n",
|
||||
".env": "SECRET=root",
|
||||
":(oops.log": "log",
|
||||
":!c.log": "log",
|
||||
});
|
||||
|
||||
expect(await copied()).toEqual([".env"]);
|
||||
},
|
||||
);
|
||||
|
||||
it("ignores exclude patterns from the user's git template", async () => {
|
||||
const template = join(root, "template");
|
||||
await mkdir(join(template, "info"), { recursive: true });
|
||||
await writeFile(join(template, "info", "exclude"), "*.log\n");
|
||||
await writeSource({
|
||||
".gitignore": "*.log\n.env\n",
|
||||
".worktreeinclude": ".env\n",
|
||||
".env": "SECRET=root",
|
||||
"debug.log": "log",
|
||||
});
|
||||
|
||||
process.env.GIT_TEMPLATE_DIR = template;
|
||||
try {
|
||||
expect(await copied()).toEqual([".env"]);
|
||||
} finally {
|
||||
delete process.env.GIT_TEMPLATE_DIR;
|
||||
}
|
||||
});
|
||||
|
||||
it("does not search an ignored directory deeper than a pattern without ** can reach", async () => {
|
||||
const packages: Record<string, string> = {};
|
||||
for (let i = 0; i < 20; i++) packages[`apps/web/node_modules/pkg${i}/lib/index.js`] = "code";
|
||||
await writeSource({
|
||||
".gitignore": "node_modules/\n.env\n",
|
||||
".worktreeinclude": "apps/*/.env\n",
|
||||
"apps/web/.env": "SECRET=web",
|
||||
...packages,
|
||||
});
|
||||
|
||||
let result: Awaited<ReturnType<typeof copyWorktreeIncludes>> | undefined;
|
||||
const visited = await directoriesVisited(async () => {
|
||||
result = await copyWorktreeIncludes(worktree, source);
|
||||
});
|
||||
|
||||
expect(result).toEqual({ kind: "copied", copied: ["apps/web/.env"], skipped: [] });
|
||||
expect(visited).toBeLessThan(10);
|
||||
});
|
||||
|
||||
it("reads the first pattern after a UTF-8 byte order mark", async () => {
|
||||
await writeSource({
|
||||
".gitignore": "node_modules/\n",
|
||||
".worktreeinclude": "\uFEFFnode_modules/.cache/\n",
|
||||
"node_modules/.cache/state.json": "cache",
|
||||
});
|
||||
|
||||
expect(await copied()).toEqual(["node_modules/.cache/state.json"]);
|
||||
});
|
||||
|
||||
it("matches patterns case-insensitively when the source repo ignores case", async () => {
|
||||
execFileSync("git", ["-C", source, "config", "core.ignoreCase", "true"]);
|
||||
await writeSource({
|
||||
".gitignore": ".env\nconfig/\n",
|
||||
".worktreeinclude": ".ENV\nCONFIG/a.json\n",
|
||||
".env": "SECRET=root",
|
||||
"config/a.json": "a",
|
||||
});
|
||||
|
||||
expect(await copied()).toEqual([".env", "config/a.json"]);
|
||||
});
|
||||
|
||||
it("searches a pattern's path in the case it has on disk when the source repo ignores case", async () => {
|
||||
execFileSync("git", ["-C", source, "config", "core.ignoreCase", "true"]);
|
||||
await writeSource({
|
||||
".gitignore": "Config/\nÉTÉ/\n",
|
||||
".worktreeinclude": "config/a.json\nÉTÉ/sub/.env\n",
|
||||
"Config/a.json": "a",
|
||||
"ÉTÉ/sub/.env": "SECRET=summer",
|
||||
});
|
||||
|
||||
expect(await copied()).toEqual(["Config/a.json", "ÉTÉ/sub/.env"]);
|
||||
});
|
||||
|
||||
// Each searched folder is one argument to Git. Windows caps a command line at 32,767
|
||||
// characters and Linux at 2 MB, so each platform gets enough folders to exceed its own
|
||||
// limit, with names short enough for Windows paths.
|
||||
it("searches more ignored folders than fit on one command line", async () => {
|
||||
const folders = process.platform === "win32" ? 300 : 15_000;
|
||||
const name = (i: number) => `${"x".repeat(150)}${i}`;
|
||||
await writeSource({
|
||||
".gitignore": "x*/\n.env\n",
|
||||
".worktreeinclude": "**/.env\n",
|
||||
[`${name(folders - 1)}/.env`]: "SECRET=last",
|
||||
});
|
||||
for (let i = 0; i < folders - 1; i++) await mkdir(join(source, name(i)));
|
||||
await Promise.all(
|
||||
Array.from({ length: folders - 1 }, (_, i) => writeFile(join(source, name(i), "a"), "")),
|
||||
);
|
||||
|
||||
expect(await copied()).toEqual([`${name(folders - 1)}/.env`]);
|
||||
}, 60_000);
|
||||
|
||||
it("copies ignored files inside an untracked directory a pattern names", async () => {
|
||||
await writeSource({
|
||||
".gitignore": ".env\n",
|
||||
".worktreeinclude": "newdir/\n",
|
||||
"newdir/.env": "SECRET=new",
|
||||
"newdir/notes.txt": "untracked",
|
||||
});
|
||||
|
||||
expect(await copied()).toEqual(["newdir/.env"]);
|
||||
});
|
||||
});
|
||||
@@ -2,7 +2,8 @@
|
||||
// Copyright (c) 2026 Carlos Precioso.
|
||||
import { execFile } from "node:child_process";
|
||||
import { constants, existsSync } from "node:fs";
|
||||
import { copyFile, mkdir } from "node:fs/promises";
|
||||
import { copyFile, mkdir, mkdtemp, readFile, rm } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { dirname, join } from "node:path";
|
||||
import { promisify } from "node:util";
|
||||
|
||||
@@ -22,37 +23,33 @@ async function git(cwd: string, args: string[], input?: string): Promise<string>
|
||||
return stdout;
|
||||
}
|
||||
|
||||
async function gitAllowExit1(cwd: string, args: string[], input: string): Promise<string> {
|
||||
// `git check-ignore --stdin` reads each path as a pathspec, so a name such as `:(x`
|
||||
// would be parsed as pathspec magic. A `./` prefix keeps every path literal.
|
||||
async function checkIgnore(cwd: string, args: string[], paths: string[]): Promise<string[]> {
|
||||
const input = paths.map((path) => `./${path}\0`).join("");
|
||||
let output: string;
|
||||
try {
|
||||
return await git(cwd, args, input);
|
||||
output = await git(cwd, [...args, "check-ignore", "--stdin", "-z"], input);
|
||||
} catch (error) {
|
||||
// `git check-ignore` exits 1 when nothing matched.
|
||||
if ((error as { code?: number }).code === 1) return "";
|
||||
if ((error as { code?: number }).code === 1) return [];
|
||||
throw error;
|
||||
}
|
||||
return splitNul(output).map((path) => path.replace(/^\.\//, ""));
|
||||
}
|
||||
|
||||
const splitNul = (s: string) => s.split("\0").filter(Boolean);
|
||||
const isDirectory = (entry: string) => entry.endsWith("/");
|
||||
|
||||
// Copy files that match .worktreeinclude (gitignore syntax)
|
||||
// AND are gitignored, so tracked files are never touched.
|
||||
export async function copyWorktreeIncludes(worktree: string, source: string): Promise<CopyResult> {
|
||||
if (!existsSync(join(source, INCLUDE_FILE))) return { kind: "no-include-file" };
|
||||
|
||||
const matches = splitNul(
|
||||
await git(source, [
|
||||
"ls-files",
|
||||
"--others",
|
||||
"--ignored",
|
||||
`--exclude-from=${INCLUDE_FILE}`,
|
||||
"-z",
|
||||
]),
|
||||
);
|
||||
const matches = await findIncludedFiles(source);
|
||||
if (matches.length === 0) return { kind: "copied", copied: [], skipped: [] };
|
||||
|
||||
const ignored = splitNul(
|
||||
await gitAllowExit1(source, ["check-ignore", "--stdin", "-z"], matches.join("\0") + "\0"),
|
||||
);
|
||||
const ignored = await checkIgnore(source, [], matches);
|
||||
|
||||
const copied: string[] = [];
|
||||
const skipped: string[] = [];
|
||||
@@ -69,3 +66,152 @@ export async function copyWorktreeIncludes(worktree: string, source: string): Pr
|
||||
}
|
||||
return { kind: "copied", copied, skipped };
|
||||
}
|
||||
|
||||
// Git lists a directory it ignores as a whole, such as node_modules/, as one entry.
|
||||
// Only directories that a pattern matches or names a path inside are searched, and
|
||||
// only as deep as the pattern names, so creating a worktree does not walk every file
|
||||
// in large ignored trees.
|
||||
async function findIncludedFiles(source: string): Promise<string[]> {
|
||||
const ignored = splitNul(
|
||||
await git(source, [
|
||||
"ls-files",
|
||||
"--others",
|
||||
"--ignored",
|
||||
"--exclude-standard",
|
||||
"--directory",
|
||||
"-z",
|
||||
]),
|
||||
);
|
||||
if (ignored.length === 0) return [];
|
||||
|
||||
const ignoreCase = await sourceIgnoresCase(source);
|
||||
const patterns = parsePatterns(await readFile(join(source, INCLUDE_FILE), "utf8"));
|
||||
const matched = new Set(await matchIncludePatterns(source, ignored, ignoreCase));
|
||||
const files = ignored.filter((entry) => !isDirectory(entry) && matched.has(entry));
|
||||
const searched = new Set<string>();
|
||||
// Git also lists an untracked folder that holds ignored entries, which are listed on
|
||||
// their own, so only folders Git ignores as a whole are searched.
|
||||
const directories = await checkIgnore(source, [], ignored.filter(isDirectory));
|
||||
for (const directory of directories) {
|
||||
if (matched.has(directory)) {
|
||||
searched.add(directory);
|
||||
continue;
|
||||
}
|
||||
for (const pattern of patterns) {
|
||||
const inside = searchedPathInside(pattern, directory, ignoreCase);
|
||||
if (inside !== null) searched.add(inside);
|
||||
}
|
||||
}
|
||||
if (searched.size === 0) return files;
|
||||
|
||||
const pathspecs = [...searched].map(
|
||||
(path) => `:(${ignoreCase ? "literal,icase" : "literal"})${path}`,
|
||||
);
|
||||
const inside: string[] = [];
|
||||
for (const batch of commandLineBatches(pathspecs)) {
|
||||
const listed = await git(source, [
|
||||
"ls-files",
|
||||
"--others",
|
||||
"--ignored",
|
||||
`--exclude-from=${INCLUDE_FILE}`,
|
||||
"-z",
|
||||
"--",
|
||||
...batch,
|
||||
]);
|
||||
inside.push(...splitNul(listed));
|
||||
}
|
||||
return [...new Set([...files, ...inside])];
|
||||
}
|
||||
|
||||
// Windows caps a command line at 32,767 characters, so a pattern such as `**/.env` in a
|
||||
// repo with many ignored folders searches them over several Git calls.
|
||||
const COMMAND_LINE_BATCH_CHARS = 16_000;
|
||||
|
||||
function commandLineBatches(args: string[]): string[][] {
|
||||
const batches: string[][] = [];
|
||||
let batch: string[] = [];
|
||||
let length = 0;
|
||||
for (const arg of args) {
|
||||
if (batch.length > 0 && length + arg.length + 1 > COMMAND_LINE_BATCH_CHARS) {
|
||||
batches.push(batch);
|
||||
batch = [];
|
||||
length = 0;
|
||||
}
|
||||
batch.push(arg);
|
||||
length += arg.length + 1;
|
||||
}
|
||||
if (batch.length > 0) batches.push(batch);
|
||||
return batches;
|
||||
}
|
||||
|
||||
// Match entries against .worktreeinclude alone, in a scratch repository where no other
|
||||
// ignore rules apply. Directory entries keep their trailing slash, so directory
|
||||
// patterns match them without anything on disk.
|
||||
async function matchIncludePatterns(
|
||||
source: string,
|
||||
entries: string[],
|
||||
ignoreCase: boolean,
|
||||
): Promise<string[]> {
|
||||
const scratch = await mkdtemp(join(tmpdir(), "paseo-worktree-include-"));
|
||||
try {
|
||||
// An empty template keeps the user's template `info/exclude` out of the matching.
|
||||
await git(scratch, ["init", "-q", "--template="]);
|
||||
return await checkIgnore(
|
||||
scratch,
|
||||
[
|
||||
"-c",
|
||||
`core.excludesFile=${join(source, INCLUDE_FILE)}`,
|
||||
"-c",
|
||||
`core.ignoreCase=${ignoreCase}`,
|
||||
],
|
||||
entries,
|
||||
);
|
||||
} finally {
|
||||
await rm(scratch, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
// The scratch repository would otherwise take core.ignoreCase from the temp folder.
|
||||
async function sourceIgnoresCase(source: string): Promise<boolean> {
|
||||
try {
|
||||
return (await git(source, ["config", "--type=bool", "core.ignoreCase"])).trim() === "true";
|
||||
} catch {
|
||||
// `git config` exits 1 when the key is unset.
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function parsePatterns(contents: string): string[] {
|
||||
// Git skips a leading UTF-8 byte order mark in exclude files.
|
||||
return contents
|
||||
.replace(/^\uFEFF/, "")
|
||||
.split(/\r?\n/)
|
||||
.map((line) => line.trimEnd())
|
||||
.filter((line) => line !== "" && !line.startsWith("#") && !line.startsWith("!"));
|
||||
}
|
||||
|
||||
// A pattern with a slash before its end is anchored to the checkout root, so it can
|
||||
// name a path inside `directory` when its literal start and the directory overlap.
|
||||
// Without `**`, a pattern matches paths of exactly its own depth, so a directory that
|
||||
// deep or deeper can hold no match below it. Returns the narrowest path to search: the
|
||||
// whole path when the pattern has no glob, else the folder before its first glob, or
|
||||
// `directory` itself when the path ends above it.
|
||||
function searchedPathInside(
|
||||
pattern: string,
|
||||
rawDirectory: string,
|
||||
ignoreCase: boolean,
|
||||
): string | null {
|
||||
// Git folds only ASCII letters when it ignores case.
|
||||
const fold = (text: string) =>
|
||||
ignoreCase ? text.replace(/[A-Z]+/g, (letters) => letters.toLowerCase()) : text;
|
||||
const path = fold(pattern.replace(/^\//, ""));
|
||||
const directory = fold(rawDirectory);
|
||||
const depth = (text: string) => text.replace(/\/$/, "").split("/").length;
|
||||
if (depth(path) < 2) return null;
|
||||
if (!path.includes("**") && depth(directory) >= depth(path)) return null;
|
||||
const globAt = path.search(/[*?[\\]/);
|
||||
const literal = globAt === -1 ? path : path.slice(0, globAt);
|
||||
if (!literal.startsWith(directory) && !directory.startsWith(literal)) return null;
|
||||
const searched = globAt === -1 ? literal : literal.slice(0, literal.lastIndexOf("/") + 1);
|
||||
return searched.length > directory.length ? searched : directory;
|
||||
}
|
||||
|
||||
@@ -36,6 +36,8 @@ config/*.local.json
|
||||
|
||||
A pattern only selects files that Git already ignores. Adding a path here does not ignore it, so also configure `.gitignore` when needed. Tracked files and untracked files that Git does not ignore are excluded.
|
||||
|
||||
Paseo does not search inside a directory that Git ignores as a whole, such as `node_modules/`, unless a pattern names that directory or a path inside it. A bare name like `.env` matches `.env` and `apps/web/.env`, but not `node_modules/pkg/.env`. To copy from inside an ignored directory, name it in the pattern, as in `node_modules/pkg/.env` or `.secrets/`. A pattern with a glob in its first directory name, such as `**/.env` or `*/.env`, searches every ignored directory, including `node_modules/`, so name the directory instead when it is large.
|
||||
|
||||
## When files are copied
|
||||
|
||||
The built-in `worktree-include` plugin reads the file from the checkout you create the worktree from. That source can itself be another worktree. Keep the plugin enabled for copying to run.
|
||||
|
||||
@@ -36,6 +36,8 @@ config/*.local.json
|
||||
|
||||
模式只会选择 Git 已忽略的文件。在此添加路径不会使 Git 忽略该文件,需要时还应配置 `.gitignore`。已跟踪的文件和未被 Git 忽略的未跟踪文件都不会被复制。
|
||||
|
||||
对于被 Git 整体忽略的目录(例如 `node_modules/`),除非某个模式指明了该目录或其中的路径,否则 Paseo 不会在其中查找。像 `.env` 这样的纯文件名会匹配 `.env` 和 `apps/web/.env`,但不会匹配 `node_modules/pkg/.env`。要从被忽略的目录中复制文件,请在模式中写出该目录,例如 `node_modules/pkg/.env` 或 `.secrets/`。第一级目录名中带有通配符的模式(例如 `**/.env` 或 `*/.env`)会在所有被忽略的目录中查找,包括 `node_modules/`,因此目录较大时请直接写出目录。
|
||||
|
||||
## 文件复制时机 {#when-files-are-copied}
|
||||
|
||||
内置的 `worktree-include` 插件从用于创建 worktree 的检出读取该文件。源检出也可以是另一个 worktree。保持该插件启用才能执行复制。
|
||||
|
||||
Reference in New Issue
Block a user