Compare commits

..
Author SHA1 Message Date
paseo-bot[bot]andClaude Opus 5.5 6c94ab046f refactor(app): give the sidebar row "actions always visible" rule one home
The rule was written out in the workspace, status and project rows and
passed to resolveTrailingActionVisibility as isTouchPlatform, which no
longer meant a touch platform. useRowActionsAlwaysVisible() now owns it
(compact layout or no fine pointer; the native pointer source already
reports no fine pointer), and the parameter is named for what it means.
Behaviour is unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 00:15:48 +00:00
aa1e4c8ad6 fix(app): keep hover-revealed row menus for mouse-driven touch-screen laptops
Show the always-visible row menu only when the primary pointer cannot
hover, the same check the sidebar resize grip uses. A touch-screen laptop
driven by a mouse keeps its row stats, hover archive button, and
hover-revealed menu.

Co-authored-by: Matt Abar <mattaabar@gmail.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 23:03:02 +00:00
Matt AbarandClaude Opus 5.5 9fe97efb34 test(app): pin the web touch grip offset in the layout test
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 15:09:56 -07:00
Matt AbarandClaude Opus 5.5 cfd32891f5 fix(app): make the web touch resize grip easy to see
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 15:08:30 -07:00
Matt AbarandClaude Opus 5.5 7792a1d697 fix(app): keep the web touch grip inside the sidebar, level with the top rows
The previous commit moved the web touch grip just outside the sidebar so it
would not cover a row's menu button. But the sidebar clips its overflow, and
in a browser that clips hit-testing too, so a finger could no longer reach the
grip and the sidebar could not be resized by touch.

On the web the touch grip now stays inside the sidebar and sits level with the
top navigation rows (New workspace, History, Search), which have nothing at
their right edge, and it shows faintly at rest so it can be found. Native
keeps the centred grip, and the explorer sidebar is unchanged.

A browser test drags the grip with a finger and checks that nothing covers it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 14:53:53 -07:00
Matt AbarandClaude Opus 5.5 eacbbfca80 fix(app): keep the web touch resize grip off the sidebar row menus
The touch resize grip sits inside the sidebar because native hit-testing
clips to the sidebar. On a touch screen in the browser it then covered the
right edge of the rows, where the row menu button now always shows, so a
tap on the menu started a resize instead. Browsers do not clip hit-testing,
so on the web the touch grip sits just outside the sidebar.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 12:37:45 -07:00
Matt AbarandClaude Opus 5.5 976e47ae3f fix(app): show sidebar row menus on touch screens
An iPad in the browser runs the desktop layout with the sidebar pinned.
Its workspace and project rows showed their kebab only on hover, which a
touch screen can't do, and iOS Safari fires no contextmenu for a long
press, so the row menu (rename, pin, archive, copy path) was unreachable.

Rows now treat any touch screen (any-pointer: coarse, from the existing
pointer-capabilities hook) like the native and compact layouts for the
kebab, so it stays visible and opens with a tap.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 12:37:45 -07:00
83 changed files with 544 additions and 1772 deletions
-15
View File
@@ -1,20 +1,5 @@
# Changelog
## 0.16.1 - 2026-11-17
### Fixed
- Fixed Claude Bypass approving actions without a permission card when a `permissions.ask` rule or a hook that returns `ask` required one ([#9927](https://github.com/getpaseo/paseo/pull/9927))
- Fixed controls being touch-sized on a touch-screen laptop when a trackpad or mouse is its primary input ([#9909](https://github.com/getpaseo/paseo/pull/9909) by [@michaelhthomas](https://github.com/michaelhthomas))
- Fixed Claude sessions failing until `/login` when Paseo refreshed the Claude model list while Claude Code was renewing an expired access token ([#9855](https://github.com/getpaseo/paseo/pull/9855) by [@daysun-k](https://github.com/daysun-k))
- Fixed Add host text fields on web drawing without a box, which left the host password field invisible ([#9865](https://github.com/getpaseo/paseo/pull/9865) by [@angusb93](https://github.com/angusb93))
- Fixed an OpenCode question that could not be answered or dismissed after a new message steered the turn ([#9891](https://github.com/getpaseo/paseo/pull/9891))
- Fixed Pi and OMP model names that contain `/` being cut to the text after the last slash ([#9823](https://github.com/getpaseo/paseo/pull/9823), [#9836](https://github.com/getpaseo/paseo/pull/9836) by [@rms523](https://github.com/rms523))
- Fixed Changes leaving out an edit when the file was saved with the same size in the same second it was staged ([#9854](https://github.com/getpaseo/paseo/pull/9854))
- Fixed an error toast that never closed when marking a chat as read failed ([#9837](https://github.com/getpaseo/paseo/pull/9837))
- Fixed wait results and finish notifications after a daemon restart joining an agent's self-started reply to the reply before it ([#9846](https://github.com/getpaseo/paseo/pull/9846))
- Fixed Codex chats staying loaded in the daemon until restart when a client opened them only to read their history ([#9859](https://github.com/getpaseo/paseo/pull/9859) by [@Spshulem](https://github.com/Spshulem))
## 0.16.0 - 2026-11-16
- **Background tasks:** See and stop background tasks above the composer for Claude Code, Codex and OpenCode v2. ([#6220](https://github.com/getpaseo/paseo/pull/6220), [#9162](https://github.com/getpaseo/paseo/pull/9162), [#9635](https://github.com/getpaseo/paseo/pull/9635) by [@fxlelouarn](https://github.com/fxlelouarn))
-15
View File
@@ -1,20 +1,5 @@
# Changelog
## 0.16.1 - 2026-11-17
### 修复
- 修复 `permissions.ask` 规则或返回 `ask` 的钩子要求确认时,Claude Bypass 不显示权限卡片就批准操作的问题 ([#9927](https://github.com/getpaseo/paseo/pull/9927))
- 修复触屏笔记本以触控板或鼠标为主要输入时,控件仍使用触控尺寸的问题 ([#9909](https://github.com/getpaseo/paseo/pull/9909),贡献者:[@michaelhthomas](https://github.com/michaelhthomas))
- 修复 Claude Code 正在续期已过期的访问令牌时,Paseo 刷新 Claude 模型列表导致 Claude 会话在执行 `/login` 前一直失败的问题 ([#9855](https://github.com/getpaseo/paseo/pull/9855),贡献者:[@daysun-k](https://github.com/daysun-k))
- 修复 Web 端“添加主机”的文本字段没有输入框,导致主机密码字段不可见的问题 ([#9865](https://github.com/getpaseo/paseo/pull/9865),贡献者:[@angusb93](https://github.com/angusb93))
- 修复新消息引导当前回合后,OpenCode 提问既无法回答也无法关闭的问题 ([#9891](https://github.com/getpaseo/paseo/pull/9891))
- 修复名称包含 `/` 的 Pi 和 OMP 模型被截成最后一个斜杠之后文本的问题 ([#9823](https://github.com/getpaseo/paseo/pull/9823), [#9836](https://github.com/getpaseo/paseo/pull/9836),贡献者:[@rms523](https://github.com/rms523))
- 修复文件暂存后在同一秒内以相同大小保存时,“更改”遗漏该修改的问题 ([#9854](https://github.com/getpaseo/paseo/pull/9854))
- 修复将对话标记为已读失败后,错误提示一直不关闭的问题 ([#9837](https://github.com/getpaseo/paseo/pull/9837))
- 修复 daemon 重启后,等待结果和完成通知把 Agent 自行开始的回复与上一条回复拼接在一起的问题 ([#9846](https://github.com/getpaseo/paseo/pull/9846))
- 修复客户端仅为读取历史而打开的 Codex 对话一直加载在 daemon 中直到重启的问题 ([#9859](https://github.com/getpaseo/paseo/pull/9859),贡献者:[@Spshulem](https://github.com/Spshulem))
## 0.16.0 - 2026-11-16
- **后台任务**:在 Composer 上方查看并停止 Claude Code、Codex 和 OpenCode v2 的后台任务。 ([#6220](https://github.com/getpaseo/paseo/pull/6220), [#9162](https://github.com/getpaseo/paseo/pull/9162), [#9635](https://github.com/getpaseo/paseo/pull/9635),贡献者:[@fxlelouarn](https://github.com/fxlelouarn))
+1 -1
View File
@@ -76,7 +76,7 @@ Dense toolbar rows, such as the composer's, are the exception to the 44pt contro
In the composer, the first glyph's ink starts on the text column's edge, and the trailing control is always a disc, so the row does not shift as it changes between voice mode, send and stop. The disc nests into the corner, as far from the right edge as from the bottom, and touch-sized the composer's corner radius is concentric with it (`packages/app/src/composer/input/toolbar-rails.ts`). Touch-sized the disc keeps a 6pt clearance from its neighbour, because it is always painted and a pressed neighbour would merge with it. The attach button sits 2pt closer to the picker than its highlight would put it: the plus is all thin arms, so the full gap reads wide. That offset is set by eye.
One gate, `resolveControlSizing`, picks touch or pointer sizing: touch when the layout is compact or touch is the primary input. An iPad with the sidebar docked is wide and touch-sized; a desktop is pointer-sized; a phone is both compact and touch. The primary input comes from `(pointer: coarse)` (`hasTouchPrimaryPointer` in `hooks/pointer-capabilities.ts`), not from whether a touch screen exists: WebKit keeps touch primary on an iPad with a trackpad attached, and Chromium reports a fine primary pointer for a laptop with a touch screen that its trackpad drives. The fact is read once at startup: attaching a pointer to a tablet does not shrink its controls, and a 2-in-1 launched with a pointer keeps pointer sizes after it switches to tablet mode until the app reloads. Stylesheets take sizes from `bySizing({ touch, pointer })`, which resolves to a breakpoint value, so a caller never sees which sizing it got. Rows, icon buttons and icon slots take theirs from `styles/density.ts`, which uses the same gate. An `{ xs, md }` literal for a hit target or glyph is wrong: on an iPad it yields the pointer size.
One gate, `resolveControlSizing`, picks touch or pointer sizing: touch when the layout is compact or the device has a touch screen. An iPad with the sidebar docked is wide and touch-sized; a desktop is pointer-sized; a phone is both compact and touch. The touch-screen fact is read once at startup (`hasTouchScreen` in `hooks/use-fine-pointer.ts`), so attaching a mouse or keyboard to a tablet never shrinks its controls. Stylesheets take sizes from `bySizing({ touch, pointer })`, which resolves to a breakpoint value, so a caller never sees which sizing it got. Rows, icon buttons and icon slots take theirs from `styles/density.ts`, which uses the same gate. An `{ xs, md }` literal for a hit target or glyph is wrong: on an iPad it yields the pointer size.
Buttons are pills (`borderRadius.full`) with medium-weight labels; an icon-only button is a circle. `<Switch>` follows the same two sizes: a 34×20 track by default and in `sm`, 44×26 where controls are touch-sized, and it reserves its size's control height so a row holding one lines up with a row holding a button. Buttons, text fields, dropdown triggers, and `<SegmentedControl>` (`packages/app/src/components/ui/segmented-control.tsx`) share the size contract — the same size name means the same height and label size on every control kind, so controls in one row line up. Segments run tighter than a button, because the gap between segments already reads as padding. The selected segment is a `surface3` fill with `foreground` text, not an inverted one — inverting it inside thin chrome puts a white slab in the toolbar. A settings row sizes the controls in its trailing slot itself, default in a card and `sm` when nested (`packages/app/src/components/ui/control-size.tsx`), so don't pass a size to a button, dropdown or field placed in a row. Code that computes with a control's height outside a stylesheet uses `controlHeightForLayout`. Never shrink a control's font or padding locally to fit a context — if the context needs a smaller control, the size tier is missing or the wrong one is in use.
@@ -1,6 +0,0 @@
Fixed
- Fixed Claude Bypass approving actions without a permission card when a permissions.ask rule or a hook that returns ask required one
- Fixed controls being touch-sized on a touch-screen laptop when a trackpad or mouse is its primary input
- Fixed Claude sessions failing until /login when Paseo refreshed the Claude model list while Claude Code was renewing an expired access token
Full notes: https://paseo.sh/changelog
@@ -1,6 +0,0 @@
Fixed
- Fixed Claude Bypass approving actions without a permission card when a permissions.ask rule or a hook that returns ask required one
- Fixed controls being touch-sized on a touch-screen laptop when a trackpad or mouse is its primary input
- Fixed Claude sessions failing until /login when Paseo refreshed the Claude model list while Claude Code was renewing an expired access token
Full notes: https://paseo.sh/changelog
@@ -1,6 +0,0 @@
Fixed
- Fixed Claude Bypass approving actions without a permission card when a permissions.ask rule or a hook that returns ask required one
- Fixed controls being touch-sized on a touch-screen laptop when a trackpad or mouse is its primary input
- Fixed Claude sessions failing until /login when Paseo refreshed the Claude model list while Claude Code was renewing an expired access token
Full notes: https://paseo.sh/changelog
@@ -1,6 +0,0 @@
Fixed
- Fixed Claude Bypass approving actions without a permission card when a permissions.ask rule or a hook that returns ask required one
- Fixed controls being touch-sized on a touch-screen laptop when a trackpad or mouse is its primary input
- Fixed Claude sessions failing until /login when Paseo refreshed the Claude model list while Claude Code was renewing an expired access token
Full notes: https://paseo.sh/changelog
+1 -1
View File
@@ -1 +1 @@
sha256-k7+5S/4tyAmHdZmUdhpuZ7GOc7hp9cG8wUBFdJI32ng=
sha256-alhf4ULeJ7n8sfgnxsX8Ugw40GB7jz0u9R/3/MOveIw=
+65 -65
View File
@@ -1,12 +1,12 @@
{
"name": "paseo",
"version": "0.16.1",
"version": "0.16.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "paseo",
"version": "0.16.1",
"version": "0.16.0",
"hasInstallScript": true,
"license": "Apache-2.0",
"workspaces": [
@@ -130,22 +130,22 @@
}
},
"node_modules/@anthropic-ai/claude-agent-sdk": {
"version": "0.3.326",
"resolved": "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk/-/claude-agent-sdk-0.3.326.tgz",
"integrity": "sha512-BUTSky/4YWfL/MxC+4kV0NDbJFjbJPoQMFEk/s9G6hV9LUfYPMbsWz94bFQ7ZIo2ubj2xwJ2c2NVxkNlQhVw+Q==",
"version": "0.3.246",
"resolved": "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk/-/claude-agent-sdk-0.3.246.tgz",
"integrity": "sha512-FtR0HoHHNqeqJWjZN8qLUAzZVFUI9ztXYNPPwv98Ecmv9qq2QTauI8IzkY26CC0mleWAqb9RQEW2C0OtiUliug==",
"license": "SEE LICENSE IN README.md",
"engines": {
"node": ">=18.14.0"
"node": ">=18.0.0"
},
"optionalDependencies": {
"@anthropic-ai/claude-agent-sdk-darwin-arm64": "0.3.326",
"@anthropic-ai/claude-agent-sdk-darwin-x64": "0.3.326",
"@anthropic-ai/claude-agent-sdk-linux-arm64": "0.3.326",
"@anthropic-ai/claude-agent-sdk-linux-arm64-musl": "0.3.326",
"@anthropic-ai/claude-agent-sdk-linux-x64": "0.3.326",
"@anthropic-ai/claude-agent-sdk-linux-x64-musl": "0.3.326",
"@anthropic-ai/claude-agent-sdk-win32-arm64": "0.3.326",
"@anthropic-ai/claude-agent-sdk-win32-x64": "0.3.326"
"@anthropic-ai/claude-agent-sdk-darwin-arm64": "0.3.246",
"@anthropic-ai/claude-agent-sdk-darwin-x64": "0.3.246",
"@anthropic-ai/claude-agent-sdk-linux-arm64": "0.3.246",
"@anthropic-ai/claude-agent-sdk-linux-arm64-musl": "0.3.246",
"@anthropic-ai/claude-agent-sdk-linux-x64": "0.3.246",
"@anthropic-ai/claude-agent-sdk-linux-x64-musl": "0.3.246",
"@anthropic-ai/claude-agent-sdk-win32-arm64": "0.3.246",
"@anthropic-ai/claude-agent-sdk-win32-x64": "0.3.246"
},
"peerDependencies": {
"@anthropic-ai/sdk": ">=0.93.0",
@@ -154,9 +154,9 @@
}
},
"node_modules/@anthropic-ai/claude-agent-sdk-darwin-arm64": {
"version": "0.3.326",
"resolved": "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk-darwin-arm64/-/claude-agent-sdk-darwin-arm64-0.3.326.tgz",
"integrity": "sha512-D3ZbowCMdKNet0YPZlsJxdJUW1t1Q8KLy1BwNd+5eilf18TlCRtWZlm8DrewFLmu/gxBK7gcsq6uysrIVbPyQg==",
"version": "0.3.246",
"resolved": "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk-darwin-arm64/-/claude-agent-sdk-darwin-arm64-0.3.246.tgz",
"integrity": "sha512-pYDv2RT+UVOvEapMEWKf7Gm5a87Si1Zf+XR23IMGYbG5mESatNJ8Gz2PmkrwfTezZknb0ljWZe8zgcTFITM3dA==",
"cpu": [
"arm64"
],
@@ -167,9 +167,9 @@
]
},
"node_modules/@anthropic-ai/claude-agent-sdk-darwin-x64": {
"version": "0.3.326",
"resolved": "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk-darwin-x64/-/claude-agent-sdk-darwin-x64-0.3.326.tgz",
"integrity": "sha512-m8K3Im2S8STdAVBrriuDZyJcnjsu/Vc3476wIOqTAefnCCdtdZ4AHcOcWxt+4KIHE5Vx1qT2qacTRrQBaVVweA==",
"version": "0.3.246",
"resolved": "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk-darwin-x64/-/claude-agent-sdk-darwin-x64-0.3.246.tgz",
"integrity": "sha512-yl+gMMFUQ8++SBaxUe2JxBqU0LOJO4HZTsWWTOrH5kRlTRhdQDF/lESsoNXCHgfF/+77YNKgef0h+rl/D12Jfg==",
"cpu": [
"x64"
],
@@ -180,9 +180,9 @@
]
},
"node_modules/@anthropic-ai/claude-agent-sdk-linux-arm64": {
"version": "0.3.326",
"resolved": "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk-linux-arm64/-/claude-agent-sdk-linux-arm64-0.3.326.tgz",
"integrity": "sha512-nYVN8jCcH490DCXIvby7rllzQFxLzKeKClfo2u/yv7mx3ipZQv344caULL/amwZ8w8GUzYyZ8hnS6pI9goSq+A==",
"version": "0.3.246",
"resolved": "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk-linux-arm64/-/claude-agent-sdk-linux-arm64-0.3.246.tgz",
"integrity": "sha512-t7AEewD7bcjZYMmrfFLjsUSxPo4z+5J5O5cC9V2zOvAhNkefdMeGWI2/1cdqZxuaOiFVt46byjlZuiNNunF+bQ==",
"cpu": [
"arm64"
],
@@ -193,9 +193,9 @@
]
},
"node_modules/@anthropic-ai/claude-agent-sdk-linux-arm64-musl": {
"version": "0.3.326",
"resolved": "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk-linux-arm64-musl/-/claude-agent-sdk-linux-arm64-musl-0.3.326.tgz",
"integrity": "sha512-baSsuP2/wuWujRpHjKT4WkJB5lhttqKq9jcTfY2KRtQpylbk8E5PWcct/pmwJfNCKIUoE8CD+JpmoWzsdd5Ajw==",
"version": "0.3.246",
"resolved": "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk-linux-arm64-musl/-/claude-agent-sdk-linux-arm64-musl-0.3.246.tgz",
"integrity": "sha512-AeiDXveuA9dVRDouSRiQzL40P3dOuJPfZOlwwsFNbVUN0D+06WtwgmeWYnyRG4dxsM67Pf4lYcRZ0x9pfEZUwQ==",
"cpu": [
"arm64"
],
@@ -206,9 +206,9 @@
]
},
"node_modules/@anthropic-ai/claude-agent-sdk-linux-x64": {
"version": "0.3.326",
"resolved": "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk-linux-x64/-/claude-agent-sdk-linux-x64-0.3.326.tgz",
"integrity": "sha512-WMhDY07gk2O0E8FXTbrVYmPjSLFaYPDCPwsNueVxm6vZ7ek+lPaKuOMAxTb1K07TzSmTOexoWeX2Y9VrbVDMpw==",
"version": "0.3.246",
"resolved": "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk-linux-x64/-/claude-agent-sdk-linux-x64-0.3.246.tgz",
"integrity": "sha512-BIbBlJ6x7Cys6UFvahUfce26H+U+Q4tLWjKRD39AaV7JvRav8/vfdFytzWq6E+h9hT1OOWYuPYx2gMn5vDhZhQ==",
"cpu": [
"x64"
],
@@ -219,9 +219,9 @@
]
},
"node_modules/@anthropic-ai/claude-agent-sdk-linux-x64-musl": {
"version": "0.3.326",
"resolved": "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk-linux-x64-musl/-/claude-agent-sdk-linux-x64-musl-0.3.326.tgz",
"integrity": "sha512-kK9VO3uFqNd4wgeU0Cefluam5AdPu6mvF1nn6aboGy8TA5NoxlWTmA4/AwMhK39zK1S9Q2OjeX0JtAahYlIchw==",
"version": "0.3.246",
"resolved": "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk-linux-x64-musl/-/claude-agent-sdk-linux-x64-musl-0.3.246.tgz",
"integrity": "sha512-+3PrWX3qXgakO3tZImr7keKFry5XIkbHBEaUxgi3/RtPmxGwS+JdVAr0xxzOoC2F6Y66Kn0lUnztRnZHORBc+Q==",
"cpu": [
"x64"
],
@@ -232,9 +232,9 @@
]
},
"node_modules/@anthropic-ai/claude-agent-sdk-win32-arm64": {
"version": "0.3.326",
"resolved": "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk-win32-arm64/-/claude-agent-sdk-win32-arm64-0.3.326.tgz",
"integrity": "sha512-S+Ai+HhGRVFfTDmYWRfTrdWF3b4KMsfLSThZCqRJ0WCOKOXrRShMKV1hqqHBljx/wkMDPCpY0V/9S/e6w57eGQ==",
"version": "0.3.246",
"resolved": "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk-win32-arm64/-/claude-agent-sdk-win32-arm64-0.3.246.tgz",
"integrity": "sha512-JV8b28OJ8d+EMVEVIWlN3aEkT8uSehO3ZN/PJzXFG7Jgn56oVYUew4aY9vK4jao/4E4mdfzvs358w4HcTBUzVw==",
"cpu": [
"arm64"
],
@@ -245,9 +245,9 @@
]
},
"node_modules/@anthropic-ai/claude-agent-sdk-win32-x64": {
"version": "0.3.326",
"resolved": "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk-win32-x64/-/claude-agent-sdk-win32-x64-0.3.326.tgz",
"integrity": "sha512-Yn1gZXYFuHmjHz7SpHx4TqDcRDsC8TfwWcntJdYjFzMWm+caPAp6QRqr/aTvirjqVA1D+D8Rd29xhuytpE3xTQ==",
"version": "0.3.246",
"resolved": "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk-win32-x64/-/claude-agent-sdk-win32-x64-0.3.246.tgz",
"integrity": "sha512-omI65bYGynLpE1Ybijk56K1wBnt0H6WujNwlg1LzIdeHrYmpUxoqncK92xKH5kb9XWUz3byHqArbv7wsT+M/2A==",
"cpu": [
"x64"
],
@@ -37468,7 +37468,7 @@
},
"packages/app": {
"name": "@getpaseo/app",
"version": "0.16.1",
"version": "0.16.0",
"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.0",
"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.0",
"@getpaseo/protocol": "0.16.0",
"@getpaseo/server": "0.16.0",
"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.0",
"license": "Apache-2.0",
"dependencies": {
"@getpaseo/protocol": "0.16.1",
"@getpaseo/relay": "0.16.1",
"@getpaseo/protocol": "0.16.0",
"@getpaseo/relay": "0.16.0",
"ws": "^8.20.0",
"zod": "^4.4.3"
},
@@ -39906,7 +39906,7 @@
},
"packages/desktop": {
"name": "@getpaseo/desktop",
"version": "0.16.1",
"version": "0.16.0",
"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.0",
"license": "MIT",
"devDependencies": {
"@types/jest": "^29.5.14",
@@ -40195,7 +40195,7 @@
},
"packages/highlight": {
"name": "@getpaseo/highlight",
"version": "0.16.1",
"version": "0.16.0",
"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.0",
"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.0",
"@getpaseo/protocol": "0.16.0",
"@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.0",
"@getpaseo/protocol": "0.16.0",
"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.0",
"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.0",
"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.0",
"license": "Apache-2.0",
"dependencies": {
"@agentclientprotocol/sdk": "^0.17.1",
"@anthropic-ai/claude-agent-sdk": "0.3.326",
"@anthropic-ai/claude-agent-sdk": "0.3.246",
"@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.0",
"@getpaseo/highlight": "0.16.0",
"@getpaseo/plugin": "0.16.0",
"@getpaseo/protocol": "0.16.0",
"@getpaseo/relay": "0.16.0",
"@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.0",
"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.0",
"dependencies": {
"@getpaseo/plugin": "*",
"zod": "^4.4.3"
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "paseo",
"version": "0.16.1",
"version": "0.16.0",
"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 requestUrl = new URL((await daemonRequest).url());
expect(requestUrl.port).toBe(getE2EDaemonPort());
expect(requestUrl.searchParams.get("token")).toBeTruthy();
expect(new URL(downloaded.url()).protocol).toBe("blob:");
const url = new URL(downloaded.url());
expect(url.protocol).toBe("http:");
expect(url.port).toBe(getE2EDaemonPort());
expect(url.pathname).toBe("/api/files/download");
expect(url.searchParams.get("token")).toBeTruthy();
expect(downloaded.suggestedFilename()).toBe(fileName);
const savedFile = testInfo.outputPath(fileName);
await downloaded.saveAs(savedFile);
@@ -479,45 +479,6 @@ test("downloads a file over direct TCP with its original filename and bytes", as
expect(await readFile(savedFile)).toEqual(source);
});
test("keeps the app open and shows the error when the host rejects a download", async ({
page,
}, testInfo) => {
const fileName = "removed-during-download.bin";
const filePath = path.join(workspace.workspaceDirectory, fileName);
const source = Buffer.from([0, 1, 2, 255]);
await writeFile(filePath, source);
await gotoWorkspace(page, workspace.workspaceId);
await openFileExplorer(page);
const workspaceUrl = page.url();
// The file disappears after the token is issued, so the real daemon answers 404.
await page.route(
"**/api/files/download?*",
async (route) => {
await rm(filePath);
await route.continue();
},
{ times: 1 },
);
await page
.getByTestId("file-explorer-tree-scroll")
.getByText(fileName, { exact: true })
.click({ button: "right" });
await page.getByRole("menuitem", { name: "Download", exact: true }).click();
await expect(
page.getByText("Failed to download file (HTTP 404).", { exact: true }),
).toBeVisible();
expect(page.url()).toBe(workspaceUrl);
await writeFile(filePath, source);
const downloaded = await downloadFileFromExplorer(page, fileName);
const savedFile = testInfo.outputPath(fileName);
await downloaded.saveAs(savedFile);
expect(await readFile(savedFile)).toEqual(source);
expect(page.url()).toBe(workspaceUrl);
});
test("downloads an unsupported binary from its preview with original filename and bytes", async ({
page,
}, testInfo) => {
@@ -208,35 +208,6 @@ test.describe("Plugin sidebar items", () => {
});
});
test("a short desktop sidebar keeps workspaces usable while navigation scrolls", async ({
page,
}) => {
await page.setViewportSize({ width: 1280, height: 480 });
await gotoAppShell(page);
await expect(botRow(page, "status")).toBeAttached();
const workspace = visibleTestId(page, `sidebar-workspace-row-${getServerId()}:${workspaceId}`);
await expect(workspace).toBeInViewport({ ratio: 1 });
await expect(botRow(page, "status")).not.toBeInViewport();
await test.step("navigation stays within half the sidebar", async () => {
const nav = await boxOf(visibleTestId(page, "sidebar-nav-scroll"));
expect(nav.height).toBeLessThanOrEqual(480 / 2 + 1);
});
await test.step("scrolling navigation reaches its last row without moving workspaces", async () => {
const before = await boxOf(workspace);
await visibleTestId(page, "sidebar-global-new-workspace").hover();
await page.mouse.wheel(0, 800);
await expect(botRow(page, "status")).toBeInViewport({ ratio: 1 });
await expect(workspace).toBeInViewport({ ratio: 1 });
expect((await boxOf(workspace)).y).toBe(before.y);
await qaScreenshot(page, "desktop-short-sidebar-nav-scrolled");
await botRow(page, "status").click();
await expect(page.getByText("Bot status details", { exact: true })).toBeVisible();
await page.getByRole("button", { name: "Close bot status", exact: true }).click();
});
});
test("a restored plugin screen waits for its catalog before rendering", async ({ page }) => {
await page.setViewportSize(WIDE);
await gotoWorkspace(page, workspaceId);
@@ -110,7 +110,6 @@ test.describe("Sidebar items in Appearance settings", () => {
await test.step("the sidebar starts in the default order", async () => {
await expectSidebarOrder(page, ["new-workspace", "history", "search", "schedules"]);
await expect(page.locator('[data-testid="sidebar-nav-separator"]:visible')).toHaveCount(1);
});
await test.step("the Sidebar section lists every item in the same order", async () => {
@@ -196,9 +195,6 @@ test.describe("Sidebar items in Appearance settings", () => {
await expectSidebarItemHidden(page, "history");
await expectSidebarItemHidden(page, "search");
await expectSidebarItemHidden(page, "schedules");
// Nothing is left above the Workspaces section: no drag strip, no empty divider.
await expect(page.locator('[data-testid="sidebar-nav-drag-strip"]:visible')).toHaveCount(0);
await expect(page.locator('[data-testid="sidebar-nav-separator"]:visible')).toHaveCount(0);
});
});
@@ -1,36 +0,0 @@
import { expect, test } from "../support/fixtures";
import { gotoAppShell } from "../support/helpers/app";
import {
expectFooterActionsInline,
seedDockedSidebarWidth,
} from "../support/helpers/sidebar-footer-overflow";
// Chromium's pointer bitmasks expose both inputs while the mouse is primary.
test.use({
viewport: { width: 1280, height: 800 },
launchOptions: {
args: [
"--blink-settings=primaryPointerType=4,availablePointerTypes=6,primaryHoverType=2,availableHoverTypes=3",
],
},
});
test("a touchscreen laptop keeps sidebar actions visible with a fine primary pointer", async ({
page,
}) => {
await seedDockedSidebarWidth(page, 200);
await gotoAppShell(page);
expect(
await page.evaluate(() => ({
finePrimary: matchMedia("(pointer: fine)").matches,
touchScreen: matchMedia("(any-pointer: coarse)").matches,
})),
).toEqual({ finePrimary: true, touchScreen: true });
await expectFooterActionsInline(page, [
"sidebar-add-project",
"sidebar-usage-icon",
"sidebar-hosts-trigger",
"sidebar-help",
"sidebar-settings",
]);
});
@@ -718,3 +718,108 @@ test.describe("Half-screen desktop layout", () => {
}
});
});
// An iPad in the browser runs the desktop layout with the sidebar pinned, but it can't hover,
// and iOS Safari fires no contextmenu event for a long press. The kebab is the only way in.
test.describe("Workspace row menu on a wide touch screen", () => {
test.use({ viewport: { width: 1194, height: 834 }, isMobile: true, hasTouch: true });
test("shows the row's menu button without hovering and opens it with a tap", async ({
page,
}, info) => {
const workspace = await seedWorkspace({ repoPrefix: "sidebar-touch-menu-" });
const workspaceKey = `${getServerId()}:${workspace.workspaceId}`;
try {
await gotoAppShell(page);
await waitForSidebarWorkspace(page, workspace.workspaceId);
const kebab = page.getByTestId(`sidebar-workspace-kebab-${workspaceKey}`);
await expect(kebab).toBeVisible({ timeout: 30_000 });
await expect(kebab).toHaveCSS("opacity", "1");
await page.screenshot({ path: info.outputPath("touch-sidebar-row-menu.png") });
await kebab.tap();
await expect(
page.getByTestId(`sidebar-workspace-menu-copy-path-${workspaceKey}`),
).toBeVisible({ timeout: 30_000 });
} finally {
await workspace.cleanup();
}
});
test("resizes the sidebar with a finger drag on its grip", async ({ page, context }, info) => {
await gotoAppShell(page);
const grip = page.getByTestId("left-sidebar-resize-handle");
await expect(grip).toBeVisible({ timeout: 30_000 });
const before = await grip.boundingBox();
if (!before) throw new Error("The sidebar resize grip has no box");
const x = before.x + before.width / 2;
const y = before.y + before.height / 2;
// Nothing else may sit on top of the grip, or a finger can't reach it.
const hit = await page.evaluate(
({ px, py }) =>
document.elementFromPoint(px, py)?.closest("[data-testid]")?.getAttribute("data-testid"),
{ px: x, py: y },
);
expect(hit).toBe("left-sidebar-resize-handle");
const cdp = await context.newCDPSession(page);
await cdp.send("Input.dispatchTouchEvent", {
type: "touchStart",
touchPoints: [{ x, y, id: 1 }],
});
for (let step = 1; step <= 10; step += 1) {
await cdp.send("Input.dispatchTouchEvent", {
type: "touchMove",
touchPoints: [{ x: x + step * 8, y, id: 1 }],
});
}
await cdp.send("Input.dispatchTouchEvent", { type: "touchEnd", touchPoints: [] });
await expect
.poll(async () => (await grip.boundingBox())?.x ?? before.x, { timeout: 10_000 })
.toBeGreaterThan(before.x + 40);
await page.screenshot({ path: info.outputPath("touch-sidebar-resized.png") });
});
});
// A touch-screen laptop driven by a mouse reports a coarse pointer among its pointers, but its
// primary pointer hovers, so rows keep revealing their menu on hover.
test.describe("Workspace row menu on a touch-screen laptop with a mouse", () => {
test.use({ viewport: { width: 1440, height: 900 } });
test.beforeEach(async ({ page }) => {
await page.addInitScript(() => {
const browserMatchMedia = window.matchMedia.bind(window);
window.matchMedia = (query: string) => {
const result = browserMatchMedia(query);
if (query !== "(any-pointer: coarse)") return result;
return new Proxy(result, {
get: (target, key) => {
if (key === "matches") return true;
const value: unknown = Reflect.get(target, key, target);
return typeof value === "function" ? value.bind(target) : value;
},
});
};
});
});
test("keeps the row's menu button behind hover", async ({ page }) => {
const workspace = await seedWorkspace({ repoPrefix: "sidebar-hybrid-menu-" });
const workspaceKey = `${getServerId()}:${workspace.workspaceId}`;
try {
await gotoAppShell(page);
const row = await waitForSidebarWorkspace(page, workspace.workspaceId);
expect(await page.evaluate(() => window.matchMedia("(any-pointer: coarse)").matches)).toBe(
true,
);
const kebab = page.getByTestId(`sidebar-workspace-kebab-${workspaceKey}`);
await expect(kebab).toHaveCount(0);
await row.hover();
await expect(kebab).toBeVisible({ timeout: 10_000 });
} finally {
await workspace.cleanup();
}
});
});
@@ -73,36 +73,35 @@ function labelRow(page: import("@playwright/test").Page, name: string) {
return page.getByTestId(`workspace-label-picker-row-${name}`);
}
async function box(locator: import("@playwright/test").Locator) {
const measured = await locator.boundingBox();
if (!measured) throw new Error("expected a visible element to measure");
return measured;
}
async function size(locator: import("@playwright/test").Locator) {
const { width, height } = await settled(locator);
await settled(locator);
const { width, height } = await box(locator);
return { width, height };
}
/**
* Waits until an element is on screen and stops moving, and returns where it settled.
* Waits until an element stops moving.
*
* The flyout scales in and the sidebar behind it re-lays out as the filter changes, so a rail
* measured mid-animation is not a rail — and a measurement built from two `boundingBox()` calls
* would take its two halves from two different frames. A row that has not been laid out yet has
* no box at all; that is not settled either, so the poll keeps waiting instead of failing.
* would take its two halves from two different frames.
*/
async function settled(locator: import("@playwright/test").Locator) {
const last: { box: Awaited<ReturnType<typeof locator.boundingBox>>; key: string | null } = {
box: null,
key: null,
};
let previous = "";
await expect
.poll(async () => {
const current = await locator.boundingBox();
const key = current ? JSON.stringify(current) : null;
const stable = key !== null && key === last.key;
last.box = current;
last.key = key;
const current = JSON.stringify(await box(locator));
const stable = current === previous;
previous = current;
return stable;
})
.toBe(true);
if (!last.box) throw new Error("a settled element has a box");
return last.box;
}
async function expectAssigned(
@@ -170,11 +170,6 @@ export interface ModelTriggerLabelState {
modelShown: boolean;
modelText: string;
modelTruncated: boolean;
/**
* The model label shows what its box fits right now: the full text when it fits, otherwise a
* truncation that fits. False while the control has yet to catch up with a reflow.
*/
modelFitsBox: boolean;
}
declare global {
@@ -199,18 +194,12 @@ function readModelTriggerLabelStateInPage(): ModelTriggerLabelState {
};
const modelShown = model !== undefined && shown(model);
const modelText = model?.textContent ?? "";
const overflows = (node: Element) => node.scrollWidth > node.clientWidth;
const modelOverflows = model !== undefined && overflows(model);
// The label's box is sized by an invisible copy of the full text, its first child, so the box
// follows a reflow at once while the shown text waits for the control's next layout event.
const fullTextSizer = model?.parentElement?.parentElement?.firstElementChild;
const fullTextFits = fullTextSizer ? !overflows(fullTextSizer) : true;
return {
modelShown,
modelText,
thinkingShown: modelShown && thinking !== undefined,
modelTruncated: modelText.endsWith("…") || modelOverflows,
modelFitsBox: !modelOverflows && modelText.endsWith("…") !== fullTextFits,
modelTruncated:
model !== undefined && (modelText.endsWith("…") || model.scrollWidth > model.clientWidth),
};
}
@@ -228,26 +217,13 @@ export async function recordModelTriggerFramesFromLoad(page: Page): Promise<void
})()`);
}
/**
* The model control's labels once it has caught up with its width: two reads 100ms apart agree
* and the model label shows what its box fits. A resize reflows the page at once, but the control
* chooses its labels again only when its layout events arrive, and on a slow runner that takes
* longer than 100ms. Until then the label can be clipped by the browser beside the thinking
* label, or truncated in a box that has since widened.
*/
/** The model control's labels once two reads 100ms apart agree. */
export async function readSettledModelTriggerLabels(page: Page): Promise<ModelTriggerLabelState> {
const deadline = Date.now() + 10_000;
let previous = await page.evaluate(readModelTriggerLabelStateInPage);
for (;;) {
await page.waitForTimeout(100);
const next = await page.evaluate(readModelTriggerLabelStateInPage);
const agrees = JSON.stringify(next) === JSON.stringify(previous);
if (agrees && next.modelFitsBox) return next;
if (Date.now() > deadline) {
throw new Error(
`the model control never settled on a label that fits its box: ${JSON.stringify(next)}`,
);
}
if (JSON.stringify(next) === JSON.stringify(previous)) return next;
previous = next;
}
}
@@ -97,15 +97,18 @@ export class ImportSessionFlow {
await target.scrollIntoViewIfNeeded();
await expect(target).toBeInViewport();
}
/**
* Scrolls the virtualized list, the only one that leaves rows unmounted. A row handle is no way
* in: the list unmounts rows as it scrolls, and a detached row has no scroller above it.
*/
private async scrollList(forward: boolean) {
await this.page.getByTestId("import-session-list").evaluate((list, advance) => {
list.scrollTop = advance ? list.scrollTop + list.clientHeight * 0.8 : 0;
list.dispatchEvent(new Event("scroll"));
}, forward);
await this.page
.locator('[data-testid^="import-session-session-"]')
.first()
.evaluate((row, advance) => {
let element = row.parentElement;
while (element && !["auto", "scroll"].includes(getComputedStyle(element).overflowY))
element = element.parentElement;
if (!element) throw new Error("Import list has no scroll owner");
element.scrollTop = advance ? element.scrollTop + element.clientHeight * 0.8 : 0;
element.dispatchEvent(new Event("scroll"));
}, forward);
}
async search(query: string) {
await this.page.getByTestId("import-session-search").fill(query);
@@ -117,18 +120,11 @@ export class ImportSessionFlow {
await this.page.getByTestId("import-session-search").fill("");
await expect(this.page.getByTestId("import-session-load-more")).toBeVisible();
}
/** Load more keeps the reader down the list instead of sending them back to the top. */
async loadMore() {
const loadMore = this.page.getByTestId("import-session-load-more");
const topRow = this.page.getByTestId((await this.rowIds())[0]!);
await expect(topRow).toBeInViewport();
await loadMore.click();
// The next page is the last and short, so the button leaves once it lands.
await expect(loadMore).toHaveCount(0);
await expect(this.page.getByText("Loading sessions...", { exact: true })).toHaveCount(0);
await expect(topRow).not.toBeInViewport();
await this.page.getByTestId("import-session-load-more").click();
await this.revealSession("fixture-root-20");
await expect(this.page.getByText("Root session 20", { exact: true })).toBeInViewport();
await expect(this.page.getByTestId("import-session-load-more")).toHaveCount(0);
}
async retryProvider(provider: string, label: string) {
await this.expectProviderError(label);
@@ -60,8 +60,14 @@ export function footerOverflowMenu(page: Page): Locator {
return page.getByTestId("sidebar-footer-overflow-menu");
}
/** The icon line shows exactly `testIDs`, in order. */
export async function expectFooterActionsInline(page: Page, testIDs: string[]): Promise<void> {
/**
* The icon line shows exactly `testIDs`, in order, each `controlSize` square and wholly inside the
* line's box, so no button is cut off by the sidebar's edge.
*/
export async function expectFooterLine(
page: Page,
input: { testIDs: string[]; controlSize: number },
): Promise<void> {
const line = footerLine(page);
await expect(line).toHaveCount(1);
await expect
@@ -70,16 +76,7 @@ export async function expectFooterActionsInline(page: Page, testIDs: string[]):
.locator(FOOTER_LINE_TEST_IDS.map((testID) => `[data-testid="${testID}"]`).join(","))
.evaluateAll((elements) => elements.map((element) => element.getAttribute("data-testid"))),
)
.toEqual(testIDs);
}
/** The actions are square and fit inside the line. */
export async function expectFooterLine(
page: Page,
input: { testIDs: string[]; controlSize: number },
): Promise<void> {
await expectFooterActionsInline(page, input.testIDs);
const line = footerLine(page);
.toEqual(input.testIDs);
const { row, buttons } = await line.evaluate((element, testIDs) => {
const rect = (node: Element) => {
const { x, width, height } = node.getBoundingClientRect();
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/app",
"version": "0.16.1",
"version": "0.16.0",
"private": true,
"main": "index.ts",
"scripts": {
@@ -17,13 +17,6 @@ import { isNative } from "@/constants/platform";
* On macOS, Electron handles edge resize natively.
*/
/**
* Marks a scroll viewport as window content: it and its descendants emit no window
* regions, because Electron does not clip app-region rects to scroll viewports.
* See the `[data-window-content]` rule in public/index.html.
*/
export const WINDOW_CONTENT_DATASET = { "window-content": "" };
export const titlebarDragSurfaceStyle: React.CSSProperties = {
cursor: "default",
// @ts-expect-error — WebkitAppRegion is not in CSSProperties
@@ -17,11 +17,6 @@ export function nextPageLimit(limit: number): number {
return PAGE_LIMITS.find((candidate) => candidate > limit) ?? limit;
}
/** The page Load more grew this limit from, or null for the first page. */
export function previousPageLimit(limit: number): number | null {
return PAGE_LIMITS.findLast((candidate) => candidate < limit) ?? null;
}
export function requiresImportSessionsHostUpgrade(input: {
supportsSnapshot: boolean;
workspaceId?: string | null;
@@ -1172,44 +1172,6 @@ describe("ImportSessionSheet", () => {
});
});
it("keeps the loaded list in place while Load more fetches the next page", async () => {
let releaseNextPage: () => void = () => undefined;
const nextPage = new Promise<void>((resolve) => {
releaseNextPage = resolve;
});
const fetchRecentProviderSessions = vi.fn(async (options: { limit?: number } | undefined) => {
if (options?.limit !== 15) await nextPage;
return {
requestId: "recent-provider-sessions",
entries: createPageOfEntries(options?.limit === 15 ? 15 : 20),
};
});
renderSheet(createRecentSessionsClient(fetchRecentProviderSessions, vi.fn()), {
cwd: null,
snapshot: { supportsSnapshot: true, entries: [createSnapshotEntry("claude")] },
});
fireEvent.click(await screen.findByTestId("import-session-load-more"));
// The list the user scrolled to Load more is the one they keep: replacing it would drop
// them back at the top, behind a loading state, until the larger page lands.
const list = screen.getByTestId("import-session-list");
await waitFor(() => {
expect(fetchRecentProviderSessions).toHaveBeenCalledWith({
providers: ["claude"],
limit: 45,
});
});
expect(screen.getByTestId("import-session-list")).toBe(list);
expect(screen.queryByText("Loading sessions...")).toBeNull();
releaseNextPage();
await waitFor(() => {
expect(screen.queryByTestId("import-session-load-more")).toBeNull();
});
expect(screen.getByTestId("import-session-list")).toBe(list);
});
it("stops the refresh spinner and retries only the failed provider", async () => {
const fetchRecentProviderSessions = vi.fn(
async (options: { providers?: string[] } | undefined) => {
@@ -1,6 +1,6 @@
import React, { type ReactNode, useCallback, useEffect, useMemo, useRef, useState } from "react";
import { Pressable, type PressableStateCallbackType, Text, View } from "react-native";
import { useMutation, useQueries, useQueryClient, type QueryClient } from "@tanstack/react-query";
import { keepPreviousData, useMutation, useQueries, useQueryClient } from "@tanstack/react-query";
import { useTranslation } from "react-i18next";
import type {
DaemonClient,
@@ -40,7 +40,6 @@ import {
resolveDirectoryLabel,
nextPageLimit,
PER_PROVIDER_LIMIT,
previousPageLimit,
type ProviderErrorRow,
resolveImportTarget,
resolveProvidersToFetch,
@@ -101,12 +100,11 @@ interface SessionsQueryConfig {
// Query's default retry would keep the header spinner turning and pile up
// in-flight daemon requests behind a dead provider (#2512).
retry: false;
placeholderData: () => RecentSessionsResponse | undefined;
placeholderData: typeof keepPreviousData;
queryFn: () => Promise<RecentSessionsResponse>;
}
function buildSessionsQueriesConfig(args: {
queryClient: QueryClient;
providersToFetch: AgentProvider[] | null;
visible: boolean;
client: RecentProviderSessionsClient | null;
@@ -115,24 +113,14 @@ function buildSessionsQueriesConfig(args: {
limit: number;
hostDisconnectedMessage?: string;
}): SessionsQueryConfig[] {
const { queryClient, providersToFetch, visible, client, cwd, query, limit } = args;
const { hostDisconnectedMessage } = args;
const { providersToFetch, visible, client, cwd, query, limit, hostDisconnectedMessage } = args;
if (providersToFetch === null) return [];
const enabled = visible && Boolean(client);
const previousLimit = previousPageLimit(limit);
return providersToFetch.map((provider) => ({
queryKey: buildSessionsQueryKey({ cwd, query, limit, provider }),
enabled,
retry: false as const,
// While Load more fetches the next page, keep showing the page it grew from. React Query's
// keepPreviousData cannot do this here: useQueries gives a changed key a new observer, which
// has no previous data, so the rows would vanish and the list would remount at the top.
placeholderData: () =>
previousLimit === null
? undefined
: queryClient.getQueryData<RecentSessionsResponse>(
buildSessionsQueryKey({ cwd, query, limit: previousLimit, provider }),
),
placeholderData: keepPreviousData,
queryFn: async () => {
if (!client) {
throw new Error(hostDisconnectedMessage ?? i18n.t("workspace.terminal.hostDisconnected"));
@@ -534,7 +522,6 @@ export function ImportSessionSheet({
const queriesConfig = useMemo(
() =>
buildSessionsQueriesConfig({
queryClient,
providersToFetch,
visible,
client,
@@ -543,7 +530,7 @@ export function ImportSessionSheet({
limit: pageLimit,
hostDisconnectedMessage: t("workspace.terminal.hostDisconnected"),
}),
[queryClient, providersToFetch, visible, client, scopeCwd, query, pageLimit, t],
[providersToFetch, visible, client, scopeCwd, query, pageLimit, t],
);
const queries = useQueries({ queries: queriesConfig });
+43 -89
View File
@@ -9,16 +9,7 @@ import {
type LucideIcon,
} from "lucide-react-native";
import { useTranslation } from "react-i18next";
import {
memo,
useCallback,
useEffect,
useMemo,
useRef,
useState,
type ReactNode,
type RefObject,
} from "react";
import { memo, useCallback, useEffect, useMemo, useRef, useState, type RefObject } from "react";
import {
Pressable,
ScrollView,
@@ -28,19 +19,12 @@ import {
View,
type LayoutChangeEvent,
} from "react-native";
import {
Gesture,
type GestureType,
ScrollView as GHScrollView,
} from "react-native-gesture-handler";
import { Gesture, ScrollView as GHScrollView } from "react-native-gesture-handler";
import Animated, { runOnJS, useAnimatedStyle, useSharedValue } from "react-native-reanimated";
import { scheduleOnRN } from "react-native-worklets";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { StyleSheet, useUnistyles } from "react-native-unistyles";
import {
TitlebarDragRegion,
WINDOW_CONTENT_DATASET,
} from "@/components/desktop/titlebar-drag-region";
import { TitlebarDragRegion } from "@/components/desktop/titlebar-drag-region";
import { SidebarCloseButton } from "@/components/headers/sidebar-close-button";
import {
resolveDesktopSidebarInsetLeft,
@@ -55,7 +39,7 @@ import { HostPicker } from "@/components/hosts/host-picker";
import { SidebarDisplayPreferencesMenu } from "@/components/sidebar/display-preferences/menu";
import { SidebarSeparator } from "@/components/sidebar/sidebar-separator";
import { SidebarToastRegion } from "@/components/sidebar/sidebar-toast-region";
import { SidebarNavRows, useVisibleSidebarNavItems } from "@/components/sidebar/sidebar-nav-rows";
import { SidebarNavRows } from "@/components/sidebar/sidebar-nav-rows";
import { SidebarFooterIconHighlight } from "@/components/sidebar/sidebar-footer-icon-highlight";
import { SidebarHelpMenu } from "@/components/sidebar/sidebar-help-menu";
import { SidebarFooterOverflowMenu } from "@/components/sidebar/sidebar-footer-overflow-menu";
@@ -638,7 +622,29 @@ function MobileSidebar({
>
<View style={styles.sidebarContent} pointerEvents="auto">
<WindowChromeSafeArea placement="below" />
<SidebarNavScroll closeGestureRef={closeGestureRef}>{navRows}</SidebarNavScroll>
{platformIsNative ? (
<GHScrollView
// Same contract as the workspace list: vertical drags scroll the nav
// block, a clear horizontal intent still activates the close pan.
simultaneousHandlers={closeGestureRef}
style={styles.mobileNavScroll}
showsVerticalScrollIndicator={false}
alwaysBounceVertical={false}
testID="sidebar-nav-scroll"
>
{navRows}
</GHScrollView>
) : (
<ScrollView
style={styles.mobileNavScroll}
showsVerticalScrollIndicator={false}
alwaysBounceVertical={false}
testID="sidebar-nav-scroll"
>
{navRows}
</ScrollView>
)}
<SidebarSeparator />
<SidebarViewSlot dismiss={handleWorkspacePress}>
<SidebarToastRegion active={active}>
@@ -683,47 +689,6 @@ function MobileSidebar({
);
}
interface SidebarNavScrollProps {
closeGestureRef: RefObject<GestureType | undefined>;
/** Web only: the viewport emits no window regions (see WINDOW_CONTENT_DATASET). */
windowContent?: boolean;
children: ReactNode;
}
// The capped, scrolling nav block shared by the mobile and desktop sidebars, with the
// divider below it. The divider is a sibling because Unistyles does not patch the
// gesture-handler ScrollView.
function SidebarNavScroll({ closeGestureRef, windowContent, children }: SidebarNavScrollProps) {
return (
<>
{platformIsNative ? (
<GHScrollView
// Same contract as the workspace list: vertical drags scroll the nav
// block, a clear horizontal intent still activates the close pan.
simultaneousHandlers={closeGestureRef}
style={styles.navScroll}
showsVerticalScrollIndicator={false}
alwaysBounceVertical={false}
testID="sidebar-nav-scroll"
>
{children}
</GHScrollView>
) : (
<ScrollView
dataSet={windowContent ? WINDOW_CONTENT_DATASET : undefined}
style={styles.navScroll}
showsVerticalScrollIndicator={false}
alwaysBounceVertical={false}
testID="sidebar-nav-scroll"
>
{children}
</ScrollView>
)}
<SidebarSeparator testID="sidebar-nav-separator" />
</>
);
}
function DesktopSidebar({
theme,
workspaceGroups,
@@ -844,14 +809,12 @@ function DesktopSidebar({
],
[insetsTop, insets.bottom, insets.left, overlay, divisionLayout],
);
// Below the window controls' row, or in the top band's place, the first row starts flush.
const inTopBand = useTopBand() !== null;
// Windows and Linux draw their window controls top-right, so the sidebar has no chrome
// row there. The strip above the scrolling rows is then its window drag surface.
const showsChromeRow = ownsTopLeft || Boolean(DEV_BUILD_LABEL);
// With every top item hidden the sidebar starts at the Workspaces section, as before the
// nav scroller existed: no strip above it and no divider below it.
const hasNavRows = useVisibleSidebarNavItems().length > 0;
const showsDragStrip = hasNavRows && !showsChromeRow && !inTopBand;
const sidebarHeaderGroupStyle = useMemo(
() => [styles.sidebarHeaderGroup, (ownsTopLeft || inTopBand) && styles.sidebarHeaderGroupFlush],
[ownsTopLeft, inTopBand],
);
return (
<MobilePanelOverlay
panel="agent-list"
@@ -862,7 +825,7 @@ function DesktopSidebar({
<Animated.View style={desktopSidebarStyle}>
<View style={desktopSidebarBorderStyle}>
<View style={styles.sidebarDragArea}>
{showsChromeRow ? (
{ownsTopLeft || DEV_BUILD_LABEL ? (
<View style={styles.desktopChromeRow}>
<TitlebarDragRegion />
{DEV_BUILD_LABEL ? (
@@ -879,21 +842,11 @@ function DesktopSidebar({
</View>
) : null}
</View>
) : null}
{showsDragStrip ? (
<View style={styles.desktopDragStrip} testID="sidebar-nav-drag-strip">
<TitlebarDragRegion />
</View>
) : null}
) : (
<TitlebarDragRegion />
)}
<SidebarNavRows style={sidebarHeaderGroupStyle} onBeforeNavigate={closeSidebar} />
</View>
{/* The drag overlay stays above this viewport: Electron does not clip
app-region rects to scroll viewports, so a scrolled-out row would
still claim its no-drag rect. */}
{hasNavRows ? (
<SidebarNavScroll closeGestureRef={closeGestureRef} windowContent>
<SidebarNavRows style={styles.sidebarHeaderGroup} onBeforeNavigate={closeSidebar} />
</SidebarNavScroll>
) : null}
<SidebarViewSlot dismiss={closeSidebar}>
<SidebarToastRegion active={active}>
@@ -982,18 +935,19 @@ const staticStyles = RNStyleSheet.create({
});
const styles = StyleSheet.create((theme) => ({
// The rows start flush: the chrome row, drag strip, or top band above them gives the inset.
sidebarHeaderGroup: {
paddingTop: theme.spacing[2],
gap: 2,
paddingBottom: theme.spacing[1.5],
borderBottomWidth: 1,
borderBottomColor: theme.colors.border,
},
desktopDragStrip: {
position: "relative",
height: theme.spacing[2],
sidebarHeaderGroupFlush: {
paddingTop: 0,
},
// The nav block caps at half the sidebar; a long item list scrolls inside the
// cap instead of crowding the workspace list off a short screen.
navScroll: {
mobileNavScroll: {
flexGrow: 0,
flexShrink: 1,
maxHeight: "50%",
@@ -12,6 +12,20 @@ describe("resolveSidebarResizeHandleGeometry", () => {
expect(geometry.height ?? 0).toBeGreaterThanOrEqual(MIN_TOUCH_TARGET);
});
it("keeps a web touch grip inside the sidebar, level with the top navigation rows", () => {
const geometry = resolveSidebarResizeHandleGeometry(false, true);
// The sidebar clips its overflow, so a grip outside it can't be touched.
expect(geometry.edgeOffset).toBeGreaterThanOrEqual(0);
expect(geometry.width).toBeGreaterThanOrEqual(MIN_TOUCH_TARGET);
// Not centred, where it would cover a row's menu button.
expect(geometry.top).toBe(48);
});
it("centres the native touch grip", () => {
expect(resolveSidebarResizeHandleGeometry(false).top).toBeNull();
});
it("straddles the border for a fine pointer", () => {
const geometry = resolveSidebarResizeHandleGeometry(true);
@@ -10,6 +10,13 @@
* children whose ancestors contain the point. A strip hanging outside the
* sidebar is dead on touch, and what remains is far too small for a finger.
* So the touch variant sits fully inside the sidebar and is sized for a thumb.
*
* A touch screen on the web (an iPad in the browser) shows every row's menu button
* at the sidebar's right edge, and a grip centred on that edge covers the menu of
* whichever row is at mid-height. The grip can't move outside the sidebar either:
* the sidebar clips its overflow, which in a browser also clips hit-testing. So on
* the web the touch grip stays inside and sits level with the top navigation rows
* (New workspace, History, Search...), which have nothing at their right edge.
*/
export const POINTER_HANDLE_WIDTH = 10;
@@ -37,21 +44,29 @@ export interface SidebarResizeHandleGeometry {
width: number;
/** `null` stretches the hit area to the sidebar's full height. */
height: number | null;
/** Distance from the sidebar's top to the hit area; `null` centres it vertically. */
top: number | null;
}
/** The web touch grip's distance from the sidebar top: beside the top navigation rows. */
export const WEB_TOUCH_HANDLE_TOP = 48;
export function resolveSidebarResizeHandleGeometry(
finePointer: boolean,
web = false,
): SidebarResizeHandleGeometry {
if (finePointer) {
return {
edgeOffset: -POINTER_HANDLE_WIDTH / 2,
width: POINTER_HANDLE_WIDTH,
height: null,
top: null,
};
}
return {
edgeOffset: 0,
width: TOUCH_HANDLE_WIDTH,
height: TOUCH_HANDLE_HEIGHT,
top: web ? WEB_TOUCH_HANDLE_TOP : null,
};
}
@@ -85,14 +85,24 @@ function PointerResizeHandle({ edge, gesture, testID }: SidebarResizeHandleProps
);
}
// On the web the grip shows at rest, so a touch user can find it.
function restingGripStyle(pressed: boolean) {
if (pressed) return styles.visibleGrip;
if (isWeb) return styles.restingGrip;
return styles.hiddenGrip;
}
function TouchResizeHandle({ edge, gesture, pressed, testID }: SidebarResizeHandleProps) {
const geometry = resolveSidebarResizeHandleGeometry(false);
const geometry = resolveSidebarResizeHandleGeometry(false, isWeb && edge === "right");
// `box-none` keeps the full-height column out of hit-testing so only the
// grab target steals taps from the rows behind it.
const layerStyle = [
styles.touchLayer,
{ width: geometry.width },
edgeOffsetStyle(edge, geometry.edgeOffset),
geometry.top === null
? null
: { justifyContent: "flex-start" as const, paddingTop: geometry.top },
];
const targetStyle = [
styles.touchTarget,
@@ -101,7 +111,7 @@ function TouchResizeHandle({ edge, gesture, pressed, testID }: SidebarResizeHand
const gripStyle = [
styles.grip,
edge === "left" ? styles.leftEdgeGrip : styles.rightEdgeGrip,
pressed ? styles.visibleGrip : styles.hiddenGrip,
restingGripStyle(pressed),
];
return (
@@ -159,7 +169,10 @@ const styles = StyleSheet.create((theme) => ({
opacity: 0,
},
visibleGrip: {
opacity: 0.3,
opacity: 0.55,
},
restingGrip: {
opacity: 0.35,
},
leftEdgeGrip: {
alignSelf: "flex-start",
@@ -106,6 +106,7 @@ import {
SidebarWorkspaceRowContent,
SidebarWorkspaceShortcutBadge,
resolveTrailingActionVisibility,
useRowActionsAlwaysVisible,
SidebarWorkspaceTrailingActionBase,
SidebarWorkspaceTrailingActionOverlay,
SidebarWorkspaceTrailingActionSlot,
@@ -409,7 +410,6 @@ function ProjectRowTrailingActions({
settingsTarget,
projectPath,
isHovered,
isMobileBreakpoint,
isProjectActive,
onBeginWorkspaceSetup,
onRemoveProject,
@@ -421,13 +421,12 @@ function ProjectRowTrailingActions({
settingsTarget: { serverId: string; projectId: string } | null;
projectPath: string;
isHovered: boolean;
isMobileBreakpoint: boolean;
isProjectActive: boolean;
onBeginWorkspaceSetup: () => void;
onRemoveProject?: () => void;
removeProjectStatus: "idle" | "pending" | "success";
}) {
const actionsVisible = isHovered || platformIsNative || isMobileBreakpoint;
const actionsVisible = useRowActionsAlwaysVisible() || isHovered;
return (
<View style={styles.projectTrailingActions}>
{worktreeTarget ? (
@@ -604,7 +603,7 @@ function WorkspaceRowRightGroup({
workspace,
backdrop,
isHovered,
isTouchPlatform,
actionsAlwaysVisible,
isCreating,
showShortcutBadge,
shortcutNumber,
@@ -624,7 +623,7 @@ function WorkspaceRowRightGroup({
workspace: SidebarWorkspaceEntry;
backdrop: SidebarSurfaceBackdrop;
isHovered: boolean;
isTouchPlatform: boolean;
actionsAlwaysVisible: boolean;
isCreating: boolean;
showShortcutBadge: boolean;
shortcutNumber: number | null;
@@ -657,7 +656,7 @@ function WorkspaceRowRightGroup({
trailing,
hasArchiveAction: Boolean(onArchive),
isHovered,
isTouchPlatform,
actionsAlwaysVisible,
showShortcut,
});
const kebab = useOpenKebabMenuVisibility(showKebabInSlot);
@@ -881,7 +880,6 @@ function ProjectHeaderRow({
const [isHovered, setIsHovered] = useState(false);
const [isHighlighted, setIsHighlighted] = useState(false);
const [contextMenuOpen, setContextMenuOpen] = useState(false);
const isMobileBreakpoint = useIsCompactFormFactor();
const localDaemonServerId = useLocalDaemonServerId();
const projectPath = resolveSidebarProjectLocalPath(project, localDaemonServerId);
const settingsTarget = project.hosts[0] ?? null;
@@ -964,7 +962,6 @@ function ProjectHeaderRow({
settingsTarget={settingsTarget}
projectPath={projectPath}
isHovered={isHovered}
isMobileBreakpoint={isMobileBreakpoint}
isProjectActive={isProjectActive}
onBeginWorkspaceSetup={handleBeginWorkspaceSetup}
onRemoveProject={onRemoveProject}
@@ -1079,6 +1076,7 @@ function WorkspaceRowInner({
const isCompact = useIsCompactFormFactor();
const [isHighlighted, setIsHighlighted] = useState(false);
const isTouchPlatform = platformIsNative || isCompact;
const actionsAlwaysVisible = useRowActionsAlwaysVisible();
const interaction = useLongPressDragInteraction({
drag,
menuController,
@@ -1173,7 +1171,7 @@ function WorkspaceRowInner({
workspace={workspace}
backdrop={backdrop}
isHovered={isHovered}
isTouchPlatform={isTouchPlatform}
actionsAlwaysVisible={actionsAlwaysVisible}
isCreating={isCreating}
showShortcutBadge={showShortcutBadge}
shortcutNumber={shortcutNumber}
@@ -35,19 +35,14 @@ interface SidebarNavRowsProps extends SidebarNavRowProps {
firstRowTrailing?: ReactNode;
}
/** The top-level items the user keeps visible, in display order. */
export function useVisibleSidebarNavItems() {
const { items } = useSidebarNavItems("header");
return useMemo(() => items.filter((item) => item.visible), [items]);
}
/**
* Top-level sidebar navigation, ordered and filtered by the user's
* `sidebarNavItems` preference. Renders nothing — not even the bordered group
* wrapper — when every item is hidden and there is no `firstRowTrailing`.
*/
export function SidebarNavRows({ style, onBeforeNavigate, firstRowTrailing }: SidebarNavRowsProps) {
const visibleItems = useVisibleSidebarNavItems();
const { items } = useSidebarNavItems("header");
const visibleItems = useMemo(() => items.filter((item) => item.visible), [items]);
const groupRef = useRef<View | null>(null);
if (visibleItems.length === 0 && !firstRowTrailing) return null;
@@ -46,6 +46,7 @@ import {
SidebarWorkspaceRowFrame,
SidebarWorkspaceRowContent,
resolveTrailingActionVisibility,
useRowActionsAlwaysVisible,
type SidebarWorkspaceTrailingPresentation,
SidebarWorkspaceTrailingActionBase,
SidebarWorkspaceTrailingActionOverlay,
@@ -828,6 +829,7 @@ function StatusWorkspaceRowInnerContent({
}) {
const isCompact = useIsCompactFormFactor();
const isTouchPlatform = platformIsNative || isCompact;
const actionsAlwaysVisible = useRowActionsAlwaysVisible();
const [isHighlighted, setIsHighlighted] = useState(false);
const trailing = useSidebarWorkspaceTrailing();
const {
@@ -874,7 +876,7 @@ function StatusWorkspaceRowInnerContent({
trailing,
hasArchiveAction: Boolean(onArchive),
isHovered,
isTouchPlatform,
actionsAlwaysVisible,
showShortcut,
});
const workspaceRowStyle = getStatusWorkspaceRowStyle({
@@ -16,6 +16,8 @@ import {
type SidebarWorkspaceTrailing,
} from "@/components/sidebar/workspace-trailing";
import { useAppSettings } from "@/hooks/use-settings";
import { usePointerCapabilities } from "@/hooks/pointer-capabilities";
import { useIsCompactFormFactor } from "@/constants/layout";
import { densityIconBox } from "@/styles/density";
import type { Theme } from "@/styles/theme";
import type { SidebarStateBucket } from "@/utils/sidebar-agent-state";
@@ -365,6 +367,17 @@ export function SidebarWorkspaceShortcutBadge({ number }: { number: number }) {
export type SidebarWorkspaceTrailingPresentation = "visible" | "hidden" | "absent";
/**
* Whether a sidebar row keeps its actions shown instead of revealing them on hover. True on the
* compact layout and wherever the primary pointer can't hover: native apps, and a touch screen in
* a wide browser (an iPad in Safari), where the menu button is the only way to the row menu.
*/
export function useRowActionsAlwaysVisible(): boolean {
const isCompact = useIsCompactFormFactor();
const { finePointer } = usePointerCapabilities();
return isCompact || !finePointer;
}
/**
* What the trailing slot shows for a row. Derived in one place because three row renderers
* share it: the two project-mode rows and the status-mode row. The rule used to be copied
@@ -380,14 +393,14 @@ export function resolveTrailingActionVisibility({
trailing,
hasArchiveAction,
isHovered,
isTouchPlatform,
actionsAlwaysVisible,
showShortcut,
}: {
workspace: SidebarWorkspaceEntry;
trailing: SidebarWorkspaceTrailing;
hasArchiveAction: boolean;
isHovered: boolean;
isTouchPlatform: boolean;
actionsAlwaysVisible: boolean;
showShortcut: boolean;
}): {
trailingPresentation: SidebarWorkspaceTrailingPresentation;
@@ -398,10 +411,11 @@ export function resolveTrailingActionVisibility({
reserveSlotWidth: boolean;
} {
const hasTrailing = hasSidebarWorkspaceTrailing({ workspace, trailing });
const showKebab = Boolean(hasArchiveAction && (isHovered || isTouchPlatform)) && !showShortcut;
const showKebab =
Boolean(hasArchiveAction && (isHovered || actionsAlwaysVisible)) && !showShortcut;
// Touch permanently replaces the stats with the menu. Only temporary shortcut hints
// conceal content while retaining its width, so desktop rows do not shift.
const hasContent = hasTrailing && !(hasArchiveAction && isTouchPlatform);
const hasContent = hasTrailing && !(hasArchiveAction && actionsAlwaysVisible);
let trailingPresentation: SidebarWorkspaceTrailingPresentation = "absent";
if (hasContent) trailingPresentation = showShortcut ? "hidden" : "visible";
return {
@@ -409,7 +423,7 @@ export function resolveTrailingActionVisibility({
showKebab,
// One-click archive is a pointer affordance: on touch it would sit a few pixels from the
// kebab and turn a miss into an archive.
showArchiveButton: showKebab && isHovered && !isTouchPlatform,
showArchiveButton: showKebab && isHovered && !actionsAlwaysVisible,
// The scrim paints the row's own hover background, so it can only be drawn on a hovered
// row — over an unhovered one the gradient fades to the wrong color. That is also why
// touch, which shows the kebab without ever hovering, never gets one.
@@ -419,7 +433,7 @@ export function resolveTrailingActionVisibility({
// does; the kebab only does on touch, where there is no hover for it to appear on and so
// no scrim to let it overlay the title. Everywhere else the width goes back to the title
// and the kebab fades in over its tail.
reserveSlotWidth: hasContent || (hasArchiveAction && isTouchPlatform),
reserveSlotWidth: hasContent || (hasArchiveAction && actionsAlwaysVisible),
};
}
@@ -68,27 +68,24 @@ const theme = {
} as unknown as Theme;
describe("control sizing gate", () => {
it("is touch-sized in the compact layout or where touch is the primary input, and pointer-sized otherwise", () => {
expect(resolveControlSizing({ compactLayout: true, touchPrimaryPointer: true })).toBe("touch");
expect(resolveControlSizing({ compactLayout: true, touchPrimaryPointer: false })).toBe("touch");
expect(resolveControlSizing({ compactLayout: false, touchPrimaryPointer: true })).toBe("touch");
expect(resolveControlSizing({ compactLayout: false, touchPrimaryPointer: false })).toBe(
"pointer",
);
it("is touch-sized in the compact layout or on a touch screen, and pointer-sized otherwise", () => {
expect(resolveControlSizing({ compactLayout: true, touchScreen: true })).toBe("touch");
expect(resolveControlSizing({ compactLayout: true, touchScreen: false })).toBe("touch");
expect(resolveControlSizing({ compactLayout: false, touchScreen: true })).toBe("touch");
expect(resolveControlSizing({ compactLayout: false, touchScreen: false })).toBe("pointer");
});
it("gives a touch primary pointer its touch sizes at every width", () => {
it("gives a touch screen its touch sizes at every width", () => {
const sizes = { touch: 44, pointer: 32 };
// An iPad: touch-sized in the docked desktop layout too.
expect(bySizing(sizes, true)).toEqual({ xs: 44, md: 44 });
// A mouse- or trackpad-driven window, touch screen or not: touch-sized only once it narrows
// into the compact layout.
// A mouse-driven window: touch-sized only once it narrows into the compact layout.
expect(bySizing(sizes, false)).toEqual({ xs: 44, md: 32 });
});
it("keeps a device without a touch primary pointer on pointer sizes from md up", () => {
// The unit runtime has no touch primary pointer, which is the desktop that must not change.
it("keeps a device without a touch screen on pointer sizes from md up", () => {
// The unit runtime has no touch screen, which is the desktop that must not change.
expect(controlSizingForLayout(false)).toBe("pointer");
expect(controlSizingForLayout(true)).toBe("touch");
expect(CONTROL_HEIGHTS.md).toEqual({ xs: 44, md: 32 });
@@ -1,4 +1,4 @@
import { hasTouchPrimaryPointer } from "@/hooks/pointer-capabilities";
import { hasTouchScreen } from "@/hooks/pointer-capabilities";
// The sizing gate, apart from the control sizes so that low-level modules such as
// `constants/layout` can size by it without loading the theme. Import it through
@@ -14,32 +14,28 @@ export type ControlSizing = "touch" | "pointer";
export interface ControlSizingFacts {
/** The layout is below the `md` breakpoint. */
compactLayout: boolean;
/** Touch is the device's primary input; see `hasTouchPrimaryPointer`. */
touchPrimaryPointer: boolean;
/** The device has a touch screen; see `hasTouchScreen`. */
touchScreen: boolean;
}
/**
* The one sizing gate: touch-sized in the compact layout or where touch is the primary input,
* pointer-sized otherwise. An iPad keeps touch sizing with a trackpad attached; a laptop with a
* touch screen that its trackpad drives is pointer-sized.
* The one sizing gate: touch-sized in the compact layout or on any device with a touch screen,
* pointer-sized otherwise. A touch screen keeps touch sizing when a mouse or keyboard is attached.
*/
export function resolveControlSizing({
compactLayout,
touchPrimaryPointer,
touchScreen,
}: ControlSizingFacts): ControlSizing {
if (compactLayout || touchPrimaryPointer) return "touch";
if (compactLayout || touchScreen) return "touch";
return "pointer";
}
// Read once, so attaching a mouse or keyboard later never flips the sizing.
const DEVICE_HAS_TOUCH_PRIMARY_POINTER = hasTouchPrimaryPointer();
const DEVICE_HAS_TOUCH_SCREEN = hasTouchScreen();
/** The sizing on this device for a layout, for code that sizes outside a stylesheet. */
export function controlSizingForLayout(compactLayout: boolean): ControlSizing {
return resolveControlSizing({
compactLayout,
touchPrimaryPointer: DEVICE_HAS_TOUCH_PRIMARY_POINTER,
});
return resolveControlSizing({ compactLayout, touchScreen: DEVICE_HAS_TOUCH_SCREEN });
}
/** A Unistyles breakpoint value: one number in the compact layout, another from `md` up. */
@@ -55,11 +51,11 @@ export type SizingValue = Record<ControlSizing, number>;
*/
export function bySizing(
sizes: SizingValue,
touchPrimaryPointer: boolean = DEVICE_HAS_TOUCH_PRIMARY_POINTER,
touchScreen: boolean = DEVICE_HAS_TOUCH_SCREEN,
): LayoutValue {
return {
xs: sizes[resolveControlSizing({ compactLayout: true, touchPrimaryPointer })],
md: sizes[resolveControlSizing({ compactLayout: false, touchPrimaryPointer })],
xs: sizes[resolveControlSizing({ compactLayout: true, touchScreen })],
md: sizes[resolveControlSizing({ compactLayout: false, touchScreen })],
};
}
@@ -23,18 +23,10 @@ class FakeMediaQueryList {
}
}
function createFakeDisplay(initial: {
finePointer: boolean;
touchScreen: boolean;
touchPrimaryPointer?: boolean;
}) {
function createFakeDisplay(initial: { finePointer: boolean; touchScreen: boolean }) {
const queries = {
finePointer: new FakeMediaQueryList("(hover: hover) and (pointer: fine)", initial.finePointer),
touchScreen: new FakeMediaQueryList("(any-pointer: coarse)", initial.touchScreen),
touchPrimaryPointer: new FakeMediaQueryList(
"(pointer: coarse)",
initial.touchPrimaryPointer ?? false,
),
};
const matchMedia = (query: string) => {
const match = Object.values(queries).find((list) => list.media === query);
@@ -83,25 +75,3 @@ describe("pointer capabilities", () => {
});
});
});
describe("hasTouchPrimaryPointer", () => {
it("is false on a touch-screen laptop driven by its trackpad", () => {
const display = createFakeDisplay({ finePointer: true, touchScreen: true });
expect(createPointerCapabilitiesSource(display.matchMedia).hasTouchPrimaryPointer()).toBe(
false,
);
});
it("is true when the primary pointer is coarse", () => {
const display = createFakeDisplay({
finePointer: false,
touchScreen: true,
touchPrimaryPointer: true,
});
expect(createPointerCapabilitiesSource(display.matchMedia).hasTouchPrimaryPointer()).toBe(true);
});
it("is false without media queries", () => {
expect(createPointerCapabilitiesSource(null).hasTouchPrimaryPointer()).toBe(false);
});
});
+6 -12
View File
@@ -8,7 +8,6 @@ import { isWeb } from "@/constants/platform";
// (detachable keyboards, tablet mode, devtools touch emulation).
const FINE_POINTER_QUERY = "(hover: hover) and (pointer: fine)";
const TOUCH_SCREEN_QUERY = "(any-pointer: coarse)";
const TOUCH_PRIMARY_POINTER_QUERY = "(pointer: coarse)";
export interface PointerCapabilities {
/** A mouse-like pointer drives the UI. */
@@ -22,7 +21,6 @@ type MatchMedia = (query: string) => MediaQueryList;
export interface PointerCapabilitiesSource {
getSnapshot: () => PointerCapabilities;
subscribe: (onChange: () => void) => () => void;
hasTouchPrimaryPointer: () => boolean;
}
export function createPointerCapabilitiesSource(
@@ -30,11 +28,9 @@ export function createPointerCapabilitiesSource(
): PointerCapabilitiesSource {
const finePointerQuery = matchMedia?.(FINE_POINTER_QUERY) ?? null;
const touchScreenQuery = matchMedia?.(TOUCH_SCREEN_QUERY) ?? null;
const touchPrimaryPointerQuery = matchMedia?.(TOUCH_PRIMARY_POINTER_QUERY) ?? null;
let snapshot: PointerCapabilities = { finePointer: false, touchScreen: false };
return {
hasTouchPrimaryPointer: () => touchPrimaryPointerQuery?.matches ?? false,
getSnapshot() {
const finePointer = finePointerQuery?.matches ?? false;
const touchScreen = touchScreenQuery?.matches ?? false;
@@ -65,7 +61,6 @@ const NATIVE_POINTER_CAPABILITIES: PointerCapabilities = { finePointer: false, t
const nativeSource: PointerCapabilitiesSource = {
getSnapshot: () => NATIVE_POINTER_CAPABILITIES,
subscribe: () => () => {},
hasTouchPrimaryPointer: () => true,
};
const source = isWeb ? createPointerCapabilitiesSource(browserMatchMedia()) : nativeSource;
@@ -84,11 +79,10 @@ export function hasFinePointer(): boolean {
return source.getSnapshot().finePointer;
}
/**
* True when touch is the primary input, read at call time. iPadOS keeps touch primary with a
* trackpad attached; a laptop with a touch screen that its trackpad drives reports a fine primary
* pointer.
*/
export function hasTouchPrimaryPointer(): boolean {
return source.hasTouchPrimaryPointer();
/** Touch sizing remains enabled on hybrid browsers that report touch points. */
export function hasTouchScreen(): boolean {
return (
source.getSnapshot().touchScreen ||
(isWeb && typeof window !== "undefined" && window.navigator.maxTouchPoints > 0)
);
}
-1
View File
@@ -2017,7 +2017,6 @@ export const ar: TranslationResources = {
hostUnavailable: "مضيف التنزيل غير متاح.",
cancelled: "تم إلغاء التنزيل.",
failed: "فشل تنزيل الملف.",
httpFailed: "فشل تنزيل الملف (HTTP {{status}}).",
shareFile: "مشاركة الملف",
shareFileNamed: "مشاركة{{fileName}}",
},
-1
View File
@@ -2045,7 +2045,6 @@ export const en = {
hostUnavailable: "Download host is unavailable.",
cancelled: "Download was cancelled.",
failed: "Failed to download file.",
httpFailed: "Failed to download file (HTTP {{status}}).",
shareFile: "Share file",
shareFileNamed: "Share {{fileName}}",
},
-1
View File
@@ -2066,7 +2066,6 @@ export const es: TranslationResources = {
hostUnavailable: "El host de descarga no está disponible.",
cancelled: "La descarga fue cancelada.",
failed: "No se pudo descargar el archivo.",
httpFailed: "No se pudo descargar el archivo (HTTP {{status}}).",
shareFile: "compartir archivo",
shareFileNamed: "Compartir{{fileName}}",
},
-1
View File
@@ -2065,7 +2065,6 @@ export const fr: TranslationResources = {
hostUnavailable: "L’hôte de téléchargement est indisponible.",
cancelled: "Téléchargement annulé.",
failed: "Impossible de télécharger le fichier.",
httpFailed: "Impossible de télécharger le fichier (HTTP {{status}}).",
shareFile: "Partager le fichier",
shareFileNamed: "Partager {{fileName}}",
},
-1
View File
@@ -2038,7 +2038,6 @@ export const ja: TranslationResources = {
hostUnavailable: "ダウンロードホストが利用できません。",
cancelled: "ダウンロードがキャンセルされました。",
failed: "ファイルのダウンロードに失敗しました。",
httpFailed: "ファイルのダウンロードに失敗しました (HTTP {{status}}).",
shareFile: "ファイルを共有",
shareFileNamed: "{{fileName}}を共有",
},
-1
View File
@@ -2028,7 +2028,6 @@ export const ko: TranslationResources = {
hostUnavailable: "다운로드 호스트를 사용할 수 없습니다.",
cancelled: "다운로드가 취소되었습니다.",
failed: "파일을 다운로드하지 못했습니다.",
httpFailed: "파일을 다운로드하지 못했습니다 (HTTP {{status}}).",
shareFile: "파일 공유",
shareFileNamed: "{{fileName}} 공유",
},
-1
View File
@@ -2051,7 +2051,6 @@ export const ptBR: TranslationResources = {
hostUnavailable: "Host de download indisponível.",
cancelled: "Download cancelado.",
failed: "Falha ao baixar arquivo.",
httpFailed: "Falha ao baixar arquivo (HTTP {{status}}).",
shareFile: "Compartilhar arquivo",
shareFileNamed: "Compartilhar {{fileName}}",
},
-1
View File
@@ -2051,7 +2051,6 @@ export const ru: TranslationResources = {
hostUnavailable: "Хост загрузки недоступен.",
cancelled: "Загрузка отменена.",
failed: "Не удалось загрузить файл.",
httpFailed: "Не удалось загрузить файл (HTTP {{status}}).",
shareFile: "Поделиться файлом",
shareFileNamed: "Поделиться {{fileName}}",
},
-1
View File
@@ -1994,7 +1994,6 @@ export const zhCN: TranslationResources = {
hostUnavailable: "下载 Host 不可用。",
cancelled: "下载已取消。",
failed: "下载文件失败。",
httpFailed: "下载文件失败 (HTTP {{status}}).",
shareFile: "共享文件",
shareFileNamed: "共享 {{fileName}}",
},
@@ -21,7 +21,8 @@ import {
import { useLocalDaemonServerId } from "@/hooks/use-is-local-daemon";
import { PairDeviceModal } from "@/desktop/components/pair-device-modal";
import { buildSettingsHostSectionRoute } from "@/utils/host-routes";
import { WINDOW_CONTENT_DATASET } from "@/components/desktop/titlebar-drag-region";
const WINDOW_CONTENT_DATASET = { "window-content": "" };
export function OpenProjectScreen() {
const { t } = useTranslation();
@@ -90,7 +90,6 @@ interface StartInput {
token?: ReturnType<typeof createTokenRequest>;
reader?: ReturnType<typeof createFileReader>;
saver?: ReturnType<typeof createFileSaver>;
fetchFile?: typeof fetch;
}
async function startDownload(input: StartInput): Promise<Download | undefined> {
@@ -109,7 +108,6 @@ async function startDownload(input: StartInput): Promise<Download | undefined> {
requestFileDownloadToken: token.request,
readFile: reader.read,
saveFile: saver.save,
fetchFile: input.fetchFile ?? (async () => new Response(FILE_BYTES)),
});
const { activeDownloadId, downloads } = useDownloadStore.getState();
return activeDownloadId ? downloads.get(activeDownloadId) : undefined;
@@ -205,57 +203,6 @@ describe("download store transport selection", () => {
expect(saver.savedFiles).toEqual([]);
});
it("fails with the HTTP status when a proxy in front of the host rejects the download", async () => {
const requests: Array<RequestInit | undefined> = [];
const download = await startDownload({
profile: profileWith([localTcpConnection]),
activeConnectionId: localTcpConnection.id,
fetchFile: async (_url, init) => {
requests.push(init);
return new Response("<h1>401 Authorization Required</h1>", {
status: 401,
headers: { "WWW-Authenticate": 'Basic realm="Paseo"' },
});
},
});
expect(download).toMatchObject({
status: "error",
message: i18n.t("downloads.httpFailed", { status: 401 }),
});
expect(requests).toEqual([{ credentials: "include", redirect: "error" }]);
});
it("fails with a readable message when the download request cannot reach the host", async () => {
const download = await startDownload({
profile: profileWith([localTcpConnection]),
activeConnectionId: localTcpConnection.id,
fetchFile: async () => {
throw new TypeError("Failed to fetch");
},
});
expect(download).toMatchObject({ status: "error", message: i18n.t("downloads.failed") });
});
it("fails with a readable message when the connection drops while the file is downloading", async () => {
const saver = createFileSaver();
const download = await startDownload({
profile: profileWith([localTcpConnection]),
activeConnectionId: localTcpConnection.id,
fetchFile: async () =>
new Response(
new ReadableStream({
start: (controller) => controller.error(new TypeError("network error")),
}),
),
saver,
});
expect(download).toMatchObject({ status: "error", message: i18n.t("downloads.failed") });
expect(saver.savedFiles).toEqual([]);
});
it("fails the download and saves nothing when the session read fails", async () => {
const reader = createFileReader(async () => {
throw new Error("Connection lost");
+34 -39
View File
@@ -4,6 +4,7 @@ import * as LegacyFileSystem from "expo-file-system/legacy";
import * as Sharing from "expo-sharing";
import type { HostProfile } from "@/types/host-connection";
import { buildDaemonWebSocketUrl } from "@/utils/daemon-endpoints";
import { openExternalUrl } from "@/utils/open-external-url";
import { isWeb } from "@/constants/platform";
import { i18n } from "@/i18n/i18next";
@@ -58,7 +59,6 @@ interface DownloadState {
/** Reads the whole file over the session socket; used when no direct HTTP endpoint is active. */
readFile: (path: string, maxBytes: number) => Promise<{ bytes: Uint8Array; size: number }>;
saveFile?: typeof saveDownloadedBytes;
fetchFile?: typeof fetch;
}) => Promise<void>;
updateProgress: (id: string, progress: DownloadProgress) => void;
@@ -86,7 +86,6 @@ export const useDownloadStore = create<DownloadState>()((set, get) => ({
requestFileDownloadToken,
readFile,
saveFile = saveDownloadedBytes,
fetchFile = fetch,
}) => {
const id = generateDownloadId();
const download: Download = {
@@ -145,11 +144,14 @@ export const useDownloadStore = create<DownloadState>()((set, get) => ({
throw new Error(i18n.t("downloads.hostUnavailable"));
}
const downloadUrl = buildDownloadUrl(downloadTarget.baseUrl, tokenResponse.token);
const downloadUrl = buildDownloadUrl(
downloadTarget.baseUrl,
tokenResponse.token,
isWeb ? downloadTarget.authCredentials : null,
);
if (isWeb) {
const file = await fetchDownload(fetchFile, downloadUrl);
saveBrowserFile(file, resolvedFileName);
triggerBrowserDownload(downloadUrl, resolvedFileName);
get().completeDownload(id);
return;
}
@@ -196,6 +198,11 @@ export const useDownloadStore = create<DownloadState>()((set, get) => ({
await shareSavedFile(result.uri, tokenResponse.mimeType, resolvedFileName);
} catch (error) {
const message = error instanceof Error ? error.message : i18n.t("downloads.failed");
if (isWeb) {
console.warn("[DownloadStore] Download failed:", message);
get().failDownload(id, message);
return;
}
get().failDownload(id, message);
}
},
@@ -276,6 +283,7 @@ function findMostRecentDownloadId(downloads: Map<string, Download>): string | nu
interface DownloadTarget {
baseUrl: string | null;
authHeader: string | null;
authCredentials: { username: string; password: string } | null;
}
/**
@@ -298,7 +306,7 @@ function resolveDaemonDownloadTarget(
buildDaemonWebSocketUrl(connection.endpoint, { useTls: connection.useTls ?? false }),
);
} catch {
return { baseUrl: null, authHeader: null };
return { baseUrl: null, authHeader: null, authCredentials: null };
}
if (parsed.protocol === "ws:") {
@@ -324,41 +332,23 @@ function resolveDaemonDownloadTarget(
? `Basic ${btoa(`${authCredentials.username}:${authCredentials.password}`)}`
: null;
return { baseUrl, authHeader };
return { baseUrl, authHeader, authCredentials };
}
function buildDownloadUrl(baseUrl: string, token: string): string {
function buildDownloadUrl(
baseUrl: string,
token: string,
authCredentials: { username: string; password: string } | null,
): string {
const url = new URL("/api/files/download", baseUrl);
url.searchParams.set("token", token);
if (authCredentials) {
url.username = authCredentials.username;
url.password = authCredentials.password;
}
return url.toString();
}
/**
* Fetches the file instead of navigating to it. The app runs on another origin than the host
* (paseo://app on desktop), so a link to the download URL navigates the whole window, and any
* response that is not the file (a proxy's 401 page, a 404) replaces the app.
*/
async function fetchDownload(fetchFile: typeof fetch, url: string): Promise<Blob> {
let response: Response;
try {
// Send the same cookies the host's WebSocket handshake sends, so a proxy in front of the
// host lets the download through. Refuse redirects: a proxy that redirects to a login page
// would otherwise be saved as the file.
response = await fetchFile(url, { credentials: "include", redirect: "error" });
} catch {
throw new Error(i18n.t("downloads.failed"));
}
if (!response.ok) {
throw new Error(i18n.t("downloads.httpFailed", { status: response.status }));
}
try {
// The body streams after the headers, so the connection can still drop here.
return await response.blob();
} catch {
throw new Error(i18n.t("downloads.failed"));
}
}
/**
* Saves bytes read over the session. Web and Electron hand them to the browser's download
* manager and return `null`; native writes the file and returns its URI for the share sheet.
@@ -371,7 +361,12 @@ async function saveDownloadedBytes({
if (isWeb) {
const buffer = new ArrayBuffer(bytes.byteLength);
new Uint8Array(buffer).set(bytes);
saveBrowserFile(new Blob([buffer], { type: mimeType ?? "application/octet-stream" }), fileName);
const url = URL.createObjectURL(
new Blob([buffer], { type: mimeType ?? "application/octet-stream" }),
);
triggerBrowserDownload(url, fileName);
// The browser may still be reading the blob while its save prompt is open.
setTimeout(() => URL.revokeObjectURL(url), 60_000);
return null;
}
// Resolve and write in one tick so two downloads of the same name cannot pick the same path.
@@ -395,12 +390,14 @@ async function shareSavedFile(
}
}
function saveBrowserFile(file: Blob, fileName: string) {
function triggerBrowserDownload(url: string, fileName: string) {
if (typeof document === "undefined") {
if (typeof window !== "undefined") {
void openExternalUrl(url);
}
return;
}
const url = URL.createObjectURL(file);
const link = document.createElement("a");
link.href = url;
link.download = fileName;
@@ -408,8 +405,6 @@ function saveBrowserFile(file: Blob, fileName: string) {
document.body.appendChild(link);
link.click();
link.remove();
// The browser may still be reading the blob while its save prompt is open.
setTimeout(() => URL.revokeObjectURL(url), 60_000);
}
function resolveDownloadTargetFile(fileName: string): FSFile {
+4 -4
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/cli",
"version": "0.16.1",
"version": "0.16.0",
"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.0",
"@getpaseo/protocol": "0.16.0",
"@getpaseo/server": "0.16.0",
"chalk": "^5.3.0",
"commander": "^12.0.0",
"mime-types": "^2.1.35",
+3 -3
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/client",
"version": "0.16.1",
"version": "0.16.0",
"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.0",
"@getpaseo/relay": "0.16.0",
"ws": "^8.20.0",
"zod": "^4.4.3"
},
@@ -1,64 +0,0 @@
import type { Page } from "@playwright/test";
import { test, expect } from "../../app/e2e/support/fixtures";
import { gotoAppShell } from "../../app/e2e/support/helpers/app";
// Windows and Linux draw their window controls top-right, so the desktop sidebar has no
// chrome row of its own. Its window-drag surface is the strip above the navigation rows.
const CUSTOM_CHROME_HOSTS = [
{ platform: "linux", windowChromeMode: "custom-linux" },
{ platform: "win32", windowChromeMode: "custom-windows" },
] as const;
async function installDesktopHost(
page: Page,
host: (typeof CUSTOM_CHROME_HOSTS)[number],
): Promise<void> {
await page.addInitScript((desktopHost) => {
window.paseoDesktop = {
...desktopHost,
events: { on: () => () => {} },
invoke: async (command: string) => {
if (command === "get_desktop_settings") {
return {
releaseChannel: "stable",
daemon: { manageBuiltInDaemon: true, keepRunningAfterQuit: true },
};
}
return null;
},
};
}, host);
}
async function sidebarDragGeometry(page: Page) {
const navScroll = page.locator('[data-testid="sidebar-nav-scroll"]:visible').first();
await expect(navScroll).toBeVisible();
return navScroll.evaluate((node) => {
const nav = node.getBoundingClientRect();
const dragRegions = [];
for (const element of document.querySelectorAll<HTMLElement>("*")) {
if (getComputedStyle(element).getPropertyValue("-webkit-app-region") !== "drag") continue;
const rect = element.getBoundingClientRect();
const overSidebar = rect.left < nav.right && rect.right > nav.left;
if (overSidebar && rect.height > 0) dragRegions.push({ top: rect.top, bottom: rect.bottom });
}
return { navTop: nav.top, navBottom: nav.bottom, dragRegions };
});
}
for (const host of CUSTOM_CHROME_HOSTS) {
test.describe(`Desktop sidebar on ${host.platform}`, () => {
test.use({ viewport: { width: 1280, height: 480 } });
test("keeps a window drag strip above the scrolling navigation", async ({ page }) => {
await installDesktopHost(page, host);
await gotoAppShell(page);
const geometry = await sidebarDragGeometry(page);
expect(geometry.dragRegions).not.toEqual([]);
for (const region of geometry.dragRegions) {
expect(region.bottom).toBeLessThanOrEqual(geometry.navTop + 1);
}
});
});
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/desktop",
"version": "0.16.1",
"version": "0.16.0",
"private": true,
"description": "Paseo desktop app (Electron wrapper)",
"homepage": "https://paseo.sh",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/expo-two-way-audio",
"version": "0.16.1",
"version": "0.16.0",
"description": "Native module for two way audio streaming",
"keywords": [
"ExpoTwoWayAudio",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/highlight",
"version": "0.16.1",
"version": "0.16.0",
"license": "Apache-2.0",
"files": [
"dist",
+5 -5
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/plugin",
"version": "0.16.1",
"version": "0.16.0",
"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.0",
"@getpaseo/protocol": "0.16.0",
"@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.0",
"@getpaseo/protocol": "0.16.0",
"react": ">=19.1.0 <20",
"react-native": ">=0.81.5",
"zod": "^4.4.3"
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/protocol",
"version": "0.16.1",
"version": "0.16.0",
"description": "Paseo shared protocol schemas and wire types",
"license": "Apache-2.0",
"files": [
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/relay",
"version": "0.16.1",
"version": "0.16.0",
"description": "Paseo relay for bridging daemon and client connections",
"license": "Apache-2.0",
"files": [
+7 -7
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/server",
"version": "0.16.1",
"version": "0.16.0",
"description": "Paseo backend server",
"license": "Apache-2.0",
"files": [
@@ -107,13 +107,13 @@
},
"dependencies": {
"@agentclientprotocol/sdk": "^0.17.1",
"@anthropic-ai/claude-agent-sdk": "0.3.326",
"@anthropic-ai/claude-agent-sdk": "0.3.246",
"@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.0",
"@getpaseo/highlight": "0.16.0",
"@getpaseo/plugin": "0.16.0",
"@getpaseo/protocol": "0.16.0",
"@getpaseo/relay": "0.16.0",
"@isaacs/ttlcache": "^2.1.4",
"@modelcontextprotocol/sdk": "1.29.0",
"@opencode-ai/sdk": "1.14.46",
@@ -14,19 +14,18 @@ const BASE_RECORD: StoredAgentRecord = {
config: null,
};
const ARCHIVE = {
archivedAt: "2025-01-03T00:00:00.000Z",
updatedAt: "2025-01-03T00:00:00.000Z",
};
test("archives a stored agent without changing terminal statuses", () => {
const statuses: Array<StoredAgentRecord["lastStatus"]> = ["idle", "error", "closed"];
for (const status of statuses) {
const archived = buildArchivedAgentRecord({ ...BASE_RECORD, lastStatus: status }, ARCHIVE);
const archived = buildArchivedAgentRecord(
{ ...BASE_RECORD, lastStatus: status },
{ archivedAt: "2025-01-03T00:00:00.000Z" },
);
expect(archived.lastStatus).toBe(status);
expect(archived.archivedAt).toBe("2025-01-03T00:00:00.000Z");
expect(archived.updatedAt).toBe(BASE_RECORD.updatedAt);
}
});
@@ -34,7 +33,10 @@ test("archives busy stored agents as idle", () => {
const statuses: Array<StoredAgentRecord["lastStatus"]> = ["initializing", "running"];
for (const status of statuses) {
const archived = buildArchivedAgentRecord({ ...BASE_RECORD, lastStatus: status }, ARCHIVE);
const archived = buildArchivedAgentRecord(
{ ...BASE_RECORD, lastStatus: status },
{ archivedAt: "2025-01-03T00:00:00.000Z" },
);
expect(archived.lastStatus).toBe("idle");
}
@@ -48,7 +50,7 @@ test("clears persisted attention when archiving", () => {
attentionReason: "finished",
attentionTimestamp: "2025-01-02T12:00:00.000Z",
},
ARCHIVE,
{ archivedAt: "2025-01-03T00:00:00.000Z" },
);
expect(archived).toMatchObject({
@@ -58,19 +60,11 @@ test("clears persisted attention when archiving", () => {
});
});
test("moves updatedAt to the archive time", () => {
const archived = buildArchivedAgentRecord(BASE_RECORD, ARCHIVE);
test("can stamp updatedAt to the archive timestamp", () => {
const archived = buildArchivedAgentRecord(BASE_RECORD, {
archivedAt: "2025-01-03T00:00:00.000Z",
updatedAt: "2025-01-03T00:00:00.000Z",
});
expect(archived.updatedAt).toBe("2025-01-03T00:00:00.000Z");
});
test("keeps a later updatedAt when the archive time is earlier", () => {
// Putting an original archive back after a failed unarchive must not move updatedAt backwards.
const archived = buildArchivedAgentRecord(
{ ...BASE_RECORD, updatedAt: "2025-01-04T00:00:00.000Z" },
ARCHIVE,
);
expect(archived.archivedAt).toBe("2025-01-03T00:00:00.000Z");
expect(archived.updatedAt).toBe("2025-01-04T00:00:00.000Z");
});
@@ -3,19 +3,19 @@ import type { StoredAgentRecord } from "./agent-storage.js";
export type ArchivedStoredAgentRecord = StoredAgentRecord & { archivedAt: string };
interface BuildArchivedAgentRecordOptions {
archivedAt: string;
/** When this archive happened. Re-archiving keeps the original archivedAt but still records it. */
updatedAt: string;
archivedAt?: string;
updatedAt?: string;
}
export function buildArchivedAgentRecord(
record: StoredAgentRecord,
options: BuildArchivedAgentRecordOptions,
options?: BuildArchivedAgentRecordOptions,
): ArchivedStoredAgentRecord {
const archivedAt = options?.archivedAt ?? new Date().toISOString();
return {
...record,
archivedAt: options.archivedAt,
updatedAt: latestTimestamp(record.updatedAt, options.updatedAt),
archivedAt,
updatedAt: options?.updatedAt ?? record.updatedAt,
lastStatus: normalizeArchivedStatus(record.lastStatus),
requiresAttention: false,
attentionReason: null,
@@ -23,13 +23,6 @@ export function buildArchivedAgentRecord(
};
}
// Archiving is the agent's latest change. An earlier archive time (an original archive put back
// after a failed unarchive) keeps the newer updatedAt, since clients drop an agent update that is
// older than the one they hold.
function latestTimestamp(current: string, archiveTime: string): string {
return Date.parse(archiveTime) > Date.parse(current) ? archiveTime : current;
}
function normalizeArchivedStatus(
status: StoredAgentRecord["lastStatus"],
): StoredAgentRecord["lastStatus"] {
@@ -20,10 +20,6 @@ import {
type ManagedAgent,
} from "./agent-manager.js";
import { AgentStorage, parseStoredAgentRecord } from "./agent-storage.js";
import { AgentTurnStartCanceledError } from "./agent-sdk-types.js";
import { ForegroundPromptStart } from "./agent-run-state.js";
import { CodexAppServerAgentSession } from "./providers/codex-app-server-agent.js";
import { createFakeCodexAppServer } from "./providers/codex/test-utils/fake-app-server.js";
import { InMemoryAgentTimelineStore } from "./agent-timeline-store.js";
import { limitAgentTimelineItemContent } from "./agent-timeline-content.js";
import { buildStoredAgentPayload, toAgentPayload } from "./agent-projections.js";
@@ -1214,7 +1210,7 @@ test("starts its own turn when the previous turn fails to start under a steer se
);
startHeld.resolve();
await expect(second).resolves.toMatchObject({ disposition: "turn_started" });
await expect(second).resolves.toEqual({ disposition: "turn_started" });
await vi.waitFor(() => expect(session.startPrompts).toEqual(["FIRST", "SECOND"]));
expect(session.interruptCount).toBe(0);
} finally {
@@ -6498,114 +6494,6 @@ test("archiveSnapshot dispatches archived state for stored-only agents", async (
expect(last.lifecycle).toBe("closed");
});
test("archiveSnapshot moves a stored-only agent's updatedAt to its archive time, as a live archive does", async () => {
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-archive-snapshot-updated-at-"));
const storage = new AgentStorage(join(workdir, "agents"), logger);
const manager = new AgentManager({
clients: { codex: new TestAgentClient() },
registry: storage,
logger,
});
const created = await manager.createAgent(
{ provider: "codex", cwd: workdir, title: "Stored archive updatedAt" },
undefined,
{ workspaceId: undefined },
);
await manager.closeAgent(created.id);
const before = await storage.get(created.id);
expect(before?.updatedAt).toEqual(expect.any(String));
// Later than anything the agent did: lists sorted by updated_at put it first, as they do
// for an agent archived while loaded.
const archivedAt = new Date(Date.parse(before!.updatedAt) + 60_000).toISOString();
const archived = await manager.archiveSnapshot(created.id, archivedAt);
expect(archived.updatedAt).toBe(archivedAt);
expect((await storage.get(created.id))?.updatedAt).toBe(archivedAt);
});
test("archiveSnapshot restoring an earlier archive time keeps updatedAt at the unarchive", async () => {
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-archive-snapshot-restore-"));
const storage = new AgentStorage(join(workdir, "agents"), logger);
const manager = new AgentManager({
clients: { codex: new TestAgentClient() },
registry: storage,
logger,
});
const created = await manager.createAgent(
{ provider: "codex", cwd: workdir, title: "Restore archive updatedAt" },
undefined,
{ workspaceId: undefined },
);
await manager.closeAgent(created.id);
const originalArchivedAt = (await manager.archiveSnapshot(created.id, new Date().toISOString()))
.archivedAt!;
await new Promise((resolve) => setTimeout(resolve, 5));
await manager.unarchiveSnapshot(created.id);
const unarchivedAt = (await storage.get(created.id))!.updatedAt;
const events: ManagedAgent[] = [];
manager.subscribe(
(event) => {
if (event.type === "agent_state" && event.agent.id === created.id) {
events.push(event.agent);
}
},
{ agentId: created.id, replayState: false },
);
// A send that could not load the agent puts its original archive back.
await manager.archiveSnapshot(created.id, originalArchivedAt);
// Clients keep the newer of two updates, so an older updatedAt would leave them showing it active.
const stored = await storage.get(created.id);
expect(stored?.archivedAt).toBe(originalArchivedAt);
expect(stored?.updatedAt).toBe(unarchivedAt);
expect(events.at(-1)?.updatedAt.toISOString()).toBe(unarchivedAt);
});
test("archiveSnapshot restoring an earlier archive time on a loaded agent keeps updatedAt at the unarchive", async () => {
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-archive-snapshot-restore-loaded-"));
const storage = new AgentStorage(join(workdir, "agents"), logger);
const manager = new AgentManager({
clients: { codex: new TestAgentClient() },
registry: storage,
logger,
});
const created = await manager.createAgent(
{ provider: "codex", cwd: workdir, title: "Restore loaded archive updatedAt" },
undefined,
{ workspaceId: undefined },
);
const { archivedAt: originalArchivedAt } = await manager.archiveAgent(created.id);
await new Promise((resolve) => setTimeout(resolve, 5));
await manager.unarchiveSnapshot(created.id);
const unarchivedAt = Date.parse((await storage.get(created.id))!.updatedAt);
// The send resumed the agent before a later loading step failed, so it is still loaded.
await ensureAgentLoaded(created.id, { agentManager: manager, agentStorage: storage, logger });
expect(manager.getAgent(created.id)).not.toBeNull();
const events: ManagedAgent[] = [];
manager.subscribe(
(event) => {
if (event.type === "agent_state" && event.agent.id === created.id) {
events.push(event.agent);
}
},
{ agentId: created.id, replayState: false },
);
await manager.archiveSnapshot(created.id, originalArchivedAt);
const stored = await storage.get(created.id);
expect(stored?.archivedAt).toBe(originalArchivedAt);
expect(Date.parse(stored!.updatedAt)).toBeGreaterThanOrEqual(unarchivedAt);
expect(events.at(-1)?.updatedAt.getTime()).toBeGreaterThanOrEqual(unarchivedAt);
});
test("markAgentUnread restores error attention on a read errored agent", async () => {
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-mark-unread-error-"));
const storage = new AgentStorage(join(workdir, "agents"), logger);
@@ -9753,464 +9641,6 @@ test("streamAgent clears pending run when startTurn fails before a turn id exist
);
});
test("canceling a pending Codex start settles as canceled without accepting its prompt", async () => {
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-codex-cold-cancel-"));
const threadLoaded = deferred<{ data: string[] }>();
const appServer = createFakeCodexAppServer({ "thread/loaded/list": () => threadLoaded.promise });
class ColdStartClient extends TestAgentClient {
override async createSession(config: AgentSessionConfig): Promise<AgentSession> {
return new CodexAppServerAgentSession(config, null, logger, async () => appServer.child);
}
}
const manager = new AgentManager({
clients: { codex: new ColdStartClient() },
registry: new AgentStorage(join(workdir, "agents"), logger),
logger,
});
const events: AgentStreamEvent[] = [];
manager.subscribe((event) => {
if (event.type === "agent_stream") events.push(event.event);
});
try {
const agent = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, {
workspaceId: undefined,
});
// Drain the stream: a fresh Codex agent has no session handle for runAgent before its first turn.
const senderStart = new ForegroundPromptStart(agent.id);
const firstRun = drainAsyncGenerator(
manager.streamAgent(
agent.id,
"Canceled prompt",
{ clientMessageId: "canceled-prompt" },
senderStart,
),
);
void firstRun.catch(() => undefined);
await appServer.waitForRequest("thread/loaded/list");
const senderRejection = expect(senderStart.started).rejects.toThrow(
"its prompt was not delivered",
);
const cancel = manager.cancelAgentRun(agent.id);
await new Promise((resolve) => setTimeout(resolve, 0));
threadLoaded.resolve({ data: ["thread-1"] });
await expect(cancel).resolves.toEqual({ status: "settled" });
await expect(firstRun).resolves.toBeUndefined();
await senderRejection;
expect(manager.getAgent(agent.id)).toMatchObject({ lifecycle: "idle", lastError: undefined });
expect(manager.hasInFlightRun(agent.id)).toBe(false);
expect(events.map((event) => event.type)).toEqual(["timeline", "turn_canceled"]);
// The canceled attempt stays in history like a rejected one, without being delivered.
expect(manager.getTimeline(agent.id)).toEqual([
{
type: "user_message",
text: "Canceled prompt",
clientMessageId: "canceled-prompt",
messageId: "canceled-prompt",
},
]);
expect(appServer.requests().some((request) => request.method === "turn/start")).toBe(false);
const nextRun = manager.runAgent(agent.id, "Next prompt", { clientMessageId: "next-prompt" });
await appServer.waitForRequest("turn/start");
appServer.startsTurn({ threadId: "thread-1", turnId: "next-turn" });
appServer.completeTurn();
await expect(nextRun).resolves.toMatchObject({ canceled: false });
appServer.assertNoErrors();
} finally {
threadLoaded.resolve({ data: ["thread-1"] });
manager.prepareForShutdown();
await Promise.all(manager.listAgents().map((agent) => manager.closeAgent(agent.id)));
await manager.flushForShutdown();
rmSync(workdir, { recursive: true, force: true });
}
});
test("stopping a Codex replacement of a stalled start clears replacement activity", async () => {
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-codex-replacement-cancel-"));
const firstLoaded = deferred<{ data: string[] }>();
const firstInterruptRequested = deferred<void>();
const replacementLoaded = deferred<{ data: string[] }>();
const replacementEntered = deferred<void>();
let loadCount = 0;
const appServer = createFakeCodexAppServer({
"thread/loaded/list": () => {
loadCount += 1;
if (loadCount === 1) return firstLoaded.promise;
replacementEntered.resolve();
return replacementLoaded.promise;
},
});
class ColdStartSession extends CodexAppServerAgentSession {
override async interrupt(): Promise<void> {
const interruption = super.interrupt();
firstInterruptRequested.resolve();
await interruption;
}
}
class ColdStartClient extends TestAgentClient {
override async createSession(config: AgentSessionConfig): Promise<AgentSession> {
return new ColdStartSession(config, null, logger, async () => appServer.child);
}
}
const manager = new AgentManager({
clients: { codex: new ColdStartClient() },
registry: new AgentStorage(join(workdir, "agents"), logger),
logger,
rescueTimeouts: { interruptSessionMs: 10 },
});
try {
const agent = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, {
workspaceId: undefined,
});
const firstRun = drainAsyncGenerator(manager.streamAgent(agent.id, "Original prompt"));
await appServer.waitForRequest("thread/loaded/list");
const replacement = manager.replaceAgentRun(agent.id, "Replacement prompt");
await firstInterruptRequested.promise;
firstLoaded.resolve({ data: ["thread-1"] });
const replacementStream = await replacement;
await expect(firstRun).resolves.toBeUndefined();
expect(manager.getAgent(agent.id)?.lifecycle).toBe("running");
const replacementEvent = replacementStream.next();
await replacementEntered.promise;
const cancel = manager.cancelAgentRun(agent.id);
await new Promise((resolve) => setTimeout(resolve, 0));
replacementLoaded.resolve({ data: ["thread-1"] });
await expect(cancel).resolves.toEqual({ status: "settled" });
await expect(replacementEvent).resolves.toMatchObject({
value: { type: "turn_canceled" },
});
await expect(replacementStream.next()).resolves.toMatchObject({ done: true });
expect(manager.hasInFlightRun(agent.id)).toBe(false);
expect(manager.getAgent(agent.id)?.lifecycle).toBe("idle");
expect(appServer.requests().some((request) => request.method === "turn/start")).toBe(false);
appServer.assertNoErrors();
} finally {
firstLoaded.resolve({ data: ["thread-1"] });
replacementLoaded.resolve({ data: ["thread-1"] });
manager.prepareForShutdown();
await Promise.all(manager.listAgents().map((agent) => manager.closeAgent(agent.id)));
await manager.flushForShutdown();
rmSync(workdir, { recursive: true, force: true });
}
});
test("a stalled Codex start canceled by its replacement rejects its sender's start wait", async () => {
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-codex-replaced-start-wait-"));
const firstLoaded = deferred<{ data: string[] }>();
const firstInterruptRequested = deferred<void>();
let loadCount = 0;
const appServer = createFakeCodexAppServer({
"thread/loaded/list": () => {
loadCount += 1;
return loadCount === 1 ? firstLoaded.promise : { data: ["thread-1"] };
},
});
class ColdStartSession extends CodexAppServerAgentSession {
override async interrupt(): Promise<void> {
const interruption = super.interrupt();
firstInterruptRequested.resolve();
await interruption;
}
}
class ColdStartClient extends TestAgentClient {
override async createSession(config: AgentSessionConfig): Promise<AgentSession> {
return new ColdStartSession(config, null, logger, async () => appServer.child);
}
}
const manager = new AgentManager({
clients: { codex: new ColdStartClient() },
registry: new AgentStorage(join(workdir, "agents"), logger),
logger,
rescueTimeouts: { interruptSessionMs: 10 },
});
try {
const agent = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, {
workspaceId: undefined,
});
const firstStart = new ForegroundPromptStart(agent.id);
const secondStart = new ForegroundPromptStart(agent.id);
const firstRun = drainAsyncGenerator(
manager.streamAgent(agent.id, "First prompt", undefined, firstStart),
);
await appServer.waitForRequest("thread/loaded/list");
const firstWait = firstStart.started;
const replacement = manager.replaceAgentRun(agent.id, "Second prompt", undefined, secondStart);
await firstInterruptRequested.promise;
firstLoaded.resolve({ data: ["thread-1"] });
const replacementStream = await replacement;
await expect(firstRun).resolves.toBeUndefined();
const secondWait = secondStart.started;
const replacementDrained = drainAsyncGenerator(replacementStream);
await appServer.waitForRequest("turn/start");
appServer.startsTurn({ threadId: "thread-1", turnId: "second-turn" });
await expect(secondWait).resolves.toBeUndefined();
await expect(firstWait).rejects.toThrow("its prompt was not delivered");
appServer.completeTurn();
await replacementDrained;
expect(appServer.requests().filter((request) => request.method === "turn/start")).toEqual([
expect.objectContaining({
params: expect.objectContaining({
input: [expect.objectContaining({ text: "Second prompt" })],
}),
}),
]);
appServer.assertNoErrors();
} finally {
firstLoaded.resolve({ data: ["thread-1"] });
manager.prepareForShutdown();
await Promise.all(manager.listAgents().map((agent) => manager.closeAgent(agent.id)));
await manager.flushForShutdown();
rmSync(workdir, { recursive: true, force: true });
}
});
test("a sender's start wait follows its prompt across a stale-session retry", async () => {
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-stale-start-wait-"));
const releaseStart = deferred<void>();
class StaleStartSession extends TestAgentSession {
override async startTurn(): Promise<{ turnId: string }> {
await releaseStart.promise;
throw new StaleProviderSessionError("stale-bridge");
}
}
class StaleStartClient extends ResumeTrackingTestAgentClient {
override async createSession(config: AgentSessionConfig): Promise<AgentSession> {
return new StaleStartSession(config);
}
}
const client = new StaleStartClient();
const storage = new AgentStorage(join(workdir, "agents"), logger);
const manager = new AgentManager({ clients: { codex: client }, registry: storage, logger });
const startedTurns: AgentStreamEvent[] = [];
manager.subscribe((event) => {
if (event.type === "agent_stream" && event.event.type === "turn_started") {
startedTurns.push(event.event);
}
});
try {
const agent = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, {
workspaceId: undefined,
});
const senderWait = dispatchStarted(
await startAgentRun(manager, agent.id, "Retry this prompt", logger, {
runOptions: { clientMessageId: "stale-start-wait" },
}),
);
releaseStart.resolve();
await client.waitForRetryStart();
await manager.waitForAgentEvent(agent.id);
expect(client.resumeOverrides).toHaveLength(1);
expect(startedTurns).toHaveLength(1);
expect(manager.getTimeline(agent.id).filter((item) => item.type === "user_message")).toEqual([
expect.objectContaining({ text: "Retry this prompt", clientMessageId: "stale-start-wait" }),
]);
await expect(senderWait).resolves.toBeUndefined();
} finally {
releaseStart.resolve();
manager.prepareForShutdown();
await Promise.all(manager.listAgents().map((agent) => manager.closeAgent(agent.id)));
await manager.flushForShutdown();
rmSync(workdir, { recursive: true, force: true });
}
});
test("a sender's start wait follows its prompt when the session is stale before the wait begins", async () => {
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-immediate-stale-start-"));
class StaleStartSession extends TestAgentSession {
override async startTurn(): Promise<{ turnId: string }> {
throw new StaleProviderSessionError("stale-bridge");
}
}
class StaleStartClient extends ResumeTrackingTestAgentClient {
override async createSession(config: AgentSessionConfig): Promise<AgentSession> {
return new StaleStartSession(config);
}
}
const client = new StaleStartClient();
const storage = new AgentStorage(join(workdir, "agents"), logger);
const manager = new AgentManager({ clients: { codex: client }, registry: storage, logger });
try {
const agent = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, {
workspaceId: undefined,
});
const dispatch = await startAgentRun(manager, agent.id, "Retry this prompt", logger, {
runOptions: { clientMessageId: "immediate-stale-start" },
});
// The stale start has failed and been cleared before the sender begins waiting.
await new Promise((resolve) => setTimeout(resolve, 0));
expect(manager.hasInFlightRun(agent.id)).toBe(false);
await expect(dispatchStarted(dispatch)).resolves.toBeUndefined();
await client.waitForRetryStart();
expect(manager.getTimeline(agent.id).filter((item) => item.type === "user_message")).toEqual([
expect.objectContaining({
text: "Retry this prompt",
clientMessageId: "immediate-stale-start",
}),
]);
} finally {
manager.prepareForShutdown();
await Promise.all(manager.listAgents().map((agent) => manager.closeAgent(agent.id)));
await manager.flushForShutdown();
rmSync(workdir, { recursive: true, force: true });
}
});
test.each(["reload", "retry", "stale retry"])(
"a sender's start wait rejects when its stale-session %s fails",
async (failure) => {
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-stale-start-failure-"));
const releaseStart = deferred<void>();
class StaleStartSession extends TestAgentSession {
override async startTurn(): Promise<{ turnId: string }> {
await releaseStart.promise;
throw new StaleProviderSessionError("stale-bridge");
}
}
class FailedRetrySession extends TestAgentSession {
override async startTurn(): Promise<{ turnId: string }> {
if (failure === "stale retry") throw new StaleProviderSessionError("retry-bridge");
throw new Error("retry failed");
}
}
class FailedRetryClient extends TestAgentClient {
override async createSession(config: AgentSessionConfig): Promise<AgentSession> {
return new StaleStartSession(config);
}
override async resumeSession(): Promise<AgentSession> {
if (failure === "reload") throw new Error("reload failed");
return new FailedRetrySession({ provider: "codex", cwd: workdir });
}
}
const manager = new AgentManager({ clients: { codex: new FailedRetryClient() }, logger });
try {
const agent = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, {
workspaceId: undefined,
});
const senderWait = dispatchStarted(
await startAgentRun(manager, agent.id, "Retry this prompt", logger),
);
const rejection = expect(senderWait).rejects.toThrow(
failure === "retry" ? "retry failed" : "is stale after its plugin reloaded",
);
releaseStart.resolve();
await rejection;
} finally {
releaseStart.resolve();
manager.prepareForShutdown();
await Promise.all(manager.listAgents().map((agent) => manager.closeAgent(agent.id)));
await manager.flushForShutdown();
rmSync(workdir, { recursive: true, force: true });
}
},
);
test("a sender's start wait rejects when Stop cancels its pending stale-session retry", async () => {
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-stale-retry-stop-"));
const releaseStart = deferred<void>();
const retryEntered = deferred<void>();
const retryCanceled = deferred<void>();
class StaleStartSession extends TestAgentSession {
override async startTurn(): Promise<{ turnId: string }> {
await releaseStart.promise;
throw new StaleProviderSessionError("stale-bridge");
}
}
class CanceledRetrySession extends TestAgentSession {
override async startTurn(): Promise<{ turnId: string }> {
retryEntered.resolve();
await retryCanceled.promise;
throw new AgentTurnStartCanceledError();
}
override async interrupt(): Promise<void> {
retryCanceled.resolve();
}
}
class RetryClient extends TestAgentClient {
override async createSession(config: AgentSessionConfig): Promise<AgentSession> {
return new StaleStartSession(config);
}
override async resumeSession(): Promise<AgentSession> {
return new CanceledRetrySession({ provider: "codex", cwd: workdir });
}
}
const manager = new AgentManager({ clients: { codex: new RetryClient() }, logger });
try {
const agent = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, {
workspaceId: undefined,
});
const senderWait = dispatchStarted(
await startAgentRun(manager, agent.id, "Retry this prompt", logger),
);
const rejection = expect(senderWait).rejects.toThrow("its prompt was not delivered");
releaseStart.resolve();
await retryEntered.promise;
await expect(manager.cancelAgentRun(agent.id)).resolves.toEqual({ status: "settled" });
await rejection;
expect(manager.getAgent(agent.id)?.lifecycle).toBe("idle");
expect(manager.getTimeline(agent.id)).toEqual([]);
} finally {
releaseStart.resolve();
retryCanceled.resolve();
manager.prepareForShutdown();
await Promise.all(manager.listAgents().map((agent) => manager.closeAgent(agent.id)));
await manager.flushForShutdown();
rmSync(workdir, { recursive: true, force: true });
}
});
test("a sender's start wait never adopts an unlinked run after a stale start", async () => {
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-unlinked-start-"));
const releaseStart = deferred<void>();
const staleError = new StaleProviderSessionError("stale-bridge");
class StaleStartSession extends TestAgentSession {
override async startTurn(): Promise<{ turnId: string }> {
await releaseStart.promise;
throw staleError;
}
}
class RetryClient extends TestAgentClient {
override async createSession(config: AgentSessionConfig): Promise<AgentSession> {
return new StaleStartSession(config);
}
}
const manager = new AgentManager({ clients: { codex: new RetryClient() }, logger });
try {
const agent = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, {
workspaceId: undefined,
});
const senderStart = new ForegroundPromptStart(agent.id);
const firstRun = drainAsyncGenerator(
manager.streamAgent(agent.id, "First prompt", undefined, senderStart),
);
const firstFailure = expect(firstRun).rejects.toBe(staleError);
const rejection = expect(senderStart.started).rejects.toThrow(staleError.message);
releaseStart.resolve();
await firstFailure;
try {
await manager.reloadAgentSession(agent.id);
const otherStart = new ForegroundPromptStart(agent.id);
const otherRun = drainAsyncGenerator(
manager.streamAgent(agent.id, "Another sender", undefined, otherStart),
);
await expect(otherStart.started).resolves.toBeUndefined();
await otherRun;
} finally {
senderStart.end();
}
await rejection;
expect(manager.getTimeline(agent.id).filter((item) => item.type === "user_message")).toEqual(
[],
);
} finally {
releaseStart.resolve();
manager.prepareForShutdown();
await Promise.all(manager.listAgents().map((agent) => manager.closeAgent(agent.id)));
await manager.flushForShutdown();
rmSync(workdir, { recursive: true, force: true });
}
});
test("acknowledged cancellation settles a pending run before it has a turn id", async () => {
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-cancel-pending-start-"));
const startEntered = deferred<void>();
@@ -15176,16 +14606,14 @@ test("workspace archive preserves a loaded history agent stamp and stamps cascad
labels: { [PARENT_AGENT_ID_LABEL]: parent.id },
workspaceId: undefined,
});
// Archive stamps are taken when the archive happens, so they follow the agents' activity.
const stamp = new Date(Date.now() + 60_000).toISOString();
const laterStamp = new Date(Date.now() + 120_000).toISOString();
const stamp = "2026-11-09T00:00:00.000Z";
await manager.archiveAgent(parent.id, stamp);
expect((await storage.get(parent.id))?.archivedAt).toBe(stamp);
expect((await storage.get(child.id))?.archivedAt).toBe(stamp);
await ensureAgentLoaded(parent.id, { agentManager: manager, agentStorage: storage, logger });
await manager.archiveAgent(parent.id, laterStamp);
await manager.archiveAgent(parent.id, "2026-11-09T01:00:00.000Z");
expect((await storage.get(parent.id))?.archivedAt).toBe(stamp);
expect((await storage.get(parent.id))?.updatedAt).toBe(laterStamp);
expect((await storage.get(parent.id))?.updatedAt).toBe("2026-11-09T01:00:00.000Z");
} finally {
await storage.flush();
rmSync(workdir, { recursive: true, force: true });
@@ -15533,11 +14961,3 @@ test("plugin instructions are recomputed for each launch without changing saved
expect(client.resumeOverrides.at(-1)?.daemonAppendSystemPrompt).toBe("Daemon");
expect((await storage.get(snapshot.id))?.config?.systemPrompt).toBe("Saved");
});
function dispatchStarted(dispatch: Awaited<ReturnType<typeof startAgentRun>>): Promise<void> {
if (dispatch.disposition !== "turn_started") {
throw new Error(`Expected a started turn, got ${dispatch.disposition}`);
}
void dispatch.started.catch(() => undefined);
return dispatch.started;
}
@@ -29,7 +29,6 @@ import { z } from "zod";
import type { TerminalManager } from "../../terminal/terminal-manager.js";
import {
AgentTurnStartCanceledError,
getAgentStreamEventTurnId,
type AgentCapabilityFlags,
type AgentClient,
@@ -93,7 +92,6 @@ import {
import { limitAgentTimelineItemContent } from "./agent-timeline-content.js";
import {
AgentRunState,
type ForegroundPromptStart,
type ForegroundTurnWaiter,
type PendingForegroundRun,
} from "./agent-run-state.js";
@@ -2352,7 +2350,7 @@ export class AgentManager {
private async persistArchivedRecord(
record: StoredAgentRecord,
options: { archivedAt: string; updatedAt: string },
options: { archivedAt: string; updatedAt?: string },
): Promise<ArchivedStoredAgentRecord> {
const archivedRecord = buildArchivedAgentRecord(record, options);
await this.requireRegistry().upsert(archivedRecord);
@@ -2872,11 +2870,7 @@ export class AgentManager {
throw new Error(`Agent not found: ${agentId}`);
}
// Archiving is the agent's latest change, as markRecordArchived records it for a loaded agent.
const nextRecord = await this.persistArchivedRecord(record, {
archivedAt,
updatedAt: archivedAt,
});
const nextRecord = await this.persistArchivedRecord(record, { archivedAt });
await this.syncNativeArchiveState(record.provider, record.persistence, "archive");
@@ -3145,7 +3139,7 @@ export class AgentManager {
pendingRun: PendingForegroundRun;
prompt: AgentPromptInput;
options?: AgentRunOptions;
}): Promise<string | null> {
}): Promise<string> {
const { agent, agentId, pendingRun, prompt, options } = params;
try {
const result = await agent.session.startTurn(prompt, options);
@@ -3154,32 +3148,11 @@ export class AgentManager {
}
return result.turnId;
} catch (error) {
if (error instanceof AgentTurnStartCanceledError) {
if (!pendingRun.settled) {
if (options?.clientMessageId) {
this.recordSubmittedPrompt(agent, prompt, options.clientMessageId, "rejected", {
messageId: options.clientMessageId,
});
}
await this.handleStreamEvent(agent, {
type: "turn_canceled",
provider: agent.provider,
reason: "interrupted",
});
this.finalizeForegroundTurn(agent);
this.runs.settleForegroundRun(agentId, pendingRun.token);
}
return null;
}
if (pendingRun.settled) {
throw error;
}
if (isStaleProviderSessionError(error)) {
this.runs.settleForegroundStart(pendingRun, {
status: "failed",
error: error.message,
stale: true,
});
this.runs.settleForegroundStart(pendingRun, { status: "failed", error: error.message });
agent.pendingReplacement = false;
if (!agent.activeForegroundTurnId) agent.lifecycle = "idle";
this.runs.settleForegroundRun(agentId, pendingRun.token);
@@ -3235,17 +3208,15 @@ export class AgentManager {
agentId: string,
prompt: AgentPromptInput,
options?: AgentRunOptions,
promptStart?: ForegroundPromptStart,
): AsyncGenerator<AgentStreamEvent> {
await this.ensureInteractiveSession(agentId);
yield* this.streamAgent(agentId, prompt, options, promptStart);
yield* this.streamAgent(agentId, prompt, options);
}
private async *streamAfterRuntimeCollection(
agentId: string,
prompt: AgentPromptInput,
options?: AgentRunOptions,
promptStart?: ForegroundPromptStart,
): AsyncGenerator<AgentStreamEvent> {
await this.waitForAgentClose(agentId);
await ensureAgentLoaded(agentId, {
@@ -3253,20 +3224,19 @@ export class AgentManager {
agentStorage: this.requireRegistry(),
logger: this.logger,
});
yield* this.streamAgent(agentId, prompt, options, promptStart);
yield* this.streamAgent(agentId, prompt, options);
}
streamAgent(
agentId: string,
prompt: AgentPromptInput,
options?: AgentRunOptions,
promptStart?: ForegroundPromptStart,
): AsyncGenerator<AgentStreamEvent> {
if (this.collectingRuntimes.has(agentId) || (!this.agents.has(agentId) && this.registry))
return this.streamAfterRuntimeCollection(agentId, prompt, options, promptStart);
return this.streamAfterRuntimeCollection(agentId, prompt, options);
const existingAgent = this.requireSessionAgent(agentId);
if (this.historySessions.has(existingAgent.session))
return this.streamAfterHistoryLoad(agentId, prompt, options, promptStart);
return this.streamAfterHistoryLoad(agentId, prompt, options);
this.logger.trace(
{
agentId,
@@ -3301,10 +3271,9 @@ export class AgentManager {
agent.lastError = undefined;
const pendingRun = this.runs.createPendingRun(agentId);
promptStart?.bind(pendingRun);
const streamForwarder = async function* streamForwarder(this: AgentManager) {
let turnId: string | null;
let turnId: string;
let turnStream: ReturnType<AgentRunState["createTurnStream"]> | null = null;
turnId = await this.startPendingForegroundTurn({
agent,
@@ -3313,15 +3282,6 @@ export class AgentManager {
prompt,
options,
});
if (turnId === null) {
const canceledEvent: AgentStreamEvent = {
type: "turn_canceled",
provider: agent.provider,
reason: "interrupted",
};
yield canceledEvent;
return;
}
if (isReplacement) {
agent.pendingReplacement = false;
@@ -3476,10 +3436,9 @@ export class AgentManager {
agentId: string,
prompt: AgentPromptInput,
options?: AgentRunOptions,
promptStart?: ForegroundPromptStart,
): Promise<AsyncGenerator<AgentStreamEvent>> {
this.requireSessionAgent(agentId);
return this.replaceRunInForegroundLane(agentId, prompt, options, promptStart);
return this.replaceRunInForegroundLane(agentId, prompt, options);
}
async steerAgentRun(
@@ -3520,7 +3479,6 @@ export class AgentManager {
agentId: string,
prompt: AgentPromptInput,
options?: AgentSteerOptions,
promptStart?: ForegroundPromptStart,
): Promise<ActiveTurnSteerDispatchResult> {
// A turn that is still starting has no id to steer yet. Replacing it would drop its
// prompt, so wait until it is accepted (or fails) and steer the turn it became.
@@ -3568,7 +3526,6 @@ export class AgentManager {
expectedTurnId,
prompt,
stripSteerOptions(options),
promptStart,
),
};
}
@@ -3634,10 +3591,9 @@ export class AgentManager {
expectedTurnId: string,
prompt: AgentPromptInput,
options?: AgentRunOptions,
promptStart?: ForegroundPromptStart,
): Promise<AsyncGenerator<AgentStreamEvent>> {
this.assertSteerAdmissionOwnsTurn(agent, expectedTurnId);
return this.replaceRunInForegroundLane(agent.id, prompt, options, promptStart, (live) =>
return this.replaceRunInForegroundLane(agent.id, prompt, options, (live) =>
this.assertSteerAdmissionOwnsTurn(live, expectedTurnId),
);
}
@@ -3650,13 +3606,12 @@ export class AgentManager {
agentId: string,
prompt: AgentPromptInput,
options: AgentRunOptions | undefined,
promptStart?: ForegroundPromptStart,
assertAdmission?: (agent: ActiveManagedAgent) => void,
): Promise<AsyncGenerator<AgentStreamEvent>> {
// Replacements queue in arrival order; each one holds the foreground lane only while
// it cancels and reserves, so Stop is never stuck behind a replacement that is waiting.
return this.runQueuedMutation(this.replacementMutationTails, agentId, () =>
this.replaceRunWhenAdmitted(agentId, prompt, options, promptStart, assertAdmission),
this.replaceRunWhenAdmitted(agentId, prompt, options, assertAdmission),
);
}
@@ -3664,7 +3619,6 @@ export class AgentManager {
agentId: string,
prompt: AgentPromptInput,
options: AgentRunOptions | undefined,
promptStart?: ForegroundPromptStart,
assertAdmission?: (agent: ActiveManagedAgent) => void,
): Promise<AsyncGenerator<AgentStreamEvent>> {
let stalledStart: PendingForegroundRun | null = null;
@@ -3683,7 +3637,7 @@ export class AgentManager {
if (!this.hasInFlightRun(agent.id)) {
return {
status: "reserved" as const,
iterator: this.streamAgent(agent.id, prompt, options, promptStart),
iterator: this.streamAgent(agent.id, prompt, options),
};
}
agent.pendingReplacement = true;
@@ -3697,7 +3651,7 @@ export class AgentManager {
}
return {
status: "reserved" as const,
iterator: this.streamAgent(agent.id, prompt, options, promptStart),
iterator: this.streamAgent(agent.id, prompt, options),
};
} catch (error) {
agent.pendingReplacement = false;
@@ -3888,10 +3842,7 @@ export class AgentManager {
}
async cancelAgentRun(agentId: string): Promise<AgentRunCancellationResult> {
return this.runForegroundMutation(agentId, () => {
this.requireSessionAgent(agentId).pendingReplacement = false;
return this.cancelAgentRunNow(agentId);
});
return this.runForegroundMutation(agentId, () => this.cancelAgentRunNow(agentId));
}
private async cancelAgentRunNow(agentId: string): Promise<AgentRunCancellationResult> {
@@ -15,7 +15,6 @@ import { join } from "node:path";
import { createTestLogger } from "../../test-utils/test-logger.js";
import { AgentManager } from "./agent-manager.js";
import { waitForAgentRunStartWithTimeout } from "./agent-prompt.js";
import { ForegroundPromptStart } from "./agent-run-state.js";
import type {
AgentClient,
AgentRunResult,
@@ -162,7 +161,7 @@ class SlowStartAgentClient implements AgentClient {
async function createRunStartScenario(startDelayMs: number | null): Promise<{
agentManager: AgentManager;
agentId: string;
startRun: () => Promise<{ started: Promise<void> }>;
startRun: () => Promise<void>;
cleanup: () => Promise<void>;
}> {
const workdir = mkdtempSync(join(tmpdir(), "agent-run-start-budget-"));
@@ -179,16 +178,14 @@ async function createRunStartScenario(startDelayMs: number | null): Promise<{
return {
agentManager,
agentId: snapshot.id,
// Returns the sender's start, bound to the run streamAgent registers.
// streamAgent registers the pending run synchronously, so the wait always observes it.
startRun: async () => {
const start = new ForegroundPromptStart(snapshot.id);
const run = agentManager.streamAgent(snapshot.id, "start the run", undefined, start);
const run = agentManager.streamAgent(snapshot.id, "start the run");
drained = (async () => {
for await (const _event of run) {
// Drain whatever the turn produces.
}
})().catch(() => undefined);
return { started: start.started };
},
cleanup: async () => {
// Release any turn still held open, then close. The drain is deliberately not
@@ -210,8 +207,8 @@ test("waiting for a run start outlasts the slowest provider startup budget", asy
vi.useFakeTimers();
try {
const { started } = await scenario.startRun();
const wait = waitForAgentRunStartWithTimeout(scenario.agentManager, scenario.agentId, started);
await scenario.startRun();
const wait = waitForAgentRunStartWithTimeout(scenario.agentManager, scenario.agentId);
let settled = false;
const markSettled = () => {
settled = true;
@@ -236,8 +233,8 @@ test("waiting for a run start still gives up at the run start budget", async ()
vi.useFakeTimers();
try {
const { started } = await scenario.startRun();
const wait = waitForAgentRunStartWithTimeout(scenario.agentManager, scenario.agentId, started);
await scenario.startRun();
const wait = waitForAgentRunStartWithTimeout(scenario.agentManager, scenario.agentId);
const rejection = expect(wait).rejects.toThrow(
"codex run did not start within 60 seconds (phase: run start)",
);
@@ -3,7 +3,6 @@ import type { Logger } from "pino";
import type { AgentPromptInput, AgentRunOptions } from "./agent-sdk-types.js";
import type { AgentManager, ManagedAgent } from "./agent-manager.js";
import { ForegroundPromptStart } from "./agent-run-state.js";
import type { AgentStorage } from "./agent-storage.js";
import { ensureAgentLoaded } from "./agent-loading.js";
import { isStaleProviderSessionError } from "./stale-provider-session-error.js";
@@ -39,17 +38,11 @@ export interface StartAgentRunOptions {
export type PromptDispatchDisposition = "out_of_band" | "steered" | "turn_started";
/** A dispatched prompt. A started turn carries its sender's start outcome. */
export type PromptDispatchResult =
| { disposition: "turn_started"; started: Promise<void> }
| { disposition: Exclude<PromptDispatchDisposition, "turn_started"> };
async function steerOrReplaceActiveRun(
agentManager: AgentRunController,
agentId: string,
prompt: AgentPromptInput,
options: StartAgentRunOptions | undefined,
promptStart: ForegroundPromptStart,
): Promise<
| { disposition: "steered" }
| {
@@ -64,12 +57,7 @@ async function steerOrReplaceActiveRun(
const steerOptions = options.clearPendingPermissions
? { ...options.runOptions, clearPendingPermissions: true }
: options.runOptions;
const result = await agentManager.steerOrReplaceActiveTurn(
agentId,
prompt,
steerOptions,
promptStart,
);
const result = await agentManager.steerOrReplaceActiveTurn(agentId, prompt, steerOptions);
if (result.status === "steered") {
return { disposition: "steered" };
}
@@ -84,15 +72,14 @@ async function startOrReplaceRun(
agentId: string,
prompt: AgentPromptInput,
options: StartAgentRunOptions | undefined,
promptStart: ForegroundPromptStart,
): Promise<{
iterator: AsyncGenerator<import("./agent-sdk-types.js").AgentStreamEvent>;
replaced: boolean;
}> {
const replaced = Boolean(options?.replaceRunning && agentManager.hasInFlightRun(agentId));
const iterator = replaced
? await agentManager.replaceAgentRun(agentId, prompt, options?.runOptions, promptStart)
: agentManager.streamAgent(agentId, prompt, options?.runOptions, promptStart);
? await agentManager.replaceAgentRun(agentId, prompt, options?.runOptions)
: agentManager.streamAgent(agentId, prompt, options?.runOptions);
return { iterator, replaced };
}
@@ -110,7 +97,7 @@ export async function startAgentRun(
prompt: AgentPromptInput,
logger: Logger,
options?: StartAgentRunOptions,
): Promise<PromptDispatchResult> {
): Promise<{ disposition: PromptDispatchDisposition }> {
const snapshot = agentManager.getAgent(agentId);
logger.trace(
{
@@ -131,25 +118,16 @@ export async function startAgentRun(
options?.onDispatch?.("out_of_band");
return { disposition: "out_of_band" };
}
const promptStart = new ForegroundPromptStart(agentId);
try {
try {
await agentManager.reloadStalePluginSession(agentId);
return await startAgentRunInner(agentManager, agentId, prompt, logger, options, promptStart);
} catch (error) {
if (!isStaleProviderSessionError(error)) throw error;
logger.info(
{ agentId, err: error },
"Provider session went stale; reopening from persistence",
);
// The live session belongs to a retired plugin runtime. Reload swaps in a
// fresh session on the current runtime while preserving history and labels.
await agentManager.reloadAgentSession(agentId);
return await startAgentRunInner(agentManager, agentId, prompt, logger, options, promptStart);
}
await agentManager.reloadStalePluginSession(agentId);
return await startAgentRunInner(agentManager, agentId, prompt, logger, options);
} catch (error) {
promptStart.end();
throw error;
if (!isStaleProviderSessionError(error)) throw error;
logger.info({ agentId, err: error }, "Provider session went stale; reopening from persistence");
// The live session belongs to a retired plugin runtime. Reload swaps in a
// fresh session on the current runtime while preserving history and labels.
await agentManager.reloadAgentSession(agentId);
return await startAgentRunInner(agentManager, agentId, prompt, logger, options);
}
}
@@ -158,13 +136,12 @@ async function startAgentRunInner(
agentId: string,
prompt: AgentPromptInput,
logger: Logger,
options: StartAgentRunOptions | undefined,
promptStart: ForegroundPromptStart,
): Promise<PromptDispatchResult> {
options?: StartAgentRunOptions,
): Promise<{ disposition: PromptDispatchDisposition }> {
const snapshot = agentManager.getAgent(agentId);
const steered = options?.idleOnly
? null
: await steerOrReplaceActiveRun(agentManager, agentId, prompt, options, promptStart);
: await steerOrReplaceActiveRun(agentManager, agentId, prompt, options);
if (options?.idleOnly && agentManager.hasInFlightRun(agentId)) {
throw new AgentTurnBusyError(`Agent ${agentId} is running`);
}
@@ -174,7 +151,7 @@ async function startAgentRunInner(
}
const { iterator, replaced } = steered
? { iterator: steered.iterator, replaced: true }
: await startOrReplaceRun(agentManager, agentId, prompt, options, promptStart);
: await startOrReplaceRun(agentManager, agentId, prompt, options);
logger.trace(
{
agentId,
@@ -196,7 +173,7 @@ async function startAgentRunInner(
"Provider session went stale; reopening from persistence",
);
await agentManager.reloadAgentSession(agentId);
const retry = await startOrReplaceRun(agentManager, agentId, prompt, options, promptStart);
const retry = await startOrReplaceRun(agentManager, agentId, prompt, options);
await drainAgentRunIterator(retry.iterator);
}
logger.trace(
@@ -218,11 +195,9 @@ async function startAgentRunInner(
"agent.session.iterator.error",
);
logger.error({ err: error, agentId }, "Agent stream failed");
} finally {
promptStart.end();
}
})();
return { disposition: "turn_started", started: promptStart.started };
return { disposition: "turn_started" };
}
/**
@@ -295,9 +270,8 @@ export interface StartCreatedAgentInitialPromptParams {
const AGENT_RUN_START_TIMEOUT_MS = 60_000;
export async function waitForAgentRunStartWithTimeout(
agentManager: Pick<AgentManager, "getAgent">,
agentManager: AgentManager,
agentId: string,
started: Promise<void>,
signal?: AbortSignal,
): Promise<void> {
const provider = agentManager.getAgent(agentId)?.provider ?? "provider";
@@ -312,28 +286,15 @@ export async function waitForAgentRunStartWithTimeout(
AGENT_RUN_START_TIMEOUT_MS,
);
const abortSignal = signal ? AbortSignal.any([startAbort.signal, signal]) : startAbort.signal;
let onAbort: (() => void) | null = null;
const aborted = new Promise<never>((_, reject) => {
onAbort = () => reject(createStartAbortError(abortSignal.reason));
if (abortSignal.aborted) onAbort();
else abortSignal.addEventListener("abort", onAbort, { once: true });
});
try {
await Promise.race([started, aborted]);
await agentManager.waitForAgentRunStart(agentId, {
signal: signal ? AbortSignal.any([startAbort.signal, signal]) : startAbort.signal,
});
} finally {
clearTimeout(startTimeout);
if (onAbort) abortSignal.removeEventListener("abort", onAbort);
}
}
function createStartAbortError(reason: unknown): Error {
let message = "wait_for_agent_start aborted";
if (typeof reason === "string") message = reason;
else if (reason instanceof Error) message = reason.message;
return Object.assign(new Error(message), { name: "AbortError" });
}
async function resolvePromptSource(
source: AgentPromptSource | undefined,
manager: Pick<AgentManager, "getAgent">,
@@ -359,7 +320,7 @@ async function resolvePromptSource(
*/
export async function sendPromptToAgent(
params: SendPromptToAgentParams,
): Promise<PromptDispatchResult> {
): Promise<{ disposition: PromptDispatchDisposition }> {
const source = await resolvePromptSource(params.source, params.agentManager, params.agentStorage);
const delivery = prepareAgentMessage(params.prompt, source, params.messageId);
return sendPreparedPromptToAgent({
@@ -374,14 +335,14 @@ export async function sendPromptToAgent(
/** Dispatch daemon-prepared context without reclassifying it as human input. */
export async function sendPreparedPromptToAgent(
params: Omit<SendPromptToAgentParams, "source" | "messageId">,
): Promise<PromptDispatchResult> {
): Promise<{ disposition: PromptDispatchDisposition }> {
const unarchive = params.unarchive ?? true;
const record = await params.agentStorage.get(params.agentId);
let archivedAtToRestore: string | null = null;
if (record?.archivedAt) {
if (!unarchive) {
return { disposition: "turn_started", started: Promise.resolve() };
return { disposition: "turn_started" };
}
if (await unarchiveAgentState(params.agentStorage, params.agentManager, params.agentId)) {
archivedAtToRestore = record.archivedAt;
@@ -447,11 +408,7 @@ export async function startCreatedAgentInitialPrompt(
);
if (dispatchResult.disposition === "turn_started") {
await waitForAgentRunStartWithTimeout(
params.agentManager,
params.agentId,
dispatchResult.started,
);
await waitForAgentRunStartWithTimeout(params.agentManager, params.agentId);
}
const refreshedSnapshot = params.agentManager.getAgent(params.agentId) ?? params.snapshot ?? null;
@@ -13,7 +13,7 @@ export interface ForegroundTurnWaiter {
type ForegroundRunStart =
| { status: "pending" }
| { status: "started"; turnId: string }
| { status: "failed"; error: string; stale?: true };
| { status: "failed"; error: string };
export interface PendingForegroundRun {
token: string;
@@ -343,59 +343,3 @@ function settleTrackedRun(run: TrackedAgentRun): void {
run.settled = true;
run.resolveSettled();
}
/**
* Follows one sender's prompt to the foreground run that starts it. Each run created for the
* prompt, including a stale-session retry, is bound here, so `started` settles for this
* sender's prompt and never for another run the agent tracks.
*/
export class ForegroundPromptStart {
readonly started: Promise<void>;
private resolveStarted!: () => void;
private rejectStarted!: (error: Error) => void;
private run: PendingForegroundRun | null = null;
private done = false;
constructor(private readonly agentId: string) {
this.started = new Promise<void>((resolve, reject) => {
this.resolveStarted = resolve;
this.rejectStarted = reject;
});
// Steered and fire-and-forget dispatches never wait on the start.
this.started.catch(() => undefined);
}
/** A run was created for this prompt. */
bind(run: PendingForegroundRun): void {
this.run = run;
void Promise.race([run.turnStartedPromise, run.settledPromise]).then(() =>
this.settle(run, { ended: false }),
);
}
/** The prompt's dispatch is over; no further run will be created for it. */
end(): void {
this.settle(this.run, { ended: true });
}
private settle(run: PendingForegroundRun | null, { ended }: { ended: boolean }): void {
if (this.done || run !== this.run) return;
if (run?.start.status === "started") {
this.done = true;
this.resolveStarted();
return;
}
// A stale-session failure is retried with a new run; wait for it unless dispatch ended.
if (run?.start.status === "failed" && run.start.stale && !ended) return;
this.done = true;
this.rejectStarted(new Error(this.describeUnstarted(run)));
}
private describeUnstarted(run: PendingForegroundRun | null): string {
if (run?.start.status === "failed") return run.start.error;
if (run?.settled) {
return `Agent ${this.agentId} run was canceled before its turn started; its prompt was not delivered`;
}
return `Agent ${this.agentId} run finished before starting`;
}
}
@@ -528,14 +528,6 @@ export type AgentPermissionResponse =
interrupt?: boolean;
};
/** A requested turn was canceled before the provider accepted it. */
export class AgentTurnStartCanceledError extends Error {
constructor() {
super("Turn was canceled before starting");
this.name = "AgentTurnStartCanceledError";
}
}
export interface AgentRunResult {
sessionId: string;
finalText: string;
@@ -10,7 +10,6 @@ import { AgentManager } from "../agent-manager.js";
import { AgentStorage } from "../agent-storage.js";
import type { CreatePaseoWorktreeWorkflowResult } from "../../worktree-session.js";
import { createAgentCommand } from "./create.js";
import { ForegroundPromptStart } from "../agent-run-state.js";
import type { ManagedAgent } from "../agent-manager.js";
const logger = createTestLogger();
@@ -90,12 +89,9 @@ test("session create forwards clientMessageId to the initial prompt run options"
firstAgentContext: { attachments: [] },
});
expect(streamAgent).toHaveBeenCalledWith(
"agent-1",
"hello from create",
{ clientMessageId: "msg-create-1" },
expect.any(ForegroundPromptStart),
);
expect(streamAgent).toHaveBeenCalledWith("agent-1", "hello from create", {
clientMessageId: "msg-create-1",
});
});
test("session create validates the requested mode against the provider's modes", async () => {
@@ -1,4 +1,3 @@
import { AgentRunState, ForegroundPromptStart } from "./agent-run-state.js";
import {
createFinishSubscriptions,
createFinishObservation,
@@ -280,15 +279,8 @@ function buildAgentManagerSpies() {
steerOrReplaceActiveTurn: async () => ({ status: "inactive" as const }),
tryRunOutOfBand: vi.fn().mockReturnValue(false),
subscribe: vi.fn().mockReturnValue(() => {}),
streamAgent: vi.fn(
(agentId: string, _prompt: unknown, _options: unknown, start?: ForegroundPromptStart) => {
const runs = new AgentRunState();
const run = runs.createPendingRun(agentId);
runs.settleForegroundStart(run, { status: "started", turnId: `${agentId}-turn` });
start?.bind(run);
return (async function* noop() {})();
},
),
streamAgent: vi.fn(() => (async function* noop() {})()),
waitForAgentRunStart: vi.fn().mockResolvedValue(undefined),
respondToPermission: vi.fn(),
cancelAgentRun: vi.fn(),
getPendingPermissions: vi.fn(),
@@ -91,7 +91,7 @@ test.each([
}
});
async function createBypassSession() {
test("bypass allows execution without publishing permission events and follows live mode changes", async () => {
let requestPermission: CanUseTool | undefined;
const query = Object.assign((async function* () {})(), {
async setPermissionMode(_mode: PermissionMode) {},
@@ -112,25 +112,17 @@ async function createBypassSession() {
});
const events: AgentStreamEvent[] = [];
session.subscribe((event) => events.push(event));
await session.setMode("bypassPermissions");
if (!requestPermission) throw new Error("SDK permission callback was not installed");
return { session, events, requestPermission };
}
test("bypass approves Claude's own checks without publishing permission events and follows live mode changes", async () => {
const { session, events, requestPermission } = await createBypassSession();
try {
await session.setMode("bypassPermissions");
if (!requestPermission) throw new Error("SDK permission callback was not installed");
const controller = new AbortController();
const input = { command: "rm -rf build" };
// Claude Code sends these fields, but this SDK version does not declare them on CanUseTool.
const ownCheck = {
const input = { command: "echo hello" };
const result = requestPermission("Bash", input, {
signal: controller.signal,
toolUseID: "execution",
decisionReason: "Dangerous rm command",
decisionReasonType: "safetyCheck",
};
const result = requestPermission("Bash", input, ownCheck);
// Abort also settles a prompting callback, so this test never hangs.
decisionReason: "Explicit ask rule",
});
// Abort also settles the pre-fix callback, so this repro never hangs.
controller.abort();
await expect(result).resolves.toMatchObject({ behavior: "allow", updatedInput: input });
expect(events.filter((event) => event.type.startsWith("permission_"))).toEqual([]);
@@ -143,7 +135,6 @@ test("bypass approves Claude's own checks without publishing permission events a
] as const) {
await session.setMode(mode);
const resolution = requestPermission(tool, toolInput, {
...ownCheck,
signal: new AbortController().signal,
toolUseID: tool,
});
@@ -158,44 +149,3 @@ test("bypass approves Claude's own checks without publishing permission events a
await session.close();
}
});
test.each([
["an ask rule", { decisionReasonType: "rule" }],
["a hook", { decisionReasonType: "hook", decisionReason: "Confirm before posting" }],
[
"an ask rule on Claude's own check",
{
decisionReasonType: "safetyCheck",
matchedAskRule: { source: "policySettings", toolName: "Bash", ruleContent: "rm *" },
},
],
[
"a tool the user answers on the card",
{ decisionReasonType: "other", requiresUserInteraction: true },
],
["a compound command with an ask rule in one part", { decisionReasonType: "subcommandResults" }],
[
"a read the user blocked outside the working directories",
{ decisionReasonType: "safetyCheck", decisionReasonCode: "outside_reads_blocked" },
],
[
"an organization's ask limit",
{ decisionReasonType: "workingDir", decisionReasonCode: "org_ask_ceiling" },
],
["a sandbox override the user's read block raised", { decisionReasonType: "sandboxOverride" }],
["a Claude Code that does not say why it asks", {}],
])("bypass still asks the user about %s", async (_source, why) => {
const { session, events, requestPermission } = await createBypassSession();
try {
const ask = { signal: new AbortController().signal, toolUseID: "execution", ...why };
const resolution = requestPermission("Bash", { command: "gh pr comment 1" }, ask);
const requestEvent = events.at(-1);
expect(requestEvent?.type).toBe("permission_requested");
if (requestEvent?.type !== "permission_requested")
throw new Error("Missing permission request");
await session.respondToPermission(requestEvent.request.id, { behavior: "deny" });
await expect(resolution).resolves.toMatchObject({ behavior: "deny" });
} finally {
await session.close();
}
});
@@ -11,7 +11,6 @@ import path from "node:path";
import { LRUCache } from "lru-cache";
import stripAnsi from "strip-ansi";
import { createImportDescriptorScheduler } from "./import-descriptor-scheduler.js";
import { bypassApprovesAsk } from "./bypass-approval.js";
import {
type AgentDefinition,
type CanUseTool,
@@ -5320,8 +5319,10 @@ class ClaudeAgentSession implements AgentSession {
input,
options,
): Promise<PermissionResult> => {
// Decide before publishing anything: bypassed asks never enter the permission UI.
if (this.currentMode === "bypassPermissions" && bypassApprovesAsk(toolName, options)) {
// Decide before publishing anything: bypassed tools never enter the permission UI.
// Claude also routes questions and plan review through this callback.
const needsUserAnswer = toolName === "AskUserQuestion" || toolName === "ExitPlanMode";
if (this.currentMode === "bypassPermissions" && !needsUserAnswer) {
return { behavior: "allow", updatedInput: input, toolUseID: options.toolUseID };
}
@@ -1,43 +0,0 @@
import type { CanUseTool } from "@anthropic-ai/claude-agent-sdk";
type PermissionOptions = Parameters<CanUseTool>[2];
// In bypassPermissions, Claude Code still forwards an ask when the user configured one
// (a permissions.ask rule, including managed policy, or a PreToolUse hook), when the tool
// needs an answer, or when one of its own checks fires. Bypass approves only Claude's own
// checks. A missing or unknown reason type stays with the user.
// `subcommandResults` is left out: a compound or piped command uses it as a container,
// including when a user's ask rule matched one of its parts. `sandboxOverride` is left
// out: in Bypass, Claude Code forwards it only when the user's read block or hook raised it.
const CLAUDE_OWN_CHECK_TYPES: ReadonlySet<string> = new Set([
"safetyCheck",
"workingDir",
"mode",
"classifier",
"asyncAgent",
]);
// Settings the user or organization chose, which Claude Code reports under its own types:
// permissions.blockReadsOutsideWorkingDirectories, and an organization's ask limit.
const CONFIGURED_ASK_CODES: ReadonlySet<string> = new Set([
"outside_reads_blocked",
"org_ask_ceiling",
]);
const QUESTION_TOOLS: ReadonlySet<string> = new Set(["AskUserQuestion", "ExitPlanMode"]);
export function bypassApprovesAsk(toolName: string, options: PermissionOptions): boolean {
if (QUESTION_TOOLS.has(toolName) || options.matchedAskRule) {
return false;
}
// The SDK forwards these from Claude Code without declaring them on CanUseTool.
if ("requiresUserInteraction" in options && options.requiresUserInteraction === true) {
return false;
}
const reasonCode = "decisionReasonCode" in options ? options.decisionReasonCode : undefined;
if (typeof reasonCode === "string" && CONFIGURED_ASK_CODES.has(reasonCode)) {
return false;
}
const reasonType = "decisionReasonType" in options ? options.decisionReasonType : undefined;
return typeof reasonType === "string" && CLAUDE_OWN_CHECK_TYPES.has(reasonType);
}
@@ -5428,7 +5428,7 @@ describe("Codex app-server provider", () => {
threadStart.resolve({ thread: { id: "thread-1" } });
await expect(interruptPromise).resolves.toBeUndefined();
await expect(resultPromise).resolves.toMatchObject({ canceled: true, timeline: [] });
await expect(resultPromise).rejects.toThrow("interrupted before reaching Codex");
expect(appServer.requests()).not.toContainEqual(
expect.objectContaining({ method: "turn/start" }),
);
@@ -3,7 +3,6 @@ import { applyProviderOptionsPatch } from "../option-controls.js";
import { assertChangesAreLive, validateProviderOptions } from "../provider-options.js";
import { CodexBackgroundInventory } from "./codex/background-inventory.js";
import {
AgentTurnStartCanceledError,
getAgentStreamEventTurnId,
type AgentPermissionAction,
type AgentCapabilityFlags,
@@ -4697,7 +4696,7 @@ export class CodexAppServerAgentSession implements AgentSession {
// outlives it into the new turn.
await this.waitForInterruptedTurnCleanup();
if (pendingStart.cancelRequested) {
throw new AgentTurnStartCanceledError();
throw new Error("Codex turn start was interrupted before reaching Codex");
}
await this.client.request("turn/start", turnStart.params, TURN_START_TIMEOUT_MS);
return { turnId };
@@ -1,5 +1,4 @@
import {
AgentTurnStartCanceledError,
getAgentStreamEventTurnId,
type AgentPromptInput,
type AgentRunOptions,
@@ -91,9 +90,6 @@ export async function runProviderTurn({
processEvent(event);
}
await completion;
} catch (error) {
if (!(error instanceof AgentTurnStartCanceledError)) throw error;
return { sessionId: await getSessionId(), finalText: "", timeline: [], canceled: true };
} finally {
unsubscribe();
}
@@ -2051,7 +2051,7 @@ function createToolCatalog(
};
}
const dispatch = await sendPromptToAgent({
const { disposition } = await sendPromptToAgent({
agentManager,
agentStorage,
agentId,
@@ -2070,14 +2070,11 @@ function createToolCatalog(
});
// Return once the provider has accepted the turn, so the status reports it running.
const { disposition } = dispatch;
if (dispatch.disposition === "turn_started") {
await waitForAgentRunStartWithTimeout(agentManager, agentId, dispatch.started).catch(
(error) => {
rejectNotification();
throw error;
},
);
if (disposition === "turn_started") {
await waitForAgentRunStartWithTimeout(agentManager, agentId).catch((error) => {
rejectNotification();
throw error;
});
}
const currentSnapshot = agentManager.getAgent(agentId);
+2 -2
View File
@@ -128,7 +128,7 @@ export async function fanOutReconciledWorkspaceUpdates(input: {
);
}
import { VoiceAssistantWebSocketServer, isDaemonOriginAllowed } from "./websocket-server.js";
import { VoiceAssistantWebSocketServer } from "./websocket-server.js";
import { WorkspaceSetupRuntime } from "./workspace-setup-runtime.js";
import { createWorkspaceLabelService } from "./workspace-labels/index.js";
import { createGitHubService } from "../services/github-service.js";
@@ -813,7 +813,7 @@ export async function createPaseoDaemon(
app.use((req, res, next) => {
const origin = req.headers.origin;
if (origin && isDaemonOriginAllowed(origin, req.headers.host ?? null, allowedOrigins)) {
if (origin && (allowedOrigins.has("*") || allowedOrigins.has(origin))) {
res.setHeader("Access-Control-Allow-Origin", origin);
res.setHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS");
res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
@@ -9,7 +9,7 @@ import {
symlinkSync,
} from "fs";
import { once } from "node:events";
import { get, type IncomingMessage } from "node:http";
import { get } from "node:http";
import { tmpdir } from "os";
import path from "path";
import { createDaemonTestContext, type DaemonTestContext } from "../test-utils/index.js";
@@ -69,29 +69,6 @@ describe("daemon E2E", () => {
}, 60000);
describe("file download tokens", () => {
test("lets a page on a loopback alias of the request's host and port fetch a download", async () => {
const cwd = tmpCwd();
writeFileSync(path.join(cwd, "download.bin"), "download bytes");
try {
// The web UI behind a remapped port (for example Docker -p 8080:6767): the page is at
// http://127.0.0.1:8080 and the app sends the request to localhost:8080. The WebSocket
// accepts this origin, so the download must as well.
const token = await ctx.client.requestDownloadToken(cwd, "download.bin");
const request = get({
host: "127.0.0.1",
port: ctx.daemon.port,
path: `/api/files/download?token=${token.token}`,
headers: { Host: "localhost:8080", Origin: "http://127.0.0.1:8080" },
});
const [response] = (await once(request, "response")) as [IncomingMessage];
response.resume();
expect(response.statusCode).toBe(200);
expect(response.headers["access-control-allow-origin"]).toBe("http://127.0.0.1:8080");
} finally {
rmSync(cwd, { recursive: true, force: true });
}
});
test.skipIf(process.platform !== "linux")(
"releases file descriptors after repeated HTTP download cancellations",
async () => {
@@ -38,7 +38,6 @@ import {
type ScheduleServiceOptions,
} from "./service.js";
import { ScheduleStore } from "./store.js";
import { ForegroundPromptStart } from "../agent/agent-run-state.js";
import type { ScheduleExecutionResult, StoredSchedule } from "@getpaseo/protocol/schedule/types";
interface ScheduleServiceInternals {
@@ -755,7 +754,6 @@ describe("ScheduleService", () => {
agent.id,
expect.stringContaining(`Schedule fired (id=${schedule.id}, run=`),
undefined,
expect.any(ForegroundPromptStart),
]);
});
-1
View File
@@ -8993,7 +8993,6 @@ export class Session {
await waitForAgentRunStartWithTimeout(
this.agentManager,
agentId,
result.started,
this.delivery.requestSignal,
);
}
@@ -50,11 +50,7 @@ export function createTestAgentMessages(params: {
runOptions: { clientMessageId: request.messageIds[0] },
});
if (result.disposition === "turn_started")
await waitForAgentRunStartWithTimeout(
params.agentManager,
request.recipientId,
result.started,
);
await waitForAgentRunStartWithTimeout(params.agentManager, request.recipientId);
return result.disposition;
},
onError: (error, request) =>
+7 -21
View File
@@ -745,7 +745,7 @@ export class VoiceAssistantWebSocketServer {
{ replayState: false },
),
dispatch: async (batch) => {
const dispatch = await sendPreparedPromptToAgent({
const { disposition } = await sendPreparedPromptToAgent({
agentManager,
agentStorage,
agentId: batch.recipientId,
@@ -758,9 +758,9 @@ export class VoiceAssistantWebSocketServer {
runOptions: { clientMessageId: batch.messageIds[0] },
logger: this.logger,
});
if (dispatch.disposition === "turn_started")
await waitForAgentRunStartWithTimeout(agentManager, batch.recipientId, dispatch.started);
return dispatch.disposition;
if (disposition === "turn_started")
await waitForAgentRunStartWithTimeout(agentManager, batch.recipientId);
return disposition;
},
onError: (err, batch) =>
this.logger.error(
@@ -998,7 +998,9 @@ export class VoiceAssistantWebSocketServer {
callback(false, 403, "Host not allowed");
return;
}
if (!origin || isDaemonOriginAllowed(origin, requestHost, allowedOrigins)) {
const sameOrigin = isWebSocketSameOrigin(origin, requestHost);
if (!origin || allowedOrigins.has("*") || allowedOrigins.has(origin) || sameOrigin) {
callback(true);
} else {
this.incrementRuntimeCounter("originRejected");
@@ -3265,22 +3267,6 @@ function isLoopbackAlias(hostname: string): boolean {
return /^127(?:\.\d{1,3}){3}$/.test(normalized);
}
/**
* Whether a page at `origin` may talk to the daemon reached at `requestHost`. The WebSocket
* upgrade and the HTTP CORS check both use it, so a page that can connect can also fetch.
*/
export function isDaemonOriginAllowed(
origin: string,
requestHost: string | null,
allowedOrigins: Set<string>,
): boolean {
return (
allowedOrigins.has("*") ||
allowedOrigins.has(origin) ||
isWebSocketSameOrigin(origin, requestHost)
);
}
export function isWebSocketSameOrigin(
origin: string | undefined,
requestHost: string | null,
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/website",
"version": "0.16.1",
"version": "0.16.0",
"private": true,
"type": "module",
"scripts": {
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/builtin-plugins",
"version": "0.16.1",
"version": "0.16.0",
"private": true,
"type": "module",
"scripts": {