mirror of
https://github.com/getpaseo/paseo.git
synced 2026-11-18 14:25:25 +00:00
Compare commits
34
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2ee30f4164 | ||
|
|
ac54c07639 | ||
|
|
46bd5d8a3e | ||
|
|
9895e0c957 | ||
|
|
2e9921e0e0 | ||
|
|
b1a2a50d50 | ||
|
|
9493a4f436 | ||
|
|
a87bd7fc0c | ||
|
|
527be52f2b | ||
|
|
fa6c50063e | ||
|
|
d364dbecb5 | ||
|
|
8edd1f407d | ||
|
|
f284e9abe5 | ||
|
|
c5bfe79c33 | ||
|
|
8d66a7c52e | ||
|
|
7a5b8e68e3 | ||
|
|
d577594173 | ||
|
|
293fbf825d | ||
|
|
c09a3d81e7 | ||
|
|
8c91adeba8 | ||
|
|
0a8b7a6a1e | ||
|
|
18192dc48b | ||
|
|
162745d8e6 | ||
|
|
937a610006 | ||
|
|
2269c8a010 | ||
|
|
e0847ac82f | ||
|
|
9ba2950132 | ||
|
|
fbb7a2c094 | ||
|
|
4437186c49 | ||
|
|
4bba288c10 | ||
|
|
c48d1c1700 | ||
|
|
db3cfadc6c | ||
|
|
c54bc39e79 | ||
|
|
228e6f75ea |
@@ -1,5 +1,41 @@
|
||||
# Changelog
|
||||
|
||||
## 0.16.2 - 2026-11-18
|
||||
|
||||
### Fixed
|
||||
|
||||
- Fixed Collapse turns hiding a finished reply when Claude answers a later background task notification ([#10092](https://github.com/getpaseo/paseo/pull/10092))
|
||||
- Fixed detached worktree commits getting lost when archiving a workspace ([#10009](https://github.com/getpaseo/paseo/pull/10009) by [@ragokan](https://github.com/ragokan))
|
||||
- Fixed Desktop updates leaving an older daemon running when an earlier Desktop session started it ([#10067](https://github.com/getpaseo/paseo/pull/10067))
|
||||
- Fixed daemons losing their Hub connection after execution permissions changed ([#10113](https://github.com/getpaseo/paseo/pull/10113))
|
||||
- Fixed saved hosts disappearing when one stored entry could not be read ([#9847](https://github.com/getpaseo/paseo/pull/9847) by [@ragokan](https://github.com/ragokan))
|
||||
- Fixed worktree creation timing out while scanning large ignored folders that `.worktreeinclude` does not name ([#10020](https://github.com/getpaseo/paseo/pull/10020) by [@mgranderath](https://github.com/mgranderath))
|
||||
- Fixed Steer cancelling a Claude compaction in progress ([#10028](https://github.com/getpaseo/paseo/pull/10028) by [@NightMachinery](https://github.com/NightMachinery))
|
||||
- Fixed agents getting stuck after a second Stop when the provider reused the cancelled turn ID ([#9774](https://github.com/getpaseo/paseo/pull/9774) by [@DAnaeto](https://github.com/DAnaeto))
|
||||
- Fixed Desktop staying blank after its renderer exited unexpectedly ([#10035](https://github.com/getpaseo/paseo/pull/10035))
|
||||
- Fixed failed file downloads taking over the app window on web and Desktop ([#9937](https://github.com/getpaseo/paseo/pull/9937) by [@panta82](https://github.com/panta82))
|
||||
- Fixed Import Session losing its scroll position when you select Load more ([#9974](https://github.com/getpaseo/paseo/pull/9974))
|
||||
- Fixed terminals failing to open when the home filesystem refuses Unix sockets, such as on AFS ([#9214](https://github.com/getpaseo/paseo/pull/9214) by [@bendavid](https://github.com/bendavid))
|
||||
- Fixed timed-out Git watchers repeatedly rescanning large repositories ([#9828](https://github.com/getpaseo/paseo/pull/9828) by [@Spshulem](https://github.com/Spshulem))
|
||||
- Fixed `paseo workspace create --path .` using the local daemon's directory instead of the caller's ([#10010](https://github.com/getpaseo/paseo/pull/10010))
|
||||
- Fixed MCP agent status and list responses omitting background work for idle agents ([#10022](https://github.com/getpaseo/paseo/pull/10022) by [@ortschun](https://github.com/ortschun))
|
||||
- Fixed the thinking selector showing an old level after OMP changes it ([#9841](https://github.com/getpaseo/paseo/pull/9841) by [@dsingal0](https://github.com/dsingal0))
|
||||
|
||||
## 0.16.1 - 2026-11-17
|
||||
|
||||
### Fixed
|
||||
|
||||
- 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))
|
||||
|
||||
@@ -1,5 +1,41 @@
|
||||
# Changelog
|
||||
|
||||
## 0.16.2 - 2026-11-18
|
||||
|
||||
### 修复
|
||||
|
||||
- 修复启用“折叠轮次”时,Claude 回复后续后台任务通知导致上一条已完成的回复被折叠的问题 ([#10092](https://github.com/getpaseo/paseo/pull/10092))
|
||||
- 修复归档工作区时丢失分离 HEAD 的 worktree 提交的问题 ([#10009](https://github.com/getpaseo/paseo/pull/10009),贡献者:[@ragokan](https://github.com/ragokan))
|
||||
- 修复 Desktop 更新后,由上一次 Desktop 会话启动的旧版 daemon 仍在运行的问题 ([#10067](https://github.com/getpaseo/paseo/pull/10067))
|
||||
- 修复更改执行权限后 daemon 与 Hub 断开连接的问题 ([#10113](https://github.com/getpaseo/paseo/pull/10113))
|
||||
- 修复一条已保存的主机记录无法读取时,其他主机也消失的问题 ([#9847](https://github.com/getpaseo/paseo/pull/9847),贡献者:[@ragokan](https://github.com/ragokan))
|
||||
- 修复创建 worktree 时,扫描 `.worktreeinclude` 未指定的大型忽略目录导致超时的问题 ([#10020](https://github.com/getpaseo/paseo/pull/10020),贡献者:[@mgranderath](https://github.com/mgranderath))
|
||||
- 修复发送引导消息时取消 Claude 正在进行的上下文压缩的问题 ([#10028](https://github.com/getpaseo/paseo/pull/10028),贡献者:[@NightMachinery](https://github.com/NightMachinery))
|
||||
- 修复 Provider 重用已取消的轮次 ID 时,再次停止导致 Agent 卡住的问题 ([#9774](https://github.com/getpaseo/paseo/pull/9774),贡献者:[@DAnaeto](https://github.com/DAnaeto))
|
||||
- 修复 Desktop 渲染进程意外退出后窗口一直空白的问题 ([#10035](https://github.com/getpaseo/paseo/pull/10035))
|
||||
- 修复 Web 和 Desktop 上文件下载失败时,错误页面占据应用窗口的问题 ([#9937](https://github.com/getpaseo/paseo/pull/9937),贡献者:[@panta82](https://github.com/panta82))
|
||||
- 修复在“导入会话”中选择“加载更多”时丢失滚动位置的问题 ([#9974](https://github.com/getpaseo/paseo/pull/9974))
|
||||
- 修复主目录所在的文件系统拒绝 Unix 套接字时无法打开终端的问题,例如 AFS ([#9214](https://github.com/getpaseo/paseo/pull/9214),贡献者:[@bendavid](https://github.com/bendavid))
|
||||
- 修复 Git 监视器设置超时后反复扫描大型仓库的问题 ([#9828](https://github.com/getpaseo/paseo/pull/9828),贡献者:[@Spshulem](https://github.com/Spshulem))
|
||||
- 修复 `paseo workspace create --path .` 使用本地 daemon 的目录而非命令所在目录的问题 ([#10010](https://github.com/getpaseo/paseo/pull/10010))
|
||||
- 修复针对空闲 Agent 查询 MCP 状态或列表时漏报后台任务的问题 ([#10022](https://github.com/getpaseo/paseo/pull/10022),贡献者:[@ortschun](https://github.com/ortschun))
|
||||
- 修复 OMP 更改思考级别后,选择器仍显示旧级别的问题 ([#9841](https://github.com/getpaseo/paseo/pull/9841),贡献者:[@dsingal0](https://github.com/dsingal0))
|
||||
|
||||
## 0.16.1 - 2026-11-17
|
||||
|
||||
### 修复
|
||||
|
||||
- 修复 `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))
|
||||
|
||||
@@ -150,13 +150,12 @@ Users can also detach an existing subagent from the subagents track. Detach is d
|
||||
|
||||
`notifyOnFinish` defaults to `true` for agent-scoped creation and prompt follow-ups because most delegated work needs to report back to the creating agent. Set it to `false` for explicit reporting or no completion callback.
|
||||
|
||||
Agent-originated messages and automatic notifications share a recipient-daemon delivery module. A queued receipt acknowledges admission before provider dispatch. Idle recipients retain the two-second quiet window. While a recipient has a running or starting turn (including compaction), messages stay queued across quiet windows and are delivered together after that turn settles, including failure or cancellation. A ready batch is released when the daemon observes the recipient settle; the two-second timer also retries it. Agent callers using `steer`, including the default, wait for the turn to end; only explicit `interrupt` replaces a running turn. An explicit interrupt or a command the provider accepts out of band runs before earlier queued messages. Those messages stay queued and are delivered after the running or replacement turn ends. Human prompts dispatch directly with their existing behavior. Conflicting session-mode choices retain separate ordered dispatches.
|
||||
Agent-originated messages and automatic notifications share a recipient-daemon delivery module. A queued receipt acknowledges admission before provider dispatch, allowing a child to report and finish in the same two-second quiet window. Human prompts dispatch directly. Conflicting explicit interruption or session-mode choices retain separate ordered dispatches.
|
||||
|
||||
The pending message window is in memory. Clean shutdown flushes it before closing agents; an abrupt
|
||||
crash can lose queued prompts. A durable send receipt remains pending until actual dispatch
|
||||
acknowledgment, so a lost window never becomes a completed receipt. Completion waits cover queued
|
||||
admission within their original timeout and cancellation scope, and return permission checkpoints
|
||||
while messages are waiting.
|
||||
admission within their original timeout and cancellation scope.
|
||||
|
||||
Finish notification intent has a separate daemon-owned lifetime. The finish-subscriptions module
|
||||
persists caller, child, host, and ownership policy through an injectable store; its JSON adapter uses
|
||||
|
||||
@@ -506,5 +506,5 @@ Agent and terminal environments are unchanged. System proxy settings and SOCKS-o
|
||||
## Deployment models
|
||||
|
||||
1. **Local daemon** (default): `paseo daemon start` on `127.0.0.1:6767`
|
||||
2. **Managed desktop**: Electron uses the server package’s local-instance lifecycle capability for sanitized launch, published readiness, and captured-PID stop. Only a matching `{pid, startedAt}` from a spawn in the current Desktop session authorizes automatic stop or binary replacement. Preexisting instances, including legacy `desktopManaged` records, are attach-only. Keep-running survivors attach in the next session. Explicit attached Stop requires a confirmation naming the captured home/PID. Ordinary Restart uses the worker RPC on every app platform.
|
||||
2. **Managed desktop**: Electron uses the server package’s local-instance lifecycle capability for sanitized launch, published readiness, and captured-PID stop. Only Desktop's own launch writes `desktopManaged: true` to `paseo.pid`. The CLI launch path removes the flag. While Desktop manages the built-in daemon, an app update or a version mismatch replaces any `desktopManaged` daemon, including one that an earlier Desktop session left running. Bundled CLIs before v0.9.0 exported the flag, so a daemon that one of them started also carries it and is replaced. Quit, Settings, and host removal stop only a daemon that the current session launched, matched by `{pid, startedAt}`. A daemon that the user started through the CLI is attach-only. Explicit attached Stop requires a confirmation naming the captured home/PID. Ordinary Restart uses the worker RPC on every app platform.
|
||||
3. **Remote + relay**: Daemon behind firewall, relay bridges with E2E encryption
|
||||
|
||||
@@ -590,6 +590,16 @@ bookkeeping may scan opaque row sizes during a deferred write, never during host
|
||||
before a requested cache row can paint. The row store is not encrypted. A cached timeline can contain
|
||||
source code, prompts, and tool output; encrypted-at-rest storage is a separate security decision.
|
||||
|
||||
### Saved hosts
|
||||
|
||||
**AsyncStorage key:** `@paseo:daemon-registry`, an array of host profiles.
|
||||
|
||||
Every app build on a device shares this key, including an older build after a downgrade and a newer
|
||||
one that saves a connection kind this build doesn't know. The key holds every saved host and its
|
||||
password, so never remove it. Read each host and connection on its own, skip the ones this build
|
||||
can't read, and write them back on every save. A value that isn't a JSON array is copied to
|
||||
`@paseo:daemon-registry:unreadable` before the next save overwrites it.
|
||||
|
||||
### Draft Store
|
||||
|
||||
**AsyncStorage key:** `paseo-drafts` (version 2)
|
||||
|
||||
+1
-1
@@ -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 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.
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
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
|
||||
@@ -0,0 +1,6 @@
|
||||
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
|
||||
@@ -0,0 +1,6 @@
|
||||
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
|
||||
@@ -0,0 +1,6 @@
|
||||
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
|
||||
@@ -0,0 +1,8 @@
|
||||
Fixed
|
||||
- Fixed Collapse turns hiding a finished reply when Claude answers a later background task notification
|
||||
- Fixed detached worktree commits getting lost when archiving a workspace
|
||||
- Fixed Desktop updates leaving an older daemon running when an earlier Desktop session started it
|
||||
- Fixed daemons losing their Hub connection after execution permissions changed
|
||||
- Fixed saved hosts disappearing when one stored entry could not be read
|
||||
|
||||
Full notes: https://paseo.sh/changelog
|
||||
@@ -0,0 +1,8 @@
|
||||
Fixed
|
||||
- Fixed Collapse turns hiding a finished reply when Claude answers a later background task notification
|
||||
- Fixed detached worktree commits getting lost when archiving a workspace
|
||||
- Fixed Desktop updates leaving an older daemon running when an earlier Desktop session started it
|
||||
- Fixed daemons losing their Hub connection after execution permissions changed
|
||||
- Fixed saved hosts disappearing when one stored entry could not be read
|
||||
|
||||
Full notes: https://paseo.sh/changelog
|
||||
@@ -0,0 +1,8 @@
|
||||
Fixed
|
||||
- Fixed Collapse turns hiding a finished reply when Claude answers a later background task notification
|
||||
- Fixed detached worktree commits getting lost when archiving a workspace
|
||||
- Fixed Desktop updates leaving an older daemon running when an earlier Desktop session started it
|
||||
- Fixed daemons losing their Hub connection after execution permissions changed
|
||||
- Fixed saved hosts disappearing when one stored entry could not be read
|
||||
|
||||
Full notes: https://paseo.sh/changelog
|
||||
@@ -0,0 +1,8 @@
|
||||
Fixed
|
||||
- Fixed Collapse turns hiding a finished reply when Claude answers a later background task notification
|
||||
- Fixed detached worktree commits getting lost when archiving a workspace
|
||||
- Fixed Desktop updates leaving an older daemon running when an earlier Desktop session started it
|
||||
- Fixed daemons losing their Hub connection after execution permissions changed
|
||||
- Fixed saved hosts disappearing when one stored entry could not be read
|
||||
|
||||
Full notes: https://paseo.sh/changelog
|
||||
+1
-1
@@ -1 +1 @@
|
||||
sha256-alhf4ULeJ7n8sfgnxsX8Ugw40GB7jz0u9R/3/MOveIw=
|
||||
sha256-hN+Klz3jXugHs5MsVzIQIwIa/HGbpdJ04qolKvbsOuk=
|
||||
|
||||
Generated
+65
-65
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "paseo",
|
||||
"version": "0.16.0",
|
||||
"version": "0.16.2",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "paseo",
|
||||
"version": "0.16.0",
|
||||
"version": "0.16.2",
|
||||
"hasInstallScript": true,
|
||||
"license": "Apache-2.0",
|
||||
"workspaces": [
|
||||
@@ -130,22 +130,22 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@anthropic-ai/claude-agent-sdk": {
|
||||
"version": "0.3.246",
|
||||
"resolved": "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk/-/claude-agent-sdk-0.3.246.tgz",
|
||||
"integrity": "sha512-FtR0HoHHNqeqJWjZN8qLUAzZVFUI9ztXYNPPwv98Ecmv9qq2QTauI8IzkY26CC0mleWAqb9RQEW2C0OtiUliug==",
|
||||
"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==",
|
||||
"license": "SEE LICENSE IN README.md",
|
||||
"engines": {
|
||||
"node": ">=18.0.0"
|
||||
"node": ">=18.14.0"
|
||||
},
|
||||
"optionalDependencies": {
|
||||
"@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"
|
||||
"@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"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@anthropic-ai/sdk": ">=0.93.0",
|
||||
@@ -154,9 +154,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@anthropic-ai/claude-agent-sdk-darwin-arm64": {
|
||||
"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==",
|
||||
"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==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
@@ -167,9 +167,9 @@
|
||||
]
|
||||
},
|
||||
"node_modules/@anthropic-ai/claude-agent-sdk-darwin-x64": {
|
||||
"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==",
|
||||
"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==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
@@ -180,9 +180,9 @@
|
||||
]
|
||||
},
|
||||
"node_modules/@anthropic-ai/claude-agent-sdk-linux-arm64": {
|
||||
"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==",
|
||||
"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==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
@@ -193,9 +193,9 @@
|
||||
]
|
||||
},
|
||||
"node_modules/@anthropic-ai/claude-agent-sdk-linux-arm64-musl": {
|
||||
"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==",
|
||||
"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==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
@@ -206,9 +206,9 @@
|
||||
]
|
||||
},
|
||||
"node_modules/@anthropic-ai/claude-agent-sdk-linux-x64": {
|
||||
"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==",
|
||||
"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==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
@@ -219,9 +219,9 @@
|
||||
]
|
||||
},
|
||||
"node_modules/@anthropic-ai/claude-agent-sdk-linux-x64-musl": {
|
||||
"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==",
|
||||
"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==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
@@ -232,9 +232,9 @@
|
||||
]
|
||||
},
|
||||
"node_modules/@anthropic-ai/claude-agent-sdk-win32-arm64": {
|
||||
"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==",
|
||||
"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==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
@@ -245,9 +245,9 @@
|
||||
]
|
||||
},
|
||||
"node_modules/@anthropic-ai/claude-agent-sdk-win32-x64": {
|
||||
"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==",
|
||||
"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==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
@@ -37468,7 +37468,7 @@
|
||||
},
|
||||
"packages/app": {
|
||||
"name": "@getpaseo/app",
|
||||
"version": "0.16.0",
|
||||
"version": "0.16.2",
|
||||
"dependencies": {
|
||||
"@codemirror/commands": "6.10.4",
|
||||
"@codemirror/language": "6.12.4",
|
||||
@@ -39637,13 +39637,13 @@
|
||||
},
|
||||
"packages/cli": {
|
||||
"name": "@getpaseo/cli",
|
||||
"version": "0.16.0",
|
||||
"version": "0.16.2",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@clack/prompts": "^1.0.0",
|
||||
"@getpaseo/client": "0.16.0",
|
||||
"@getpaseo/protocol": "0.16.0",
|
||||
"@getpaseo/server": "0.16.0",
|
||||
"@getpaseo/client": "0.16.2",
|
||||
"@getpaseo/protocol": "0.16.2",
|
||||
"@getpaseo/server": "0.16.2",
|
||||
"chalk": "^5.3.0",
|
||||
"commander": "^12.0.0",
|
||||
"mime-types": "^2.1.35",
|
||||
@@ -39890,11 +39890,11 @@
|
||||
},
|
||||
"packages/client": {
|
||||
"name": "@getpaseo/client",
|
||||
"version": "0.16.0",
|
||||
"version": "0.16.2",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@getpaseo/protocol": "0.16.0",
|
||||
"@getpaseo/relay": "0.16.0",
|
||||
"@getpaseo/protocol": "0.16.2",
|
||||
"@getpaseo/relay": "0.16.2",
|
||||
"ws": "^8.20.0",
|
||||
"zod": "^4.4.3"
|
||||
},
|
||||
@@ -39906,7 +39906,7 @@
|
||||
},
|
||||
"packages/desktop": {
|
||||
"name": "@getpaseo/desktop",
|
||||
"version": "0.16.0",
|
||||
"version": "0.16.2",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@getpaseo/cli": "*",
|
||||
@@ -40149,7 +40149,7 @@
|
||||
},
|
||||
"packages/expo-two-way-audio": {
|
||||
"name": "@getpaseo/expo-two-way-audio",
|
||||
"version": "0.16.0",
|
||||
"version": "0.16.2",
|
||||
"license": "MIT",
|
||||
"devDependencies": {
|
||||
"@types/jest": "^29.5.14",
|
||||
@@ -40195,7 +40195,7 @@
|
||||
},
|
||||
"packages/highlight": {
|
||||
"name": "@getpaseo/highlight",
|
||||
"version": "0.16.0",
|
||||
"version": "0.16.2",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@codemirror/language": "6.12.4",
|
||||
@@ -40225,7 +40225,7 @@
|
||||
},
|
||||
"packages/plugin": {
|
||||
"name": "@getpaseo/plugin",
|
||||
"version": "0.16.0",
|
||||
"version": "0.16.2",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@agentclientprotocol/sdk": "^1.4.0",
|
||||
@@ -40233,8 +40233,8 @@
|
||||
"use-sync-external-store": "^1.6.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@getpaseo/client": "0.16.0",
|
||||
"@getpaseo/protocol": "0.16.0",
|
||||
"@getpaseo/client": "0.16.2",
|
||||
"@getpaseo/protocol": "0.16.2",
|
||||
"@types/node": "^20.9.0",
|
||||
"@types/react": "~19.2.0",
|
||||
"react": "19.2.3",
|
||||
@@ -40244,8 +40244,8 @@
|
||||
"zod": "^4.4.3"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@getpaseo/client": "0.16.0",
|
||||
"@getpaseo/protocol": "0.16.0",
|
||||
"@getpaseo/client": "0.16.2",
|
||||
"@getpaseo/protocol": "0.16.2",
|
||||
"react": ">=19.1.0 <20",
|
||||
"react-native": ">=0.81.5",
|
||||
"zod": "^4.4.3"
|
||||
@@ -40267,7 +40267,7 @@
|
||||
},
|
||||
"packages/protocol": {
|
||||
"name": "@getpaseo/protocol",
|
||||
"version": "0.16.0",
|
||||
"version": "0.16.2",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"semver": "^7.8.5",
|
||||
@@ -40295,7 +40295,7 @@
|
||||
},
|
||||
"packages/relay": {
|
||||
"name": "@getpaseo/relay",
|
||||
"version": "0.16.0",
|
||||
"version": "0.16.2",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@noble/ciphers": "^2.4.0",
|
||||
@@ -40517,17 +40517,17 @@
|
||||
},
|
||||
"packages/server": {
|
||||
"name": "@getpaseo/server",
|
||||
"version": "0.16.0",
|
||||
"version": "0.16.2",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@agentclientprotocol/sdk": "^0.17.1",
|
||||
"@anthropic-ai/claude-agent-sdk": "0.3.246",
|
||||
"@anthropic-ai/claude-agent-sdk": "0.3.326",
|
||||
"@anthropic-ai/sdk": "^0.104.2",
|
||||
"@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",
|
||||
"@getpaseo/client": "0.16.2",
|
||||
"@getpaseo/highlight": "0.16.2",
|
||||
"@getpaseo/plugin": "0.16.2",
|
||||
"@getpaseo/protocol": "0.16.2",
|
||||
"@getpaseo/relay": "0.16.2",
|
||||
"@isaacs/ttlcache": "^2.1.4",
|
||||
"@modelcontextprotocol/sdk": "1.29.0",
|
||||
"@opencode-ai/sdk": "1.14.46",
|
||||
@@ -41474,7 +41474,7 @@
|
||||
},
|
||||
"packages/website": {
|
||||
"name": "@getpaseo/website",
|
||||
"version": "0.16.0",
|
||||
"version": "0.16.2",
|
||||
"dependencies": {
|
||||
"@cloudflare/vite-plugin": "^1.29.1",
|
||||
"@cloudflare/workers-types": "^4.20260317.1",
|
||||
@@ -43084,7 +43084,7 @@
|
||||
},
|
||||
"plugins": {
|
||||
"name": "@getpaseo/builtin-plugins",
|
||||
"version": "0.16.0",
|
||||
"version": "0.16.2",
|
||||
"dependencies": {
|
||||
"@getpaseo/plugin": "*",
|
||||
"zod": "^4.4.3"
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "paseo",
|
||||
"version": "0.16.0",
|
||||
"version": "0.16.2",
|
||||
"private": true,
|
||||
"description": "Paseo: voice-controlled development environment for local AI coding agents",
|
||||
"keywords": [
|
||||
|
||||
@@ -466,12 +466,12 @@ test("downloads a file over direct TCP with its original filename and bytes", as
|
||||
await gotoWorkspace(page, workspace.workspaceId);
|
||||
await openFileExplorer(page);
|
||||
|
||||
const daemonRequest = page.waitForRequest("**/api/files/download?*");
|
||||
const downloaded = await downloadFileFromExplorer(page, fileName);
|
||||
const url = new URL(downloaded.url());
|
||||
expect(url.protocol).toBe("http:");
|
||||
expect(url.port).toBe(getE2EDaemonPort());
|
||||
expect(url.pathname).toBe("/api/files/download");
|
||||
expect(url.searchParams.get("token")).toBeTruthy();
|
||||
const requestUrl = new URL((await daemonRequest).url());
|
||||
expect(requestUrl.port).toBe(getE2EDaemonPort());
|
||||
expect(requestUrl.searchParams.get("token")).toBeTruthy();
|
||||
expect(new URL(downloaded.url()).protocol).toBe("blob:");
|
||||
expect(downloaded.suggestedFilename()).toBe(fileName);
|
||||
const savedFile = testInfo.outputPath(fileName);
|
||||
await downloaded.saveAs(savedFile);
|
||||
@@ -479,6 +479,45 @@ test("downloads a file over direct TCP with its original filename and bytes", as
|
||||
expect(await readFile(savedFile)).toEqual(source);
|
||||
});
|
||||
|
||||
test("keeps the app open and shows the error when the host rejects a download", async ({
|
||||
page,
|
||||
}, testInfo) => {
|
||||
const fileName = "removed-during-download.bin";
|
||||
const filePath = path.join(workspace.workspaceDirectory, fileName);
|
||||
const source = Buffer.from([0, 1, 2, 255]);
|
||||
await writeFile(filePath, source);
|
||||
await gotoWorkspace(page, workspace.workspaceId);
|
||||
await openFileExplorer(page);
|
||||
const workspaceUrl = page.url();
|
||||
|
||||
// The file disappears after the token is issued, so the real daemon answers 404.
|
||||
await page.route(
|
||||
"**/api/files/download?*",
|
||||
async (route) => {
|
||||
await rm(filePath);
|
||||
await route.continue();
|
||||
},
|
||||
{ times: 1 },
|
||||
);
|
||||
await page
|
||||
.getByTestId("file-explorer-tree-scroll")
|
||||
.getByText(fileName, { exact: true })
|
||||
.click({ button: "right" });
|
||||
await page.getByRole("menuitem", { name: "Download", exact: true }).click();
|
||||
|
||||
await expect(
|
||||
page.getByText("Failed to download file (HTTP 404).", { exact: true }),
|
||||
).toBeVisible();
|
||||
expect(page.url()).toBe(workspaceUrl);
|
||||
|
||||
await writeFile(filePath, source);
|
||||
const downloaded = await downloadFileFromExplorer(page, fileName);
|
||||
const savedFile = testInfo.outputPath(fileName);
|
||||
await downloaded.saveAs(savedFile);
|
||||
expect(await readFile(savedFile)).toEqual(source);
|
||||
expect(page.url()).toBe(workspaceUrl);
|
||||
});
|
||||
|
||||
test("downloads an unsupported binary from its preview with original filename and bytes", async ({
|
||||
page,
|
||||
}, testInfo) => {
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
import { expect, type Page } from "@playwright/test";
|
||||
import { test } from "../support/fixtures";
|
||||
import { gotoAppShell, openSettings } from "../support/helpers/app";
|
||||
import { renameHostFromSettings } from "../support/helpers/hosts";
|
||||
import { getServerId } from "../support/helpers/server-id";
|
||||
import { openHostSection, selectSettingsHost } from "../support/helpers/settings";
|
||||
|
||||
const REGISTRY_KEY = "@paseo:daemon-registry";
|
||||
const SEED_NONCE_KEY = "@paseo:e2e-seed-nonce";
|
||||
const DISABLE_DEFAULT_SEED_ONCE_KEY = "@paseo:e2e-disable-default-seed-once";
|
||||
|
||||
// What a build with a connection kind this one doesn't know leaves in the registry: an extra
|
||||
// connection on a host this build can reach, and a host reached only through it.
|
||||
const UNKNOWN_CONNECTION = { id: "future:garage", type: "futureKind", address: "garage" };
|
||||
const UNKNOWN_HOST = {
|
||||
serverId: "srv_e2e_unknown_connection_host",
|
||||
label: "Unknown connection host",
|
||||
connections: [{ id: "future:roof", type: "futureKind", address: "roof" }],
|
||||
preferredConnectionId: "future:roof",
|
||||
};
|
||||
const OFFLINE_HOST = {
|
||||
serverId: "srv_e2e_saved_offline_host",
|
||||
label: "Saved offline host",
|
||||
password: "e2e-fake-password",
|
||||
connections: [{ id: "direct:127.0.0.1:59999", type: "directTcp", endpoint: "127.0.0.1:59999" }],
|
||||
preferredConnectionId: "direct:127.0.0.1:59999",
|
||||
};
|
||||
|
||||
interface StoredHost {
|
||||
serverId: string;
|
||||
label?: string;
|
||||
password?: string;
|
||||
connections: unknown[];
|
||||
}
|
||||
|
||||
async function addUnreadableEntriesAndReload(page: Page): Promise<void> {
|
||||
await page.evaluate(
|
||||
({ keys, primaryServerId, unknownConnection, offlineHost, unknownHost }) => {
|
||||
const nonce = localStorage.getItem(keys.nonce);
|
||||
if (!nonce) {
|
||||
throw new Error("Expected the e2e seed nonce before overriding the host registry.");
|
||||
}
|
||||
const registry: StoredHost[] = JSON.parse(localStorage.getItem(keys.registry) ?? "[]");
|
||||
registry
|
||||
.find((host) => host.serverId === primaryServerId)
|
||||
?.connections.push(unknownConnection);
|
||||
registry.push(offlineHost, unknownHost);
|
||||
localStorage.setItem(keys.registry, JSON.stringify(registry));
|
||||
localStorage.setItem(keys.disableSeedOnce, nonce);
|
||||
},
|
||||
{
|
||||
keys: {
|
||||
registry: REGISTRY_KEY,
|
||||
nonce: SEED_NONCE_KEY,
|
||||
disableSeedOnce: DISABLE_DEFAULT_SEED_ONCE_KEY,
|
||||
},
|
||||
primaryServerId: getServerId(),
|
||||
unknownConnection: UNKNOWN_CONNECTION,
|
||||
offlineHost: OFFLINE_HOST,
|
||||
unknownHost: UNKNOWN_HOST,
|
||||
},
|
||||
);
|
||||
await page.reload();
|
||||
}
|
||||
|
||||
async function readStoredRegistry(page: Page): Promise<StoredHost[] | null> {
|
||||
return page.evaluate((key) => JSON.parse(localStorage.getItem(key) ?? "null"), REGISTRY_KEY);
|
||||
}
|
||||
|
||||
async function readStoredHost(page: Page, serverId: string): Promise<StoredHost | undefined> {
|
||||
return (await readStoredRegistry(page))?.find((host) => host.serverId === serverId);
|
||||
}
|
||||
|
||||
test("saved hosts survive a registry entry this build can't read, and saving keeps it", async ({
|
||||
page,
|
||||
}) => {
|
||||
await gotoAppShell(page);
|
||||
await addUnreadableEntriesAndReload(page);
|
||||
|
||||
await test.step("both readable hosts are listed", async () => {
|
||||
await page.getByTestId("sidebar-hosts-trigger").click();
|
||||
await expect(page.getByTestId(`sidebar-host-row-${getServerId()}`)).toBeVisible();
|
||||
await expect(page.getByTestId(`sidebar-host-row-${OFFLINE_HOST.serverId}`)).toBeVisible();
|
||||
await expect(page.getByTestId(`sidebar-host-row-${UNKNOWN_HOST.serverId}`)).toHaveCount(0);
|
||||
await page.keyboard.press("Escape");
|
||||
});
|
||||
|
||||
await test.step("renaming a host keeps its password and the entries it can't read", async () => {
|
||||
await openSettings(page);
|
||||
await selectSettingsHost(page, OFFLINE_HOST.serverId);
|
||||
await openHostSection(page, OFFLINE_HOST.serverId, "host");
|
||||
await renameHostFromSettings(page, "Renamed offline host");
|
||||
|
||||
await expect
|
||||
.poll(() => readStoredHost(page, OFFLINE_HOST.serverId))
|
||||
.toMatchObject({ label: "Renamed offline host", password: OFFLINE_HOST.password });
|
||||
const stored = await readStoredRegistry(page);
|
||||
expect(stored?.map((host) => host.serverId)).toEqual([
|
||||
getServerId(),
|
||||
OFFLINE_HOST.serverId,
|
||||
UNKNOWN_HOST.serverId,
|
||||
]);
|
||||
expect(stored?.[0]?.connections).toContainEqual(UNKNOWN_CONNECTION);
|
||||
expect(stored?.[2]).toEqual(UNKNOWN_HOST);
|
||||
});
|
||||
});
|
||||
@@ -33,6 +33,8 @@ import {
|
||||
expectNoHostPasswordControls,
|
||||
removeHostFromHostPage,
|
||||
addDirectHostFromSettings,
|
||||
expectAddHostFieldDrawnAsInput,
|
||||
selectHostConnectionType,
|
||||
expectHostOnlineWithoutError,
|
||||
expectIdleAgentRelease,
|
||||
editRestartRecoveryPrompt,
|
||||
@@ -307,6 +309,24 @@ async function closeAddHostAndChangeTheme(page: import("@playwright/test").Page)
|
||||
await page.keyboard.press("Control+Alt+t");
|
||||
}
|
||||
|
||||
test("Add host draws its text fields as bordered inputs", async ({ page }) => {
|
||||
await gotoAppShell(page);
|
||||
|
||||
await test.step("the pairing link field", async () => {
|
||||
await openSidebarAddHost(page);
|
||||
await selectHostConnectionType(page, "relay");
|
||||
await expectAddHostFieldDrawnAsInput(page, "pair-link-input");
|
||||
await page.getByTestId("pair-link-cancel").click();
|
||||
});
|
||||
|
||||
await test.step("the direct connection fields", async () => {
|
||||
await selectHostConnectionType(page, "direct");
|
||||
await expectAddHostFieldDrawnAsInput(page, "direct-host-input");
|
||||
await expectAddHostFieldDrawnAsInput(page, "direct-port-input");
|
||||
await expectAddHostFieldDrawnAsInput(page, "direct-password-input");
|
||||
});
|
||||
});
|
||||
|
||||
test("sidebar Add host completes without navigating", async ({ page }) => {
|
||||
await gotoAppShell(page);
|
||||
await expect(page).toHaveURL(/\/open-project$/);
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
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",
|
||||
]);
|
||||
});
|
||||
@@ -361,6 +361,10 @@ test.describe("Worktree restore", () => {
|
||||
cwd: backingWorktree.workspaceDirectory,
|
||||
stdio: "pipe",
|
||||
});
|
||||
const originalHead = execFileSync("git", ["rev-parse", "HEAD"], {
|
||||
cwd: backingWorktree.workspaceDirectory,
|
||||
encoding: "utf8",
|
||||
}).trim();
|
||||
const created = await worktreeClient.createWorkspace({
|
||||
source: { kind: "directory", path: backingWorktree.workspaceDirectory },
|
||||
title: "Sample workspace",
|
||||
@@ -389,10 +393,7 @@ test.describe("Worktree restore", () => {
|
||||
await page.getByTestId(`agent-row-${getServerId()}-${agent.id}`).click();
|
||||
await expect(page.getByText("Workspace archived", { exact: true })).toBeVisible();
|
||||
await expect(
|
||||
page.getByText(
|
||||
"Restore Sample workspace to return to its agents. A new branch will start from the saved base or the repository default.",
|
||||
{ exact: true },
|
||||
),
|
||||
page.getByText("Restore Sample workspace to return to its agents.", { exact: true }),
|
||||
).toBeVisible();
|
||||
await captureBranchlessRestoreStep(page, "01-restore-workspace.png");
|
||||
|
||||
@@ -409,17 +410,13 @@ test.describe("Worktree restore", () => {
|
||||
cwd: backingWorktree.workspaceDirectory,
|
||||
encoding: "utf8",
|
||||
}).trim();
|
||||
const defaultHead = execFileSync("git", ["rev-parse", "main"], {
|
||||
cwd: tempRepo.path,
|
||||
encoding: "utf8",
|
||||
}).trim();
|
||||
expect(restoredHead).toBe(defaultHead);
|
||||
expect(restoredHead).toBe(originalHead);
|
||||
expect(
|
||||
execFileSync("git", ["branch", "--show-current"], {
|
||||
cwd: backingWorktree.workspaceDirectory,
|
||||
encoding: "utf8",
|
||||
}).trim(),
|
||||
).toMatch(/^restored\//);
|
||||
).toBe("");
|
||||
});
|
||||
|
||||
test("restore failure stays visible and permits a successful retry", async ({ page }) => {
|
||||
|
||||
@@ -97,18 +97,15 @@ export class ImportSessionFlow {
|
||||
await target.scrollIntoViewIfNeeded();
|
||||
await expect(target).toBeInViewport();
|
||||
}
|
||||
/**
|
||||
* Scrolls the virtualized list, the only one that leaves rows unmounted. A row handle is no way
|
||||
* in: the list unmounts rows as it scrolls, and a detached row has no scroller above it.
|
||||
*/
|
||||
private async scrollList(forward: boolean) {
|
||||
await this.page
|
||||
.locator('[data-testid^="import-session-session-"]')
|
||||
.first()
|
||||
.evaluate((row, advance) => {
|
||||
let element = row.parentElement;
|
||||
while (element && !["auto", "scroll"].includes(getComputedStyle(element).overflowY))
|
||||
element = element.parentElement;
|
||||
if (!element) throw new Error("Import list has no scroll owner");
|
||||
element.scrollTop = advance ? element.scrollTop + element.clientHeight * 0.8 : 0;
|
||||
element.dispatchEvent(new Event("scroll"));
|
||||
}, forward);
|
||||
await this.page.getByTestId("import-session-list").evaluate((list, advance) => {
|
||||
list.scrollTop = advance ? list.scrollTop + list.clientHeight * 0.8 : 0;
|
||||
list.dispatchEvent(new Event("scroll"));
|
||||
}, forward);
|
||||
}
|
||||
async search(query: string) {
|
||||
await this.page.getByTestId("import-session-search").fill(query);
|
||||
@@ -120,11 +117,18 @@ export class ImportSessionFlow {
|
||||
await this.page.getByTestId("import-session-search").fill("");
|
||||
await expect(this.page.getByTestId("import-session-load-more")).toBeVisible();
|
||||
}
|
||||
/** Load more keeps the reader down the list instead of sending them back to the top. */
|
||||
async loadMore() {
|
||||
await this.page.getByTestId("import-session-load-more").click();
|
||||
const loadMore = this.page.getByTestId("import-session-load-more");
|
||||
const topRow = this.page.getByTestId((await this.rowIds())[0]!);
|
||||
await expect(topRow).toBeInViewport();
|
||||
await loadMore.click();
|
||||
// The next page is the last and short, so the button leaves once it lands.
|
||||
await expect(loadMore).toHaveCount(0);
|
||||
await expect(this.page.getByText("Loading sessions...", { exact: true })).toHaveCount(0);
|
||||
await expect(topRow).not.toBeInViewport();
|
||||
await this.revealSession("fixture-root-20");
|
||||
await expect(this.page.getByText("Root session 20", { exact: true })).toBeInViewport();
|
||||
await expect(this.page.getByTestId("import-session-load-more")).toHaveCount(0);
|
||||
}
|
||||
async retryProvider(provider: string, label: string) {
|
||||
await this.expectProviderError(label);
|
||||
|
||||
@@ -121,7 +121,7 @@ export async function startIsolatedHostDaemon(
|
||||
serverId: string,
|
||||
options: IsolatedHostDaemonOptions = {},
|
||||
): Promise<IsolatedHostDaemon> {
|
||||
let port = await getAvailableHostDaemonPort();
|
||||
const port = await getAvailableHostDaemonPort();
|
||||
|
||||
const metroPort = process.env.E2E_METRO_PORT;
|
||||
if (!metroPort) throw new Error("E2E_METRO_PORT is required to start an isolated host daemon");
|
||||
@@ -231,25 +231,8 @@ export async function startIsolatedHostDaemon(
|
||||
}
|
||||
};
|
||||
|
||||
// The reserved port is released before the daemon binds it, so another
|
||||
// process can take it in between. Only the first start picks a new port:
|
||||
// restart() keeps the endpoint the app already knows.
|
||||
const startOnFreePort = async (): Promise<void> => {
|
||||
for (let attempt = 1; ; attempt += 1) {
|
||||
try {
|
||||
await spawnDaemon();
|
||||
return;
|
||||
} catch (error) {
|
||||
const lostPort = error instanceof Error && error.message.includes("EADDRINUSE");
|
||||
if (!lostPort || attempt === 3) throw error;
|
||||
await stopDaemon();
|
||||
port = await getAvailableHostDaemonPort();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
try {
|
||||
await startOnFreePort();
|
||||
await spawnDaemon();
|
||||
} catch (error) {
|
||||
await stopDaemon();
|
||||
if (!options.preserveHome) {
|
||||
|
||||
@@ -223,6 +223,14 @@ export async function addDirectHostFromSettings(
|
||||
await expect(page.getByTestId("add-host-modal")).toHaveCount(0, { timeout: 30_000 });
|
||||
}
|
||||
|
||||
export async function expectAddHostFieldDrawnAsInput(page: Page, testId: string): Promise<void> {
|
||||
const field = page.getByTestId(testId);
|
||||
await expect(field).toBeVisible();
|
||||
await expect(field).toHaveCSS("border-top-width", "1px");
|
||||
await expect(field).not.toHaveCSS("padding-left", "0px");
|
||||
await expect(field).not.toHaveCSS("background-color", "rgba(0, 0, 0, 0)");
|
||||
}
|
||||
|
||||
export async function toggleHostAdvanced(page: Page): Promise<void> {
|
||||
await page.getByTestId("direct-host-advanced-toggle").click();
|
||||
}
|
||||
|
||||
@@ -60,14 +60,8 @@ export function footerOverflowMenu(page: Page): Locator {
|
||||
return page.getByTestId("sidebar-footer-overflow-menu");
|
||||
}
|
||||
|
||||
/**
|
||||
* 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> {
|
||||
/** The icon line shows exactly `testIDs`, in order. */
|
||||
export async function expectFooterActionsInline(page: Page, testIDs: string[]): Promise<void> {
|
||||
const line = footerLine(page);
|
||||
await expect(line).toHaveCount(1);
|
||||
await expect
|
||||
@@ -76,7 +70,16 @@ export async function expectFooterLine(
|
||||
.locator(FOOTER_LINE_TEST_IDS.map((testID) => `[data-testid="${testID}"]`).join(","))
|
||||
.evaluateAll((elements) => elements.map((element) => element.getAttribute("data-testid"))),
|
||||
)
|
||||
.toEqual(input.testIDs);
|
||||
.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);
|
||||
const { row, buttons } = await line.evaluate((element, testIDs) => {
|
||||
const rect = (node: Element) => {
|
||||
const { x, width, height } = node.getBoundingClientRect();
|
||||
|
||||
@@ -1,19 +0,0 @@
|
||||
apply plugin: 'com.android.library'
|
||||
|
||||
group = 'sh.paseo.pressfeedback'
|
||||
version = '0.1.0'
|
||||
|
||||
def expoModulesCorePlugin = new File(project(":expo-modules-core").projectDir.absolutePath, "ExpoModulesCorePlugin.gradle")
|
||||
apply from: expoModulesCorePlugin
|
||||
applyKotlinExpoModulesCorePlugin()
|
||||
useCoreDependencies()
|
||||
useExpoPublishing()
|
||||
useDefaultAndroidSdkVersions()
|
||||
|
||||
android {
|
||||
namespace "sh.paseo.pressfeedback"
|
||||
defaultConfig {
|
||||
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android" />
|
||||
-39
@@ -1,39 +0,0 @@
|
||||
package sh.paseo.pressfeedback
|
||||
|
||||
import android.content.Context
|
||||
import android.graphics.Canvas
|
||||
import android.graphics.Color
|
||||
import android.graphics.Paint
|
||||
import expo.modules.kotlin.AppContext
|
||||
import expo.modules.kotlin.modules.Module
|
||||
import expo.modules.kotlin.modules.ModuleDefinition
|
||||
import expo.modules.kotlin.types.ColorCompat
|
||||
import expo.modules.kotlin.views.ExpoView
|
||||
|
||||
class PaseoPressFeedbackModule : Module() {
|
||||
override fun definition() = ModuleDefinition {
|
||||
Name("PaseoPressFeedback")
|
||||
View(PaseoPressFeedbackView::class) {
|
||||
Prop("tint") { view: PaseoPressFeedbackView, color: Color -> view.paint.color = ColorCompat.toArgb(color) }
|
||||
Prop("radius") { view: PaseoPressFeedbackView, radius: Double -> view.radius = radius.toFloat() * view.resources.displayMetrics.density }
|
||||
Prop("resetKey") { view: PaseoPressFeedbackView, key: String -> view.reset(key) }
|
||||
AsyncFunction("acknowledge") { view: PaseoPressFeedbackView -> view.acknowledge() }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class PaseoPressFeedbackView(context: Context, appContext: AppContext) : ExpoView(context, appContext) {
|
||||
val paint = Paint(Paint.ANTI_ALIAS_FLAG)
|
||||
var radius = 0f
|
||||
private var acknowledged = false
|
||||
private var resetKey = ""
|
||||
init { setWillNotDraw(false); importantForAccessibility = IMPORTANT_FOR_ACCESSIBILITY_NO }
|
||||
fun acknowledge() { acknowledged = true; invalidate() }
|
||||
fun reset(key: String) {
|
||||
if (key != resetKey) { resetKey = key; acknowledged = false; invalidate() }
|
||||
}
|
||||
override fun onDraw(canvas: Canvas) {
|
||||
super.onDraw(canvas)
|
||||
if (acknowledged) canvas.drawRoundRect(0f, 0f, width.toFloat(), height.toFloat(), radius, radius, paint)
|
||||
}
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
{
|
||||
"platforms": ["android", "ios"],
|
||||
"android": { "modules": ["sh.paseo.pressfeedback.PaseoPressFeedbackModule"] },
|
||||
"ios": { "modules": ["PaseoPressFeedbackModule"] }
|
||||
}
|
||||
@@ -1 +0,0 @@
|
||||
export { useWorkspaceRowPress } from "./src/ui";
|
||||
@@ -1,22 +0,0 @@
|
||||
Pod::Spec.new do |s|
|
||||
s.name = 'PaseoPressFeedback'
|
||||
s.version = '0.1.0'
|
||||
s.summary = 'Native accepted press feedback for Paseo'
|
||||
s.description = 'Paints accepted press feedback independently of React commits'
|
||||
s.license = 'Apache-2.0'
|
||||
s.author = 'Paseo'
|
||||
s.homepage = 'https://paseo.sh'
|
||||
s.platforms = { :ios => '15.1' }
|
||||
s.swift_version = '5.4'
|
||||
s.source = { :path => '.' }
|
||||
s.static_framework = true
|
||||
|
||||
s.dependency 'ExpoModulesCore'
|
||||
|
||||
s.pod_target_xcconfig = {
|
||||
'DEFINES_MODULE' => 'YES',
|
||||
'SWIFT_COMPILATION_MODE' => 'wholemodule'
|
||||
}
|
||||
|
||||
s.source_files = "**/*.{h,m,swift}"
|
||||
end
|
||||
@@ -1,33 +0,0 @@
|
||||
import ExpoModulesCore
|
||||
import UIKit
|
||||
|
||||
public class PaseoPressFeedbackModule: Module {
|
||||
public func definition() -> ModuleDefinition {
|
||||
Name("PaseoPressFeedback")
|
||||
View(PaseoPressFeedbackView.self) {
|
||||
Prop("tint") { (view: PaseoPressFeedbackView, color: UIColor) in view.tint = color }
|
||||
Prop("radius") { (view: PaseoPressFeedbackView, radius: Double) in view.radius = radius }
|
||||
Prop("resetKey") { (view: PaseoPressFeedbackView, key: String) in view.reset(key) }
|
||||
AsyncFunction("acknowledge") { (view: PaseoPressFeedbackView) in view.acknowledge() }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
final class PaseoPressFeedbackView: ExpoView {
|
||||
var tint = UIColor.clear
|
||||
var radius: Double = 0
|
||||
private var acknowledged = false
|
||||
private var resetKey = ""
|
||||
required init(appContext: AppContext? = nil) {
|
||||
super.init(appContext: appContext)
|
||||
isOpaque = false
|
||||
isUserInteractionEnabled = false
|
||||
}
|
||||
func acknowledge() { acknowledged = true; setNeedsDisplay() }
|
||||
func reset(_ key: String) {
|
||||
if key != resetKey { resetKey = key; acknowledged = false; setNeedsDisplay() }
|
||||
}
|
||||
override func draw(_ rect: CGRect) {
|
||||
if acknowledged { tint.setFill(); UIBezierPath(roundedRect: bounds, cornerRadius: radius).fill() }
|
||||
}
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
{
|
||||
"name": "paseo-press-feedback",
|
||||
"version": "0.1.0",
|
||||
"private": true
|
||||
}
|
||||
@@ -1,104 +0,0 @@
|
||||
import { expect, it } from "vitest";
|
||||
import { acceptWorkspaceRowPress, type WorkspaceRowPress } from "./accept";
|
||||
|
||||
function rowPress(overrides: Partial<WorkspaceRowPress> = {}) {
|
||||
const visible: string[] = [];
|
||||
const press: WorkspaceRowPress = {
|
||||
cancelled: false,
|
||||
native: true,
|
||||
selected: false,
|
||||
sidebar: "overlay",
|
||||
target: "agent-list",
|
||||
acknowledge: () => visible.push("row"),
|
||||
navigate: () => visible.push("workspace"),
|
||||
...overrides,
|
||||
};
|
||||
return { press, visible };
|
||||
}
|
||||
|
||||
it("acknowledges an accepted row before navigation starts", () => {
|
||||
const { press, visible } = rowPress();
|
||||
expect(acceptWorkspaceRowPress(press)).toBe(true);
|
||||
expect(visible).toEqual(["row", "workspace"]);
|
||||
});
|
||||
|
||||
it("does not acknowledge or navigate after scrolling or a long press claims the touch", () => {
|
||||
const { press, visible } = rowPress({ cancelled: true });
|
||||
expect(acceptWorkspaceRowPress(press)).toBe(false);
|
||||
expect(visible).toEqual([]);
|
||||
});
|
||||
|
||||
it("accepts only the first row while its selection closes the sidebar", () => {
|
||||
const { press, visible } = rowPress();
|
||||
press.navigate = () => {
|
||||
press.target = "agent";
|
||||
visible.push("workspace B");
|
||||
};
|
||||
expect(acceptWorkspaceRowPress(press)).toBe(true);
|
||||
expect(acceptWorkspaceRowPress(press)).toBe(false);
|
||||
expect(visible).toEqual(["row", "workspace B"]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
{
|
||||
name: "open phone or tablet overlay",
|
||||
sidebar: "overlay",
|
||||
target: "agent-list",
|
||||
native: true,
|
||||
accepted: true,
|
||||
},
|
||||
{ name: "closing overlay", sidebar: "overlay", target: "agent", native: true, accepted: false },
|
||||
{
|
||||
name: "explorer covering an overlay",
|
||||
sidebar: "overlay",
|
||||
target: "file-explorer",
|
||||
native: true,
|
||||
accepted: false,
|
||||
},
|
||||
{ name: "docked sidebar", sidebar: "dock", target: "agent", native: true, accepted: true },
|
||||
{
|
||||
name: "docked sidebar beside explorer",
|
||||
sidebar: "dock",
|
||||
target: "file-explorer",
|
||||
native: true,
|
||||
accepted: true,
|
||||
},
|
||||
{ name: "hidden sidebar", sidebar: "hidden", target: "agent", native: true, accepted: false },
|
||||
{
|
||||
name: "suspended open overlay",
|
||||
sidebar: "suspended",
|
||||
target: "agent-list",
|
||||
native: true,
|
||||
accepted: true,
|
||||
},
|
||||
{
|
||||
name: "suspended closed overlay",
|
||||
sidebar: "suspended",
|
||||
target: "agent",
|
||||
native: true,
|
||||
accepted: false,
|
||||
},
|
||||
{
|
||||
name: "web sidebar independent of native panel target",
|
||||
sidebar: "overlay",
|
||||
target: "agent",
|
||||
native: false,
|
||||
accepted: true,
|
||||
},
|
||||
] as const)("uses the panel state for $name", ({ accepted, name: _, ...state }) => {
|
||||
const { press, visible } = rowPress(state);
|
||||
expect(acceptWorkspaceRowPress(press)).toBe(accepted);
|
||||
expect(visible).toEqual(accepted ? ["row", "workspace"] : []);
|
||||
});
|
||||
|
||||
it("does not leave an acknowledgement over an already selected docked row", () => {
|
||||
const { press, visible } = rowPress({ selected: true, sidebar: "dock", target: "agent" });
|
||||
expect(acceptWorkspaceRowPress(press)).toBe(true);
|
||||
expect(visible).toEqual(["workspace"]);
|
||||
});
|
||||
|
||||
it("still acknowledges a selected overlay row before the sidebar leaves", () => {
|
||||
const { press, visible } = rowPress({ selected: true });
|
||||
expect(acceptWorkspaceRowPress(press)).toBe(true);
|
||||
expect(visible).toEqual(["row", "workspace"]);
|
||||
});
|
||||
@@ -1,20 +0,0 @@
|
||||
import type { LeftSidebarPresentation, MobilePanelView } from "@/stores/panel-store";
|
||||
|
||||
export interface WorkspaceRowPress {
|
||||
cancelled: boolean;
|
||||
native: boolean;
|
||||
selected: boolean;
|
||||
sidebar: LeftSidebarPresentation;
|
||||
target: MobilePanelView;
|
||||
acknowledge(): void;
|
||||
navigate(): void;
|
||||
}
|
||||
|
||||
export function acceptWorkspaceRowPress(press: WorkspaceRowPress): boolean {
|
||||
if (press.cancelled) return false;
|
||||
if (press.native && press.sidebar !== "dock" && press.target !== "agent-list") return false;
|
||||
// A selected docked row neither changes selection nor leaves the screen to clear the fill.
|
||||
if (!press.selected || press.sidebar !== "dock") press.acknowledge();
|
||||
press.navigate();
|
||||
return true;
|
||||
}
|
||||
@@ -1,47 +0,0 @@
|
||||
import { requireNativeView } from "expo";
|
||||
import { type Ref } from "react";
|
||||
import { usePanelStore } from "@/stores/panel-store";
|
||||
import { withUnistyles } from "react-native-unistyles";
|
||||
import { View, StyleSheet, type ViewProps } from "react-native";
|
||||
|
||||
export interface RowFeedbackHandle {
|
||||
acknowledge(): Promise<void>;
|
||||
}
|
||||
interface FeedbackProps extends ViewProps {
|
||||
ref?: Ref<RowFeedbackHandle>;
|
||||
resetKey: string;
|
||||
tint?: string;
|
||||
radius?: number;
|
||||
}
|
||||
const NativeFeedback = withUnistyles(requireNativeView<FeedbackProps>("PaseoPressFeedback"));
|
||||
const mapTheme = (theme: import("@/styles/theme").Theme) => ({
|
||||
tint: theme.colors.interactionHighlight,
|
||||
radius: theme.borderRadius.lg,
|
||||
});
|
||||
export function RowFeedback({
|
||||
ref,
|
||||
selected,
|
||||
}: {
|
||||
ref?: Ref<RowFeedbackHandle>;
|
||||
selected: boolean;
|
||||
}) {
|
||||
const revision = usePanelStore((state) => state.mobilePanel.revision);
|
||||
// Selection takes over the fill; a new panel transition clears it before reopening.
|
||||
const resetKey = `${selected}:${revision}`;
|
||||
return (
|
||||
<View pointerEvents="none" style={styles.overlay}>
|
||||
<NativeFeedback
|
||||
ref={ref}
|
||||
resetKey={resetKey}
|
||||
pointerEvents="none"
|
||||
style={styles.fill}
|
||||
uniProps={mapTheme}
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
overlay: { position: "absolute", top: 0, right: 0, bottom: 0, left: 0 },
|
||||
fill: { flex: 1 },
|
||||
});
|
||||
@@ -1,7 +0,0 @@
|
||||
import type { Ref } from "react";
|
||||
export interface RowFeedbackHandle {
|
||||
acknowledge(): Promise<void>;
|
||||
}
|
||||
export function RowFeedback(_props: { ref?: Ref<RowFeedbackHandle>; selected: boolean }) {
|
||||
return null;
|
||||
}
|
||||
@@ -1,38 +0,0 @@
|
||||
import { useCallback, useRef, type RefObject } from "react";
|
||||
import { isNative } from "@/constants/platform";
|
||||
import { usePanelStore } from "@/stores/panel-store";
|
||||
import { acceptWorkspaceRowPress } from "../accept";
|
||||
import { RowFeedback, type RowFeedbackHandle } from "./feedback";
|
||||
|
||||
export function useWorkspaceRowPress({
|
||||
didLongPressRef,
|
||||
onPress,
|
||||
selected,
|
||||
}: {
|
||||
didLongPressRef?: RefObject<boolean>;
|
||||
onPress(): void;
|
||||
selected: boolean;
|
||||
}) {
|
||||
const feedback = useRef<RowFeedbackHandle>(null);
|
||||
const handlePress = useCallback(() => {
|
||||
const cancelled = didLongPressRef?.current ?? false;
|
||||
if (didLongPressRef) didLongPressRef.current = false;
|
||||
const panel = usePanelStore.getState();
|
||||
acceptWorkspaceRowPress({
|
||||
cancelled,
|
||||
native: isNative,
|
||||
selected,
|
||||
sidebar: panel.layout.leftSidebar,
|
||||
target: panel.mobilePanel.target,
|
||||
// Paint on the native UI thread before navigation occupies JS; never wait for paint.
|
||||
acknowledge: () => {
|
||||
void feedback.current?.acknowledge();
|
||||
},
|
||||
navigate: onPress,
|
||||
});
|
||||
}, [didLongPressRef, onPress, selected]);
|
||||
return {
|
||||
onPress: handlePress,
|
||||
feedback: <RowFeedback ref={feedback} selected={selected} />,
|
||||
};
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@getpaseo/app",
|
||||
"version": "0.16.0",
|
||||
"version": "0.16.2",
|
||||
"private": true,
|
||||
"main": "index.ts",
|
||||
"scripts": {
|
||||
|
||||
@@ -17,6 +17,11 @@ export function nextPageLimit(limit: number): number {
|
||||
return PAGE_LIMITS.find((candidate) => candidate > limit) ?? limit;
|
||||
}
|
||||
|
||||
/** The page Load more grew this limit from, or null for the first page. */
|
||||
export function previousPageLimit(limit: number): number | null {
|
||||
return PAGE_LIMITS.findLast((candidate) => candidate < limit) ?? null;
|
||||
}
|
||||
|
||||
export function requiresImportSessionsHostUpgrade(input: {
|
||||
supportsSnapshot: boolean;
|
||||
workspaceId?: string | null;
|
||||
|
||||
@@ -1172,6 +1172,44 @@ describe("ImportSessionSheet", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps the loaded list in place while Load more fetches the next page", async () => {
|
||||
let releaseNextPage: () => void = () => undefined;
|
||||
const nextPage = new Promise<void>((resolve) => {
|
||||
releaseNextPage = resolve;
|
||||
});
|
||||
const fetchRecentProviderSessions = vi.fn(async (options: { limit?: number } | undefined) => {
|
||||
if (options?.limit !== 15) await nextPage;
|
||||
return {
|
||||
requestId: "recent-provider-sessions",
|
||||
entries: createPageOfEntries(options?.limit === 15 ? 15 : 20),
|
||||
};
|
||||
});
|
||||
|
||||
renderSheet(createRecentSessionsClient(fetchRecentProviderSessions, vi.fn()), {
|
||||
cwd: null,
|
||||
snapshot: { supportsSnapshot: true, entries: [createSnapshotEntry("claude")] },
|
||||
});
|
||||
|
||||
fireEvent.click(await screen.findByTestId("import-session-load-more"));
|
||||
// The list the user scrolled to Load more is the one they keep: replacing it would drop
|
||||
// them back at the top, behind a loading state, until the larger page lands.
|
||||
const list = screen.getByTestId("import-session-list");
|
||||
await waitFor(() => {
|
||||
expect(fetchRecentProviderSessions).toHaveBeenCalledWith({
|
||||
providers: ["claude"],
|
||||
limit: 45,
|
||||
});
|
||||
});
|
||||
expect(screen.getByTestId("import-session-list")).toBe(list);
|
||||
expect(screen.queryByText("Loading sessions...")).toBeNull();
|
||||
|
||||
releaseNextPage();
|
||||
await waitFor(() => {
|
||||
expect(screen.queryByTestId("import-session-load-more")).toBeNull();
|
||||
});
|
||||
expect(screen.getByTestId("import-session-list")).toBe(list);
|
||||
});
|
||||
|
||||
it("stops the refresh spinner and retries only the failed provider", async () => {
|
||||
const fetchRecentProviderSessions = vi.fn(
|
||||
async (options: { providers?: string[] } | undefined) => {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import React, { type ReactNode, useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { Pressable, type PressableStateCallbackType, Text, View } from "react-native";
|
||||
import { keepPreviousData, useMutation, useQueries, useQueryClient } from "@tanstack/react-query";
|
||||
import { useMutation, useQueries, useQueryClient, type QueryClient } from "@tanstack/react-query";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import type {
|
||||
DaemonClient,
|
||||
@@ -40,6 +40,7 @@ import {
|
||||
resolveDirectoryLabel,
|
||||
nextPageLimit,
|
||||
PER_PROVIDER_LIMIT,
|
||||
previousPageLimit,
|
||||
type ProviderErrorRow,
|
||||
resolveImportTarget,
|
||||
resolveProvidersToFetch,
|
||||
@@ -100,11 +101,12 @@ interface SessionsQueryConfig {
|
||||
// Query's default retry would keep the header spinner turning and pile up
|
||||
// in-flight daemon requests behind a dead provider (#2512).
|
||||
retry: false;
|
||||
placeholderData: typeof keepPreviousData;
|
||||
placeholderData: () => RecentSessionsResponse | undefined;
|
||||
queryFn: () => Promise<RecentSessionsResponse>;
|
||||
}
|
||||
|
||||
function buildSessionsQueriesConfig(args: {
|
||||
queryClient: QueryClient;
|
||||
providersToFetch: AgentProvider[] | null;
|
||||
visible: boolean;
|
||||
client: RecentProviderSessionsClient | null;
|
||||
@@ -113,14 +115,24 @@ function buildSessionsQueriesConfig(args: {
|
||||
limit: number;
|
||||
hostDisconnectedMessage?: string;
|
||||
}): SessionsQueryConfig[] {
|
||||
const { providersToFetch, visible, client, cwd, query, limit, hostDisconnectedMessage } = args;
|
||||
const { queryClient, providersToFetch, visible, client, cwd, query, limit } = args;
|
||||
const { hostDisconnectedMessage } = args;
|
||||
if (providersToFetch === null) return [];
|
||||
const enabled = visible && Boolean(client);
|
||||
const previousLimit = previousPageLimit(limit);
|
||||
return providersToFetch.map((provider) => ({
|
||||
queryKey: buildSessionsQueryKey({ cwd, query, limit, provider }),
|
||||
enabled,
|
||||
retry: false as const,
|
||||
placeholderData: keepPreviousData,
|
||||
// While Load more fetches the next page, keep showing the page it grew from. React Query's
|
||||
// keepPreviousData cannot do this here: useQueries gives a changed key a new observer, which
|
||||
// has no previous data, so the rows would vanish and the list would remount at the top.
|
||||
placeholderData: () =>
|
||||
previousLimit === null
|
||||
? undefined
|
||||
: queryClient.getQueryData<RecentSessionsResponse>(
|
||||
buildSessionsQueryKey({ cwd, query, limit: previousLimit, provider }),
|
||||
),
|
||||
queryFn: async () => {
|
||||
if (!client) {
|
||||
throw new Error(hostDisconnectedMessage ?? i18n.t("workspace.terminal.hostDisconnected"));
|
||||
@@ -522,6 +534,7 @@ export function ImportSessionSheet({
|
||||
const queriesConfig = useMemo(
|
||||
() =>
|
||||
buildSessionsQueriesConfig({
|
||||
queryClient,
|
||||
providersToFetch,
|
||||
visible,
|
||||
client,
|
||||
@@ -530,7 +543,7 @@ export function ImportSessionSheet({
|
||||
limit: pageLimit,
|
||||
hostDisconnectedMessage: t("workspace.terminal.hostDisconnected"),
|
||||
}),
|
||||
[providersToFetch, visible, client, scopeCwd, query, pageLimit, t],
|
||||
[queryClient, providersToFetch, visible, client, scopeCwd, query, pageLimit, t],
|
||||
);
|
||||
|
||||
const queries = useQueries({ queries: queriesConfig });
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { useWorkspaceRowPress } from "../../modules/paseo-press-feedback";
|
||||
import { PressHighlight as Pressable } from "@/components/ui/press-highlight";
|
||||
import { LoadingSpinner } from "@/components/ui/loading-spinner";
|
||||
import {
|
||||
@@ -1091,11 +1090,13 @@ function WorkspaceRowInner({
|
||||
...dragAttributes
|
||||
} = dragHandleProps?.attributes ?? {};
|
||||
|
||||
const { onPress: handlePress, feedback } = useWorkspaceRowPress({
|
||||
didLongPressRef: interaction.didLongPressRef,
|
||||
onPress,
|
||||
selected,
|
||||
});
|
||||
const handlePress = useCallback(() => {
|
||||
if (interaction.didLongPressRef.current) {
|
||||
interaction.didLongPressRef.current = false;
|
||||
return;
|
||||
}
|
||||
onPress();
|
||||
}, [interaction.didLongPressRef, onPress]);
|
||||
|
||||
const accessibilityState = useMemo(() => ({ selected }), [selected]);
|
||||
const isEditingTitle = titleEditor !== null;
|
||||
@@ -1190,7 +1191,6 @@ function WorkspaceRowInner({
|
||||
onTogglePin={onTogglePin}
|
||||
/>
|
||||
</SidebarWorkspaceRowContent>
|
||||
{feedback}
|
||||
</SidebarWorkspaceContextMenu>
|
||||
</View>
|
||||
);
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { useWorkspaceRowPress } from "../../../modules/paseo-press-feedback";
|
||||
import { PressHighlight as Pressable } from "@/components/ui/press-highlight";
|
||||
import {
|
||||
memo,
|
||||
@@ -847,11 +846,13 @@ function StatusWorkspaceRowInnerContent({
|
||||
const startDragPress = dragInteraction?.handlePressIn;
|
||||
const moveDragPress = dragInteraction?.handleTouchMove;
|
||||
const endDragPress = dragInteraction?.handlePressOut;
|
||||
const { onPress: handlePress, feedback } = useWorkspaceRowPress({
|
||||
didLongPressRef,
|
||||
onPress,
|
||||
selected,
|
||||
});
|
||||
const handlePress = useCallback(() => {
|
||||
if (didLongPressRef?.current) {
|
||||
didLongPressRef.current = false;
|
||||
return;
|
||||
}
|
||||
onPress();
|
||||
}, [didLongPressRef, onPress]);
|
||||
|
||||
return (
|
||||
<SidebarWorkspaceRowFrame
|
||||
@@ -964,7 +965,6 @@ function StatusWorkspaceRowInnerContent({
|
||||
/>
|
||||
) : null}
|
||||
</SidebarWorkspaceRowContent>
|
||||
{feedback}
|
||||
</SidebarWorkspaceContextMenu>
|
||||
</View>
|
||||
);
|
||||
|
||||
@@ -68,24 +68,27 @@ const theme = {
|
||||
} as unknown as Theme;
|
||||
|
||||
describe("control sizing gate", () => {
|
||||
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("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("gives a touch screen its touch sizes at every width", () => {
|
||||
it("gives a touch primary pointer 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-driven window: touch-sized only once it narrows into the compact layout.
|
||||
// A mouse- or trackpad-driven window, touch screen or not: 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 screen on pointer sizes from md up", () => {
|
||||
// The unit runtime has no touch screen, which is the desktop that must not change.
|
||||
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.
|
||||
expect(controlSizingForLayout(false)).toBe("pointer");
|
||||
expect(controlSizingForLayout(true)).toBe("touch");
|
||||
expect(CONTROL_HEIGHTS.md).toEqual({ xs: 44, md: 32 });
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { hasTouchScreen } from "@/hooks/pointer-capabilities";
|
||||
import { hasTouchPrimaryPointer } 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,28 +14,32 @@ export type ControlSizing = "touch" | "pointer";
|
||||
export interface ControlSizingFacts {
|
||||
/** The layout is below the `md` breakpoint. */
|
||||
compactLayout: boolean;
|
||||
/** The device has a touch screen; see `hasTouchScreen`. */
|
||||
touchScreen: boolean;
|
||||
/** Touch is the device's primary input; see `hasTouchPrimaryPointer`. */
|
||||
touchPrimaryPointer: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* 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.
|
||||
*/
|
||||
export function resolveControlSizing({
|
||||
compactLayout,
|
||||
touchScreen,
|
||||
touchPrimaryPointer,
|
||||
}: ControlSizingFacts): ControlSizing {
|
||||
if (compactLayout || touchScreen) return "touch";
|
||||
if (compactLayout || touchPrimaryPointer) return "touch";
|
||||
return "pointer";
|
||||
}
|
||||
|
||||
// Read once, so attaching a mouse or keyboard later never flips the sizing.
|
||||
const DEVICE_HAS_TOUCH_SCREEN = hasTouchScreen();
|
||||
const DEVICE_HAS_TOUCH_PRIMARY_POINTER = hasTouchPrimaryPointer();
|
||||
|
||||
/** The sizing on this device for a layout, for code that sizes outside a stylesheet. */
|
||||
export function controlSizingForLayout(compactLayout: boolean): ControlSizing {
|
||||
return resolveControlSizing({ compactLayout, touchScreen: DEVICE_HAS_TOUCH_SCREEN });
|
||||
return resolveControlSizing({
|
||||
compactLayout,
|
||||
touchPrimaryPointer: DEVICE_HAS_TOUCH_PRIMARY_POINTER,
|
||||
});
|
||||
}
|
||||
|
||||
/** A Unistyles breakpoint value: one number in the compact layout, another from `md` up. */
|
||||
@@ -51,11 +55,11 @@ export type SizingValue = Record<ControlSizing, number>;
|
||||
*/
|
||||
export function bySizing(
|
||||
sizes: SizingValue,
|
||||
touchScreen: boolean = DEVICE_HAS_TOUCH_SCREEN,
|
||||
touchPrimaryPointer: boolean = DEVICE_HAS_TOUCH_PRIMARY_POINTER,
|
||||
): LayoutValue {
|
||||
return {
|
||||
xs: sizes[resolveControlSizing({ compactLayout: true, touchScreen })],
|
||||
md: sizes[resolveControlSizing({ compactLayout: false, touchScreen })],
|
||||
xs: sizes[resolveControlSizing({ compactLayout: true, touchPrimaryPointer })],
|
||||
md: sizes[resolveControlSizing({ compactLayout: false, touchPrimaryPointer })],
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -23,10 +23,18 @@ class FakeMediaQueryList {
|
||||
}
|
||||
}
|
||||
|
||||
function createFakeDisplay(initial: { finePointer: boolean; touchScreen: boolean }) {
|
||||
function createFakeDisplay(initial: {
|
||||
finePointer: boolean;
|
||||
touchScreen: boolean;
|
||||
touchPrimaryPointer?: 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);
|
||||
@@ -75,3 +83,25 @@ 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);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -8,6 +8,7 @@ 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. */
|
||||
@@ -21,6 +22,7 @@ type MatchMedia = (query: string) => MediaQueryList;
|
||||
export interface PointerCapabilitiesSource {
|
||||
getSnapshot: () => PointerCapabilities;
|
||||
subscribe: (onChange: () => void) => () => void;
|
||||
hasTouchPrimaryPointer: () => boolean;
|
||||
}
|
||||
|
||||
export function createPointerCapabilitiesSource(
|
||||
@@ -28,9 +30,11 @@ 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;
|
||||
@@ -61,6 +65,7 @@ const NATIVE_POINTER_CAPABILITIES: PointerCapabilities = { finePointer: false, t
|
||||
const nativeSource: PointerCapabilitiesSource = {
|
||||
getSnapshot: () => NATIVE_POINTER_CAPABILITIES,
|
||||
subscribe: () => () => {},
|
||||
hasTouchPrimaryPointer: () => true,
|
||||
};
|
||||
|
||||
const source = isWeb ? createPointerCapabilitiesSource(browserMatchMedia()) : nativeSource;
|
||||
@@ -79,10 +84,11 @@ export function hasFinePointer(): boolean {
|
||||
return source.getSnapshot().finePointer;
|
||||
}
|
||||
|
||||
/** 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)
|
||||
);
|
||||
/**
|
||||
* 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();
|
||||
}
|
||||
|
||||
@@ -431,7 +431,7 @@ function AddHostModalContent({ visible, onClose, onCancel, onSaved }: AddHostMod
|
||||
<View style={styles.portRow}>
|
||||
<View style={hostFieldStyle}>
|
||||
<Text style={styles.label}>{t("pairing.direct.fields.host")}</Text>
|
||||
<ThemedAdaptiveTextInput
|
||||
<AdaptiveTextInput
|
||||
testID="direct-host-input"
|
||||
nativeID="direct-host-input"
|
||||
accessibilityLabel={t("pairing.direct.fields.host")}
|
||||
@@ -449,7 +449,7 @@ function AddHostModalContent({ visible, onClose, onCancel, onSaved }: AddHostMod
|
||||
</View>
|
||||
<View style={portFieldStyle}>
|
||||
<Text style={styles.label}>{t("pairing.direct.fields.port")}</Text>
|
||||
<ThemedAdaptiveTextInput
|
||||
<AdaptiveTextInput
|
||||
testID="direct-port-input"
|
||||
nativeID="direct-port-input"
|
||||
accessibilityLabel={t("pairing.direct.fields.port")}
|
||||
@@ -491,7 +491,7 @@ function AddHostModalContent({ visible, onClose, onCancel, onSaved }: AddHostMod
|
||||
<View style={styles.field}>
|
||||
<Text style={styles.label}>{t("pairing.direct.fields.password")}</Text>
|
||||
<View style={styles.passwordRow}>
|
||||
<ThemedAdaptiveTextInput
|
||||
<AdaptiveTextInput
|
||||
testID="direct-password-input"
|
||||
nativeID="direct-password-input"
|
||||
accessibilityLabel={t("pairing.direct.fields.password")}
|
||||
@@ -539,7 +539,7 @@ function AddHostModalContent({ visible, onClose, onCancel, onSaved }: AddHostMod
|
||||
<Text style={styles.advancedText}>{t("pairing.direct.advanced.label")}</Text>
|
||||
</PressHighlight>
|
||||
{isAdvancedOpen ? (
|
||||
<ThemedAdaptiveTextInput
|
||||
<AdaptiveTextInput
|
||||
testID="direct-host-uri-input"
|
||||
nativeID="direct-host-uri-input"
|
||||
accessibilityLabel={t("pairing.direct.fields.connectionUri")}
|
||||
@@ -598,7 +598,3 @@ const ThemedChevronRight = withUnistyles(ChevronRight, (theme) => ({
|
||||
const ThemedEye = withUnistyles(Eye, (theme) => ({ color: theme.colors.foregroundMuted }));
|
||||
|
||||
const ThemedEyeOff = withUnistyles(EyeOff, (theme) => ({ color: theme.colors.foregroundMuted }));
|
||||
|
||||
const ThemedAdaptiveTextInput = withUnistyles(AdaptiveTextInput, (theme) => ({
|
||||
placeholderTextColor: theme.colors.foregroundMuted,
|
||||
}));
|
||||
|
||||
@@ -212,7 +212,7 @@ function PairLinkModalContent({
|
||||
|
||||
<View style={styles.field}>
|
||||
<Text style={styles.label}>{t("pairing.link.label")}</Text>
|
||||
<ThemedAdaptiveTextInput
|
||||
<AdaptiveTextInput
|
||||
ref={inputRef}
|
||||
initialValue={initialUrl}
|
||||
testID="pair-link-input"
|
||||
@@ -234,11 +234,13 @@ function PairLinkModalContent({
|
||||
<Text style={styles.label}>
|
||||
{t("pairing.hostPassword.title", { host: parsedHostLabel(offerUrlRef.current) })}
|
||||
</Text>
|
||||
<ThemedAdaptiveTextInput
|
||||
<AdaptiveTextInput
|
||||
testID="pair-link-password-input"
|
||||
resetKey={`pair-link-password-${passwordResetKey}`}
|
||||
accessibilityLabel={t("pairing.hostPassword.label")}
|
||||
placeholder={t("pairing.hostPassword.label")}
|
||||
onChangeText={setPassword}
|
||||
autoFocus
|
||||
secureTextEntry
|
||||
style={styles.input}
|
||||
/>
|
||||
@@ -275,7 +277,3 @@ function PairLinkModalContent({
|
||||
}
|
||||
|
||||
const ThemedLink = withUnistyles(Link, (theme) => ({ color: theme.colors.accentForeground }));
|
||||
|
||||
const ThemedAdaptiveTextInput = withUnistyles(AdaptiveTextInput, (theme) => ({
|
||||
placeholderTextColor: theme.colors.foregroundMuted,
|
||||
}));
|
||||
|
||||
@@ -484,8 +484,7 @@ export const ar: TranslationResources = {
|
||||
archivedTitle: "مساحة العمل مؤرشفة",
|
||||
restoreDescription:
|
||||
"استعد {{workspaceName}} للعودة إلى وكلائها. ستستخدم شجرة العمل الفرع {{branch}}.",
|
||||
restoreWithoutBranchDescription:
|
||||
"استعد {{workspaceName}} للعودة إلى وكلائها. سيبدأ فرع جديد من الفرع الأساسي المحفوظ أو الفرع الافتراضي للمستودع.",
|
||||
restoreWithoutBranchDescription: "استعد {{workspaceName}} للعودة إلى وكلائها.",
|
||||
unarchiveDescription: "{{workspaceName}} مؤرشفة. ألغِ أرشفتها لفتحها مجددًا.",
|
||||
restoreAction: "استعادة",
|
||||
unarchiveAction: "إلغاء الأرشفة",
|
||||
@@ -2017,6 +2016,7 @@ export const ar: TranslationResources = {
|
||||
hostUnavailable: "مضيف التنزيل غير متاح.",
|
||||
cancelled: "تم إلغاء التنزيل.",
|
||||
failed: "فشل تنزيل الملف.",
|
||||
httpFailed: "فشل تنزيل الملف (HTTP {{status}}).",
|
||||
shareFile: "مشاركة الملف",
|
||||
shareFileNamed: "مشاركة{{fileName}}",
|
||||
},
|
||||
|
||||
@@ -483,8 +483,7 @@ export const en = {
|
||||
archivedTitle: "Workspace archived",
|
||||
restoreDescription:
|
||||
"Restore {{workspaceName}} to return to its agents. Its worktree will use branch {{branch}}.",
|
||||
restoreWithoutBranchDescription:
|
||||
"Restore {{workspaceName}} to return to its agents. A new branch will start from the saved base or the repository default.",
|
||||
restoreWithoutBranchDescription: "Restore {{workspaceName}} to return to its agents.",
|
||||
unarchiveDescription: "{{workspaceName}} is archived. Unarchive it to open it again.",
|
||||
restoreAction: "Restore",
|
||||
unarchiveAction: "Unarchive",
|
||||
@@ -2045,6 +2044,7 @@ export const en = {
|
||||
hostUnavailable: "Download host is unavailable.",
|
||||
cancelled: "Download was cancelled.",
|
||||
failed: "Failed to download file.",
|
||||
httpFailed: "Failed to download file (HTTP {{status}}).",
|
||||
shareFile: "Share file",
|
||||
shareFileNamed: "Share {{fileName}}",
|
||||
},
|
||||
|
||||
@@ -489,8 +489,7 @@ export const es: TranslationResources = {
|
||||
archivedTitle: "Espacio de trabajo archivado",
|
||||
restoreDescription:
|
||||
"Restaura {{workspaceName}} para volver a sus agentes. Su worktree usará la rama {{branch}}.",
|
||||
restoreWithoutBranchDescription:
|
||||
"Restaura {{workspaceName}} para volver a sus agentes. Se creará una rama nueva desde la base guardada o la rama predeterminada del repositorio.",
|
||||
restoreWithoutBranchDescription: "Restaura {{workspaceName}} para volver a sus agentes.",
|
||||
unarchiveDescription:
|
||||
"{{workspaceName}} está archivado. Desarchívalo para volver a abrirlo.",
|
||||
restoreAction: "Restaurar",
|
||||
@@ -2066,6 +2065,7 @@ export const es: TranslationResources = {
|
||||
hostUnavailable: "El host de descarga no está disponible.",
|
||||
cancelled: "La descarga fue cancelada.",
|
||||
failed: "No se pudo descargar el archivo.",
|
||||
httpFailed: "No se pudo descargar el archivo (HTTP {{status}}).",
|
||||
shareFile: "compartir archivo",
|
||||
shareFileNamed: "Compartir{{fileName}}",
|
||||
},
|
||||
|
||||
@@ -489,8 +489,7 @@ export const fr: TranslationResources = {
|
||||
archivedTitle: "Espace de travail archivé",
|
||||
restoreDescription:
|
||||
"Restaurez {{workspaceName}} pour retrouver ses agents. Son worktree utilisera la branche {{branch}}.",
|
||||
restoreWithoutBranchDescription:
|
||||
"Restaurez {{workspaceName}} pour retrouver ses agents. Une nouvelle branche partira de la base enregistrée ou de la branche par défaut du dépôt.",
|
||||
restoreWithoutBranchDescription: "Restaurez {{workspaceName}} pour retrouver ses agents.",
|
||||
unarchiveDescription: "{{workspaceName}} est archivé. Désarchivez-le pour le rouvrir.",
|
||||
restoreAction: "Restaurer",
|
||||
unarchiveAction: "Désarchiver",
|
||||
@@ -2065,6 +2064,7 @@ export const fr: TranslationResources = {
|
||||
hostUnavailable: "L’hôte de téléchargement est indisponible.",
|
||||
cancelled: "Téléchargement annulé.",
|
||||
failed: "Impossible de télécharger le fichier.",
|
||||
httpFailed: "Impossible de télécharger le fichier (HTTP {{status}}).",
|
||||
shareFile: "Partager le fichier",
|
||||
shareFileNamed: "Partager {{fileName}}",
|
||||
},
|
||||
|
||||
@@ -489,8 +489,7 @@ export const ja: TranslationResources = {
|
||||
archivedTitle: "ワークスペースはアーカイブ済みです",
|
||||
restoreDescription:
|
||||
"{{workspaceName}} を復元してエージェントに戻ります。worktree ではブランチ {{branch}} を使用します。",
|
||||
restoreWithoutBranchDescription:
|
||||
"{{workspaceName}} を復元してエージェントに戻ります。保存されたベース、またはリポジトリのデフォルトブランチから新しいブランチを作成します。",
|
||||
restoreWithoutBranchDescription: "{{workspaceName}} を復元してエージェントに戻ります。",
|
||||
unarchiveDescription:
|
||||
"{{workspaceName}} はアーカイブされています。再度開くにはアーカイブを解除してください。",
|
||||
restoreAction: "復元",
|
||||
@@ -2038,6 +2037,7 @@ export const ja: TranslationResources = {
|
||||
hostUnavailable: "ダウンロードホストが利用できません。",
|
||||
cancelled: "ダウンロードがキャンセルされました。",
|
||||
failed: "ファイルのダウンロードに失敗しました。",
|
||||
httpFailed: "ファイルのダウンロードに失敗しました (HTTP {{status}}).",
|
||||
shareFile: "ファイルを共有",
|
||||
shareFileNamed: "{{fileName}}を共有",
|
||||
},
|
||||
|
||||
@@ -485,8 +485,7 @@ export const ko: TranslationResources = {
|
||||
archivedTitle: "워크스페이스가 보관되었습니다",
|
||||
restoreDescription:
|
||||
"{{workspaceName}}를 복원하여 에이전트로 돌아갑니다. 워크트리는 {{branch}} 브랜치를 사용합니다.",
|
||||
restoreWithoutBranchDescription:
|
||||
"{{workspaceName}}를 복원하여 에이전트로 돌아갑니다. 저장된 기반 브랜치 또는 저장소 기본 브랜치에서 새 브랜치를 만듭니다.",
|
||||
restoreWithoutBranchDescription: "{{workspaceName}}를 복원하여 에이전트로 돌아갑니다.",
|
||||
unarchiveDescription: "{{workspaceName}}가 보관되었습니다. 다시 열려면 보관을 취소하세요.",
|
||||
restoreAction: "복원",
|
||||
unarchiveAction: "보관 취소",
|
||||
@@ -2028,6 +2027,7 @@ export const ko: TranslationResources = {
|
||||
hostUnavailable: "다운로드 호스트를 사용할 수 없습니다.",
|
||||
cancelled: "다운로드가 취소되었습니다.",
|
||||
failed: "파일을 다운로드하지 못했습니다.",
|
||||
httpFailed: "파일을 다운로드하지 못했습니다 (HTTP {{status}}).",
|
||||
shareFile: "파일 공유",
|
||||
shareFileNamed: "{{fileName}} 공유",
|
||||
},
|
||||
|
||||
@@ -488,8 +488,7 @@ export const ptBR: TranslationResources = {
|
||||
archivedTitle: "Workspace arquivado",
|
||||
restoreDescription:
|
||||
"Restaure {{workspaceName}} para voltar aos seus agentes. A worktree usará a branch {{branch}}.",
|
||||
restoreWithoutBranchDescription:
|
||||
"Restaure {{workspaceName}} para voltar aos seus agentes. Uma nova branch partirá da base salva ou da branch padrão do repositório.",
|
||||
restoreWithoutBranchDescription: "Restaure {{workspaceName}} para voltar aos seus agentes.",
|
||||
unarchiveDescription:
|
||||
"{{workspaceName}} está arquivado. Desarquive-o para abri-lo novamente.",
|
||||
restoreAction: "Restaurar",
|
||||
@@ -2051,6 +2050,7 @@ export const ptBR: TranslationResources = {
|
||||
hostUnavailable: "Host de download indisponível.",
|
||||
cancelled: "Download cancelado.",
|
||||
failed: "Falha ao baixar arquivo.",
|
||||
httpFailed: "Falha ao baixar arquivo (HTTP {{status}}).",
|
||||
shareFile: "Compartilhar arquivo",
|
||||
shareFileNamed: "Compartilhar {{fileName}}",
|
||||
},
|
||||
|
||||
@@ -489,7 +489,7 @@ export const ru: TranslationResources = {
|
||||
restoreDescription:
|
||||
"Восстановите «{{workspaceName}}», чтобы вернуться к его агентам. Worktree будет использовать ветку {{branch}}.",
|
||||
restoreWithoutBranchDescription:
|
||||
"Восстановите «{{workspaceName}}», чтобы вернуться к его агентам. Новая ветка будет создана от сохранённой базовой или ветки репозитория по умолчанию.",
|
||||
"Восстановите «{{workspaceName}}», чтобы вернуться к его агентам.",
|
||||
unarchiveDescription:
|
||||
"Рабочее пространство «{{workspaceName}}» находится в архиве. Разархивируйте его, чтобы снова открыть.",
|
||||
restoreAction: "Восстановить",
|
||||
@@ -2051,6 +2051,7 @@ export const ru: TranslationResources = {
|
||||
hostUnavailable: "Хост загрузки недоступен.",
|
||||
cancelled: "Загрузка отменена.",
|
||||
failed: "Не удалось загрузить файл.",
|
||||
httpFailed: "Не удалось загрузить файл (HTTP {{status}}).",
|
||||
shareFile: "Поделиться файлом",
|
||||
shareFileNamed: "Поделиться {{fileName}}",
|
||||
},
|
||||
|
||||
@@ -484,8 +484,7 @@ export const zhCN: TranslationResources = {
|
||||
archivedTitle: "Workspace 已归档",
|
||||
restoreDescription:
|
||||
"恢复 {{workspaceName}} 以返回其中的代理。worktree 将使用分支 {{branch}}。",
|
||||
restoreWithoutBranchDescription:
|
||||
"恢复 {{workspaceName}} 以返回其中的代理。新分支将从保存的基准分支或仓库默认分支创建。",
|
||||
restoreWithoutBranchDescription: "恢复 {{workspaceName}} 以返回其中的代理。",
|
||||
unarchiveDescription: "{{workspaceName}} 已归档。取消归档以重新打开。",
|
||||
restoreAction: "恢复",
|
||||
unarchiveAction: "取消归档",
|
||||
@@ -1994,6 +1993,7 @@ export const zhCN: TranslationResources = {
|
||||
hostUnavailable: "下载 Host 不可用。",
|
||||
cancelled: "下载已取消。",
|
||||
failed: "下载文件失败。",
|
||||
httpFailed: "下载文件失败 (HTTP {{status}}).",
|
||||
shareFile: "共享文件",
|
||||
shareFileNamed: "共享 {{fileName}}",
|
||||
},
|
||||
|
||||
@@ -2256,6 +2256,59 @@ describe("HostRuntimeController", () => {
|
||||
});
|
||||
});
|
||||
|
||||
const REGISTRY_KEY = "@paseo:daemon-registry";
|
||||
const futureConnection = { id: "future:1", type: "futureKind", address: "future.example.com" };
|
||||
const directA: HostConnection = {
|
||||
id: "direct:lan-a:6767",
|
||||
type: "directTcp",
|
||||
endpoint: "lan-a:6767",
|
||||
};
|
||||
const directB: HostConnection = {
|
||||
id: "direct:lan-b:6767",
|
||||
type: "directTcp",
|
||||
endpoint: "lan-b:6767",
|
||||
};
|
||||
// What a build with a connection kind this one doesn't know leaves behind: an extra connection
|
||||
// on a host this build can reach, and a host reached only through it.
|
||||
const storedWithUnreadableEntries = [
|
||||
{
|
||||
...makeHost({ serverId: "srv_a", password: "secret-a" }),
|
||||
connections: [futureConnection, directA],
|
||||
},
|
||||
makeHost({ serverId: "srv_b", password: "secret-b", connections: [directB] }),
|
||||
{ serverId: "srv_future", label: "future host", connections: [futureConnection] },
|
||||
];
|
||||
|
||||
async function bootWithRegistry(registry: string): Promise<{
|
||||
store: HostRuntimeStore;
|
||||
storage: HostRuntimeStorage;
|
||||
}> {
|
||||
const storage = createMemoryHostRuntimeStorage({
|
||||
[REGISTRY_KEY]: registry,
|
||||
"@paseo:e2e": "1",
|
||||
});
|
||||
const store = new HostRuntimeStore({
|
||||
storage,
|
||||
deps: {
|
||||
createClient: () => new FakeDaemonClient() as unknown as DaemonClient,
|
||||
connectToDaemon: async ({ host }) => ({
|
||||
client: makeConnectedProbeClient(5) as unknown as DaemonClient,
|
||||
serverId: host.serverId,
|
||||
hostname: host.label ?? null,
|
||||
}),
|
||||
getClientId: async () => "cid_test_runtime",
|
||||
},
|
||||
revokePushNotifications: async () => undefined,
|
||||
});
|
||||
await store.boot();
|
||||
return { store, storage };
|
||||
}
|
||||
|
||||
async function readRegistry(storage: HostRuntimeStorage): Promise<unknown> {
|
||||
const raw = await storage.getItem(REGISTRY_KEY);
|
||||
return raw === null ? null : JSON.parse(raw);
|
||||
}
|
||||
|
||||
describe("HostRuntimeStore", () => {
|
||||
function gatewayRecoveryFixture() {
|
||||
const parent = new FakeDaemonClient();
|
||||
@@ -2686,6 +2739,98 @@ describe("HostRuntimeStore", () => {
|
||||
session.clearSession(host.serverId);
|
||||
});
|
||||
|
||||
it("keeps readable hosts when the registry holds entries this build can't read", async () => {
|
||||
const { store, storage } = await bootWithRegistry(JSON.stringify(storedWithUnreadableEntries));
|
||||
|
||||
expect(store.getHosts().map((host) => [host.serverId, host.password])).toEqual([
|
||||
["srv_a", "secret-a"],
|
||||
["srv_b", "secret-b"],
|
||||
]);
|
||||
expect(store.getHosts()[0]?.connections.map((connection) => connection.id)).toEqual([
|
||||
directA.id,
|
||||
]);
|
||||
expect(await readRegistry(storage)).toEqual(storedWithUnreadableEntries);
|
||||
|
||||
store.syncHosts([]);
|
||||
});
|
||||
|
||||
it("keeps the entries it can't read when it saves the registry", async () => {
|
||||
const { store, storage } = await bootWithRegistry(JSON.stringify(storedWithUnreadableEntries));
|
||||
|
||||
await store.renameHost("srv_b", "renamed");
|
||||
|
||||
expect(await readRegistry(storage)).toMatchObject([
|
||||
{
|
||||
serverId: "srv_a",
|
||||
password: "secret-a",
|
||||
connections: [{ id: directA.id }, futureConnection],
|
||||
},
|
||||
{ serverId: "srv_b", password: "secret-b", label: "renamed" },
|
||||
storedWithUnreadableEntries[2],
|
||||
]);
|
||||
|
||||
store.syncHosts([]);
|
||||
});
|
||||
|
||||
it("moves a stored connection password to its host and keeps the connection it can't read", async () => {
|
||||
const { store, storage } = await bootWithRegistry(
|
||||
JSON.stringify([
|
||||
{
|
||||
serverId: "srv_legacy",
|
||||
connections: [
|
||||
{ type: "directTcp", endpoint: "lan-a:6767", password: "old-secret" },
|
||||
futureConnection,
|
||||
],
|
||||
},
|
||||
]),
|
||||
);
|
||||
|
||||
expect(store.getHosts().map((host) => [host.serverId, host.password])).toEqual([
|
||||
["srv_legacy", "old-secret"],
|
||||
]);
|
||||
await vi.waitFor(async () =>
|
||||
expect(await readRegistry(storage)).toMatchObject([
|
||||
{ serverId: "srv_legacy", password: "old-secret" },
|
||||
]),
|
||||
);
|
||||
expect(await readRegistry(storage)).toMatchObject([
|
||||
{ connections: [{ ...directA, useTls: false }, futureConnection] },
|
||||
]);
|
||||
const [written] = (await readRegistry(storage)) as Array<{ connections: unknown[] }>;
|
||||
expect(written?.connections[0]).not.toHaveProperty("password");
|
||||
|
||||
store.syncHosts([]);
|
||||
});
|
||||
|
||||
it("forgets an entry it can't read once that host is paired again and removed", async () => {
|
||||
const { store, storage } = await bootWithRegistry(
|
||||
JSON.stringify([{ serverId: "srv_future", connections: [futureConnection] }]),
|
||||
);
|
||||
expect(store.getHosts()).toEqual([]);
|
||||
|
||||
await store.upsertDirectConnection({ serverId: "srv_future", endpoint: directA.endpoint });
|
||||
await vi.waitFor(async () =>
|
||||
expect(await readRegistry(storage)).toMatchObject([
|
||||
{ serverId: "srv_future", connections: [{ id: directA.id }] },
|
||||
]),
|
||||
);
|
||||
|
||||
await store.removeHost("srv_future");
|
||||
expect(await readRegistry(storage)).toEqual([]);
|
||||
|
||||
store.syncHosts([]);
|
||||
});
|
||||
|
||||
it("copies a registry that isn't JSON aside instead of deleting it", async () => {
|
||||
const { store, storage } = await bootWithRegistry("{not json");
|
||||
|
||||
expect(store.getHosts()).toEqual([]);
|
||||
expect(await storage.getItem(`${REGISTRY_KEY}:unreadable`)).toBe("{not json");
|
||||
expect(await storage.getItem(REGISTRY_KEY)).toBe("{not json");
|
||||
|
||||
store.syncHosts([]);
|
||||
});
|
||||
|
||||
it("marks the host registry loaded after boot reads storage", async () => {
|
||||
const previousOverride = process.env.EXPO_PUBLIC_LOCAL_DAEMON;
|
||||
process.env.EXPO_PUBLIC_LOCAL_DAEMON = "not-an-endpoint";
|
||||
|
||||
@@ -17,14 +17,16 @@ import {
|
||||
import {
|
||||
connectionFromListen,
|
||||
createRemoteSshHostConnection,
|
||||
normalizeStoredHostProfile,
|
||||
forgetUnreadableHost,
|
||||
pinRelayProtectedSecurityInProfiles,
|
||||
readHostRegistry,
|
||||
upsertHostConnectionInProfiles,
|
||||
registryHasConnection,
|
||||
relayConnectionFromOffer,
|
||||
StoredHostRegistrySchema,
|
||||
writeHostRegistry,
|
||||
type HostConnection,
|
||||
type HostProfile,
|
||||
type UnreadableHostEntries,
|
||||
} from "@/types/host-connection";
|
||||
import { defaultHostAppearance, type HostBadgeDisplay, type HostColor } from "@/hosts/appearance";
|
||||
import {
|
||||
@@ -43,7 +45,7 @@ import { isWeb } from "@/constants/platform";
|
||||
import { connectToDaemon, getConnectionAuthFailureReason } from "@/utils/test-daemon-connection";
|
||||
import { getOrCreateClientId } from "@/utils/client-id";
|
||||
import { z } from "zod";
|
||||
import { readValidatedJson, readValidatedString } from "@/storage/validated-storage";
|
||||
import { readValidatedString } from "@/storage/validated-storage";
|
||||
import {
|
||||
selectBestConnection,
|
||||
type ConnectionCandidate,
|
||||
@@ -1692,6 +1694,7 @@ export class HostRuntimeStore {
|
||||
private hostListVersion = 0;
|
||||
private hostRegistryLoaded = false;
|
||||
private hosts: HostProfile[] = [];
|
||||
private unreadableHosts: UnreadableHostEntries = { hosts: [], connectionsByServerId: new Map() };
|
||||
private hostAppearanceMutationTail: Promise<void> = Promise.resolve();
|
||||
private hostRegistryStatus: HostRegistryStatus = "loading";
|
||||
private deps: HostRuntimeControllerDeps;
|
||||
@@ -1799,32 +1802,17 @@ export class HostRuntimeStore {
|
||||
let shouldPersistHosts = false;
|
||||
let profiles: HostProfile[] = [];
|
||||
try {
|
||||
const stored = await readValidatedJson(
|
||||
this.storage,
|
||||
REGISTRY_STORAGE_KEY,
|
||||
StoredHostRegistrySchema,
|
||||
);
|
||||
const stored = await this.readStoredRegistry();
|
||||
if (stored) {
|
||||
const normalizedProfiles: HostProfile[] = [];
|
||||
for (const entry of stored) {
|
||||
const profile = normalizeStoredHostProfile(entry);
|
||||
if (!profile) {
|
||||
await this.storage.removeItem(REGISTRY_STORAGE_KEY);
|
||||
normalizedProfiles.length = 0;
|
||||
break;
|
||||
}
|
||||
// COMPAT(connectionPassword): added in v0.9.1, remove after 2027-03-24 with stored-password migration.
|
||||
if (
|
||||
entry.connections.some(
|
||||
(connection) => connection.type === "directTcp" && connection.password,
|
||||
)
|
||||
) {
|
||||
shouldPersistHosts = true;
|
||||
}
|
||||
normalizedProfiles.push(profile);
|
||||
// An entry this build can't read skips only that host or connection, and stays stored.
|
||||
const registry = readHostRegistry(stored);
|
||||
this.unreadableHosts = registry.unreadable;
|
||||
// COMPAT(connectionPassword): added in v0.9.1, remove after 2027-03-24 with stored-password migration.
|
||||
if (registry.movedConnectionPassword) {
|
||||
shouldPersistHosts = true;
|
||||
}
|
||||
profiles = normalizedProfiles.filter((entry) => !isPlaceholderServerId(entry.serverId));
|
||||
if (profiles.length !== normalizedProfiles.length) {
|
||||
profiles = registry.hosts.filter((entry) => !isPlaceholderServerId(entry.serverId));
|
||||
if (profiles.length !== registry.hosts.length) {
|
||||
shouldPersistHosts = true;
|
||||
}
|
||||
}
|
||||
@@ -2320,6 +2308,7 @@ export class HostRuntimeStore {
|
||||
async removeHost(serverId: string): Promise<void> {
|
||||
await this.revokePushNotifications({ client: this.getClient(serverId), serverId });
|
||||
const remaining = this.hosts.filter((daemon) => daemon.serverId !== serverId);
|
||||
this.unreadableHosts = forgetUnreadableHost(this.unreadableHosts, serverId);
|
||||
this.setHostsAndSync(remaining);
|
||||
await this.persistHosts();
|
||||
}
|
||||
@@ -2408,7 +2397,27 @@ export class HostRuntimeStore {
|
||||
}
|
||||
|
||||
private async persistHosts(hosts = this.hosts): Promise<void> {
|
||||
await this.storage.setItem(REGISTRY_STORAGE_KEY, JSON.stringify(hosts));
|
||||
await this.storage.setItem(
|
||||
REGISTRY_STORAGE_KEY,
|
||||
JSON.stringify(writeHostRegistry(hosts, this.unreadableHosts)),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the stored registry without removing it. A value that isn't a JSON array is copied to
|
||||
* `<key>:unreadable` first, because the next save overwrites the key.
|
||||
*/
|
||||
private async readStoredRegistry(): Promise<unknown[] | null> {
|
||||
const raw = await this.storage.getItem(REGISTRY_STORAGE_KEY);
|
||||
if (raw === null) return null;
|
||||
try {
|
||||
const value: unknown = JSON.parse(raw);
|
||||
if (Array.isArray(value)) return value;
|
||||
} catch {
|
||||
// Not JSON: copied aside below.
|
||||
}
|
||||
await this.storage.setItem(`${REGISTRY_STORAGE_KEY}:unreadable`, raw);
|
||||
return null;
|
||||
}
|
||||
|
||||
private emitHostList(): void {
|
||||
|
||||
@@ -90,6 +90,7 @@ interface StartInput {
|
||||
token?: ReturnType<typeof createTokenRequest>;
|
||||
reader?: ReturnType<typeof createFileReader>;
|
||||
saver?: ReturnType<typeof createFileSaver>;
|
||||
fetchFile?: typeof fetch;
|
||||
}
|
||||
|
||||
async function startDownload(input: StartInput): Promise<Download | undefined> {
|
||||
@@ -108,6 +109,7 @@ async function startDownload(input: StartInput): Promise<Download | undefined> {
|
||||
requestFileDownloadToken: token.request,
|
||||
readFile: reader.read,
|
||||
saveFile: saver.save,
|
||||
fetchFile: input.fetchFile ?? (async () => new Response(FILE_BYTES)),
|
||||
});
|
||||
const { activeDownloadId, downloads } = useDownloadStore.getState();
|
||||
return activeDownloadId ? downloads.get(activeDownloadId) : undefined;
|
||||
@@ -203,6 +205,57 @@ describe("download store transport selection", () => {
|
||||
expect(saver.savedFiles).toEqual([]);
|
||||
});
|
||||
|
||||
it("fails with the HTTP status when a proxy in front of the host rejects the download", async () => {
|
||||
const requests: Array<RequestInit | undefined> = [];
|
||||
const download = await startDownload({
|
||||
profile: profileWith([localTcpConnection]),
|
||||
activeConnectionId: localTcpConnection.id,
|
||||
fetchFile: async (_url, init) => {
|
||||
requests.push(init);
|
||||
return new Response("<h1>401 Authorization Required</h1>", {
|
||||
status: 401,
|
||||
headers: { "WWW-Authenticate": 'Basic realm="Paseo"' },
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
expect(download).toMatchObject({
|
||||
status: "error",
|
||||
message: i18n.t("downloads.httpFailed", { status: 401 }),
|
||||
});
|
||||
expect(requests).toEqual([{ credentials: "include", redirect: "error" }]);
|
||||
});
|
||||
|
||||
it("fails with a readable message when the download request cannot reach the host", async () => {
|
||||
const download = await startDownload({
|
||||
profile: profileWith([localTcpConnection]),
|
||||
activeConnectionId: localTcpConnection.id,
|
||||
fetchFile: async () => {
|
||||
throw new TypeError("Failed to fetch");
|
||||
},
|
||||
});
|
||||
|
||||
expect(download).toMatchObject({ status: "error", message: i18n.t("downloads.failed") });
|
||||
});
|
||||
|
||||
it("fails with a readable message when the connection drops while the file is downloading", async () => {
|
||||
const saver = createFileSaver();
|
||||
const download = await startDownload({
|
||||
profile: profileWith([localTcpConnection]),
|
||||
activeConnectionId: localTcpConnection.id,
|
||||
fetchFile: async () =>
|
||||
new Response(
|
||||
new ReadableStream({
|
||||
start: (controller) => controller.error(new TypeError("network error")),
|
||||
}),
|
||||
),
|
||||
saver,
|
||||
});
|
||||
|
||||
expect(download).toMatchObject({ status: "error", message: i18n.t("downloads.failed") });
|
||||
expect(saver.savedFiles).toEqual([]);
|
||||
});
|
||||
|
||||
it("fails the download and saves nothing when the session read fails", async () => {
|
||||
const reader = createFileReader(async () => {
|
||||
throw new Error("Connection lost");
|
||||
|
||||
@@ -4,7 +4,6 @@ import * as LegacyFileSystem from "expo-file-system/legacy";
|
||||
import * as Sharing from "expo-sharing";
|
||||
import type { HostProfile } from "@/types/host-connection";
|
||||
import { buildDaemonWebSocketUrl } from "@/utils/daemon-endpoints";
|
||||
import { openExternalUrl } from "@/utils/open-external-url";
|
||||
import { isWeb } from "@/constants/platform";
|
||||
import { i18n } from "@/i18n/i18next";
|
||||
|
||||
@@ -59,6 +58,7 @@ interface DownloadState {
|
||||
/** Reads the whole file over the session socket; used when no direct HTTP endpoint is active. */
|
||||
readFile: (path: string, maxBytes: number) => Promise<{ bytes: Uint8Array; size: number }>;
|
||||
saveFile?: typeof saveDownloadedBytes;
|
||||
fetchFile?: typeof fetch;
|
||||
}) => Promise<void>;
|
||||
|
||||
updateProgress: (id: string, progress: DownloadProgress) => void;
|
||||
@@ -86,6 +86,7 @@ export const useDownloadStore = create<DownloadState>()((set, get) => ({
|
||||
requestFileDownloadToken,
|
||||
readFile,
|
||||
saveFile = saveDownloadedBytes,
|
||||
fetchFile = fetch,
|
||||
}) => {
|
||||
const id = generateDownloadId();
|
||||
const download: Download = {
|
||||
@@ -144,14 +145,11 @@ export const useDownloadStore = create<DownloadState>()((set, get) => ({
|
||||
throw new Error(i18n.t("downloads.hostUnavailable"));
|
||||
}
|
||||
|
||||
const downloadUrl = buildDownloadUrl(
|
||||
downloadTarget.baseUrl,
|
||||
tokenResponse.token,
|
||||
isWeb ? downloadTarget.authCredentials : null,
|
||||
);
|
||||
const downloadUrl = buildDownloadUrl(downloadTarget.baseUrl, tokenResponse.token);
|
||||
|
||||
if (isWeb) {
|
||||
triggerBrowserDownload(downloadUrl, resolvedFileName);
|
||||
const file = await fetchDownload(fetchFile, downloadUrl);
|
||||
saveBrowserFile(file, resolvedFileName);
|
||||
get().completeDownload(id);
|
||||
return;
|
||||
}
|
||||
@@ -198,11 +196,6 @@ export const useDownloadStore = create<DownloadState>()((set, get) => ({
|
||||
await shareSavedFile(result.uri, tokenResponse.mimeType, resolvedFileName);
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : i18n.t("downloads.failed");
|
||||
if (isWeb) {
|
||||
console.warn("[DownloadStore] Download failed:", message);
|
||||
get().failDownload(id, message);
|
||||
return;
|
||||
}
|
||||
get().failDownload(id, message);
|
||||
}
|
||||
},
|
||||
@@ -283,7 +276,6 @@ function findMostRecentDownloadId(downloads: Map<string, Download>): string | nu
|
||||
interface DownloadTarget {
|
||||
baseUrl: string | null;
|
||||
authHeader: string | null;
|
||||
authCredentials: { username: string; password: string } | null;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -306,7 +298,7 @@ function resolveDaemonDownloadTarget(
|
||||
buildDaemonWebSocketUrl(connection.endpoint, { useTls: connection.useTls ?? false }),
|
||||
);
|
||||
} catch {
|
||||
return { baseUrl: null, authHeader: null, authCredentials: null };
|
||||
return { baseUrl: null, authHeader: null };
|
||||
}
|
||||
|
||||
if (parsed.protocol === "ws:") {
|
||||
@@ -332,23 +324,41 @@ function resolveDaemonDownloadTarget(
|
||||
? `Basic ${btoa(`${authCredentials.username}:${authCredentials.password}`)}`
|
||||
: null;
|
||||
|
||||
return { baseUrl, authHeader, authCredentials };
|
||||
return { baseUrl, authHeader };
|
||||
}
|
||||
|
||||
function buildDownloadUrl(
|
||||
baseUrl: string,
|
||||
token: string,
|
||||
authCredentials: { username: string; password: string } | null,
|
||||
): string {
|
||||
function buildDownloadUrl(baseUrl: string, token: string): string {
|
||||
const url = new URL("/api/files/download", baseUrl);
|
||||
url.searchParams.set("token", token);
|
||||
if (authCredentials) {
|
||||
url.username = authCredentials.username;
|
||||
url.password = authCredentials.password;
|
||||
}
|
||||
return url.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetches the file instead of navigating to it. The app runs on another origin than the host
|
||||
* (paseo://app on desktop), so a link to the download URL navigates the whole window, and any
|
||||
* response that is not the file (a proxy's 401 page, a 404) replaces the app.
|
||||
*/
|
||||
async function fetchDownload(fetchFile: typeof fetch, url: string): Promise<Blob> {
|
||||
let response: Response;
|
||||
try {
|
||||
// Send the same cookies the host's WebSocket handshake sends, so a proxy in front of the
|
||||
// host lets the download through. Refuse redirects: a proxy that redirects to a login page
|
||||
// would otherwise be saved as the file.
|
||||
response = await fetchFile(url, { credentials: "include", redirect: "error" });
|
||||
} catch {
|
||||
throw new Error(i18n.t("downloads.failed"));
|
||||
}
|
||||
if (!response.ok) {
|
||||
throw new Error(i18n.t("downloads.httpFailed", { status: response.status }));
|
||||
}
|
||||
try {
|
||||
// The body streams after the headers, so the connection can still drop here.
|
||||
return await response.blob();
|
||||
} catch {
|
||||
throw new Error(i18n.t("downloads.failed"));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Saves bytes read over the session. Web and Electron hand them to the browser's download
|
||||
* manager and return `null`; native writes the file and returns its URI for the share sheet.
|
||||
@@ -361,12 +371,7 @@ async function saveDownloadedBytes({
|
||||
if (isWeb) {
|
||||
const buffer = new ArrayBuffer(bytes.byteLength);
|
||||
new Uint8Array(buffer).set(bytes);
|
||||
const url = URL.createObjectURL(
|
||||
new Blob([buffer], { type: mimeType ?? "application/octet-stream" }),
|
||||
);
|
||||
triggerBrowserDownload(url, fileName);
|
||||
// The browser may still be reading the blob while its save prompt is open.
|
||||
setTimeout(() => URL.revokeObjectURL(url), 60_000);
|
||||
saveBrowserFile(new Blob([buffer], { type: mimeType ?? "application/octet-stream" }), fileName);
|
||||
return null;
|
||||
}
|
||||
// Resolve and write in one tick so two downloads of the same name cannot pick the same path.
|
||||
@@ -390,14 +395,12 @@ async function shareSavedFile(
|
||||
}
|
||||
}
|
||||
|
||||
function triggerBrowserDownload(url: string, fileName: string) {
|
||||
function saveBrowserFile(file: Blob, fileName: string) {
|
||||
if (typeof document === "undefined") {
|
||||
if (typeof window !== "undefined") {
|
||||
void openExternalUrl(url);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const url = URL.createObjectURL(file);
|
||||
const link = document.createElement("a");
|
||||
link.href = url;
|
||||
link.download = fileName;
|
||||
@@ -405,6 +408,8 @@ function triggerBrowserDownload(url: string, fileName: string) {
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
link.remove();
|
||||
// The browser may still be reading the blob while its save prompt is open.
|
||||
setTimeout(() => URL.revokeObjectURL(url), 60_000);
|
||||
}
|
||||
|
||||
function resolveDownloadTargetFile(fileName: string): FSFile {
|
||||
|
||||
@@ -5,9 +5,11 @@ import {
|
||||
normalizeStoredHostProfile,
|
||||
orderHostsLocalFirst,
|
||||
pinRelayProtectedSecurityInProfiles,
|
||||
readHostRegistry,
|
||||
relayConnectionFromOffer,
|
||||
resolveActiveHostServerId,
|
||||
upsertHostConnectionInProfiles,
|
||||
writeHostRegistry,
|
||||
type HostConnection,
|
||||
type HostProfile,
|
||||
} from "./host-connection";
|
||||
@@ -87,6 +89,25 @@ describe("normalizeStoredHostProfile", () => {
|
||||
expect(profile?.connections[0]).not.toHaveProperty("password");
|
||||
});
|
||||
|
||||
it("drops a connection kind this build doesn't know and keeps the host", () => {
|
||||
const profile = normalizeStoredHostProfile({
|
||||
serverId: "srv_mixed",
|
||||
password: "secret",
|
||||
connections: [
|
||||
{ id: "future:1", type: "futureKind", address: "future.example.com" },
|
||||
{ id: "direct:lan:6767", type: "directTcp", endpoint: "lan:6767", futureField: true },
|
||||
{ id: "direct:remote:6767", type: "directTcp", endpoint: "remote:6767" },
|
||||
],
|
||||
preferredConnectionId: "direct:remote:6767",
|
||||
});
|
||||
|
||||
expect(profile?.password).toBe("secret");
|
||||
expect(profile?.connections).toEqual([
|
||||
{ id: "direct:remote:6767", type: "directTcp", endpoint: "remote:6767", useTls: false },
|
||||
]);
|
||||
expect(profile?.preferredConnectionId).toBe("direct:remote:6767");
|
||||
});
|
||||
|
||||
it("preserves legacy relay ids when TLS is absent", () => {
|
||||
const profile = normalizeStoredHostProfile({
|
||||
serverId: "srv_relay",
|
||||
@@ -177,6 +198,59 @@ describe("normalizeStoredHostProfile", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("readHostRegistry and writeHostRegistry", () => {
|
||||
const direct: HostConnection = {
|
||||
id: "direct:lan:6767",
|
||||
type: "directTcp",
|
||||
endpoint: "lan:6767",
|
||||
useTls: false,
|
||||
};
|
||||
const future = { id: "future:1", type: "futureKind", address: "future.example.com" };
|
||||
|
||||
it("writes back every entry it could not read", () => {
|
||||
const unreadableHost = { serverId: "srv_future", connections: [future] };
|
||||
const hostWithFutureField = { serverId: "srv_field", connections: [direct], futureField: 1 };
|
||||
const stored = [
|
||||
{ ...makeHost("srv_a"), connections: [direct, future] },
|
||||
unreadableHost,
|
||||
hostWithFutureField,
|
||||
"not a host",
|
||||
];
|
||||
|
||||
const { hosts, unreadable } = readHostRegistry(stored);
|
||||
expect(hosts.map((host) => host.serverId)).toEqual(["srv_a"]);
|
||||
expect(hosts[0]?.connections).toEqual([direct]);
|
||||
|
||||
expect(writeHostRegistry(hosts, unreadable)).toEqual([
|
||||
{ ...hosts[0], connections: [direct, future] },
|
||||
unreadableHost,
|
||||
hostWithFutureField,
|
||||
"not a host",
|
||||
]);
|
||||
});
|
||||
|
||||
it("writes a host saved again by this build in place of the entry it could not read", () => {
|
||||
const { hosts, unreadable } = readHostRegistry([{ serverId: "srv_a", connections: [future] }]);
|
||||
expect(hosts).toEqual([]);
|
||||
|
||||
const saved = { ...makeHost("srv_a"), connections: [direct] };
|
||||
expect(writeHostRegistry([saved], unreadable)).toEqual([saved]);
|
||||
});
|
||||
|
||||
it("moves a stored direct TCP password to its host next to a connection it can't read", () => {
|
||||
const registry = readHostRegistry([
|
||||
{
|
||||
serverId: "srv_legacy",
|
||||
connections: [future, { type: "directTcp", endpoint: "lan:6767", password: "old-secret" }],
|
||||
},
|
||||
]);
|
||||
|
||||
expect(registry.movedConnectionPassword).toBe(true);
|
||||
expect(registry.hosts[0]?.password).toBe("old-secret");
|
||||
expect(registry.hosts[0]?.connections).toEqual([direct]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("createRemoteSshHostConnection", () => {
|
||||
it("keeps optional SSH settings absent", () => {
|
||||
expect(createRemoteSshHostConnection({ host: "build-box" })).toEqual({
|
||||
|
||||
@@ -522,12 +522,12 @@ const StoredHostProfileSchema = z.strictObject({
|
||||
label: z.string().optional(),
|
||||
appearance: HostAppearanceSchema.optional(),
|
||||
lifecycle: z.strictObject({}).optional(),
|
||||
connections: z.array(StoredHostConnectionSchema).min(1),
|
||||
// Read one by one, so a connection kind another build wrote skips only that connection.
|
||||
connections: z.array(z.unknown()).min(1),
|
||||
preferredConnectionId: z.string().nullable().optional(),
|
||||
createdAt: z.string().datetime({ offset: true }).optional(),
|
||||
updatedAt: z.string().datetime({ offset: true }).optional(),
|
||||
});
|
||||
export const StoredHostRegistrySchema = z.array(StoredHostProfileSchema);
|
||||
type StoredHostConnection = z.infer<typeof StoredHostConnectionSchema>;
|
||||
|
||||
function normalizeStoredConnection(connection: StoredHostConnection): HostConnection | null {
|
||||
@@ -590,20 +590,37 @@ function normalizeStoredConnection(connection: StoredHostConnection): HostConnec
|
||||
}
|
||||
|
||||
export function normalizeStoredHostProfile(entry: unknown): HostProfile | null {
|
||||
return readStoredHost(entry)?.profile ?? null;
|
||||
}
|
||||
|
||||
interface StoredHostRead {
|
||||
profile: HostProfile;
|
||||
unreadableConnections: unknown[];
|
||||
movedConnectionPassword: boolean;
|
||||
}
|
||||
|
||||
function readStoredHost(entry: unknown): StoredHostRead | null {
|
||||
const result = StoredHostProfileSchema.safeParse(entry);
|
||||
if (!result.success) {
|
||||
return null;
|
||||
}
|
||||
const record = result.data;
|
||||
const serverId = record.serverId;
|
||||
const storedConnections: StoredHostConnection[] = [];
|
||||
const unreadableConnections: unknown[] = [];
|
||||
for (const stored of record.connections) {
|
||||
const parsed = StoredHostConnectionSchema.safeParse(stored);
|
||||
if (parsed.success) storedConnections.push(parsed.data);
|
||||
else unreadableConnections.push(stored);
|
||||
}
|
||||
// COMPAT(connectionPassword): added in v0.9.1, remove after 2027-03-24 once stored direct passwords have migrated.
|
||||
const legacyPassword = record.connections.find(
|
||||
const legacyPassword = storedConnections.find(
|
||||
(connection) => connection.type === "directTcp" && connection.password,
|
||||
);
|
||||
const password =
|
||||
record.password ?? (legacyPassword?.type === "directTcp" ? legacyPassword.password : undefined);
|
||||
|
||||
const connections = record.connections
|
||||
const connections = storedConnections
|
||||
.map((connection) => normalizeStoredConnection(connection))
|
||||
.filter((connection): connection is HostConnection => connection !== null);
|
||||
if (connections.length === 0) {
|
||||
@@ -620,18 +637,90 @@ export function normalizeStoredHostProfile(entry: unknown): HostProfile | null {
|
||||
: (connections[0]?.id ?? null);
|
||||
|
||||
return {
|
||||
serverId,
|
||||
...(password ? { password } : {}),
|
||||
label,
|
||||
appearance: record.appearance ?? defaultHostAppearance(),
|
||||
lifecycle: defaultLifecycle(),
|
||||
connections,
|
||||
preferredConnectionId,
|
||||
createdAt: record.createdAt ?? now,
|
||||
updatedAt: record.updatedAt ?? now,
|
||||
profile: {
|
||||
serverId,
|
||||
...(password ? { password } : {}),
|
||||
label,
|
||||
appearance: record.appearance ?? defaultHostAppearance(),
|
||||
lifecycle: defaultLifecycle(),
|
||||
connections,
|
||||
preferredConnectionId,
|
||||
createdAt: record.createdAt ?? now,
|
||||
updatedAt: record.updatedAt ?? now,
|
||||
},
|
||||
unreadableConnections,
|
||||
movedConnectionPassword: legacyPassword !== undefined,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Stored registry entries this build can't read, such as a connection kind added by a newer
|
||||
* build. `writeHostRegistry` writes them back so that build still finds them.
|
||||
*/
|
||||
export interface UnreadableHostEntries {
|
||||
hosts: unknown[];
|
||||
connectionsByServerId: Map<string, unknown[]>;
|
||||
}
|
||||
|
||||
export function readHostRegistry(stored: unknown[]): {
|
||||
hosts: HostProfile[];
|
||||
unreadable: UnreadableHostEntries;
|
||||
// COMPAT(connectionPassword): added in v0.9.1, remove after 2027-03-24 with stored-password migration.
|
||||
movedConnectionPassword: boolean;
|
||||
} {
|
||||
const hosts: HostProfile[] = [];
|
||||
const unreadable: UnreadableHostEntries = { hosts: [], connectionsByServerId: new Map() };
|
||||
let movedConnectionPassword = false;
|
||||
for (const entry of stored) {
|
||||
const read = readStoredHost(entry);
|
||||
if (!read) {
|
||||
unreadable.hosts.push(entry);
|
||||
continue;
|
||||
}
|
||||
hosts.push(read.profile);
|
||||
if (read.unreadableConnections.length > 0) {
|
||||
unreadable.connectionsByServerId.set(read.profile.serverId, read.unreadableConnections);
|
||||
}
|
||||
movedConnectionPassword ||= read.movedConnectionPassword;
|
||||
}
|
||||
return { hosts, unreadable, movedConnectionPassword };
|
||||
}
|
||||
|
||||
export function writeHostRegistry(
|
||||
hosts: HostProfile[],
|
||||
unreadable: UnreadableHostEntries,
|
||||
): unknown[] {
|
||||
const savedServerIds = new Set(hosts.map((host) => host.serverId));
|
||||
const written: unknown[] = hosts.map((host) => {
|
||||
const kept = unreadable.connectionsByServerId.get(host.serverId);
|
||||
return kept ? { ...host, connections: [...host.connections, ...kept] } : host;
|
||||
});
|
||||
for (const entry of unreadable.hosts) {
|
||||
// A host this build saved again replaces the entry it couldn't read.
|
||||
const serverId = readStoredServerId(entry);
|
||||
if (serverId === null || !savedServerIds.has(serverId)) written.push(entry);
|
||||
}
|
||||
return written;
|
||||
}
|
||||
|
||||
/** Drops the entries this build couldn't read for a host you removed. */
|
||||
export function forgetUnreadableHost(
|
||||
unreadable: UnreadableHostEntries,
|
||||
serverId: string,
|
||||
): UnreadableHostEntries {
|
||||
const connectionsByServerId = new Map(unreadable.connectionsByServerId);
|
||||
connectionsByServerId.delete(serverId);
|
||||
return {
|
||||
hosts: unreadable.hosts.filter((entry) => readStoredServerId(entry) !== serverId),
|
||||
connectionsByServerId,
|
||||
};
|
||||
}
|
||||
|
||||
function readStoredServerId(entry: unknown): string | null {
|
||||
if (typeof entry !== "object" || entry === null || !("serverId" in entry)) return null;
|
||||
return typeof entry.serverId === "string" ? entry.serverId.trim() : null;
|
||||
}
|
||||
|
||||
export function hostHasConnection(host: HostProfile, connection: HostConnection): boolean {
|
||||
return host.connections.some((existing) => hostConnectionEquals(existing, connection));
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@getpaseo/cli",
|
||||
"version": "0.16.0",
|
||||
"version": "0.16.2",
|
||||
"description": "Paseo CLI - control your AI coding agents from the command line",
|
||||
"license": "Apache-2.0",
|
||||
"bin": {
|
||||
@@ -29,9 +29,9 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@clack/prompts": "^1.0.0",
|
||||
"@getpaseo/client": "0.16.0",
|
||||
"@getpaseo/protocol": "0.16.0",
|
||||
"@getpaseo/server": "0.16.0",
|
||||
"@getpaseo/client": "0.16.2",
|
||||
"@getpaseo/protocol": "0.16.2",
|
||||
"@getpaseo/server": "0.16.2",
|
||||
"chalk": "^5.3.0",
|
||||
"commander": "^12.0.0",
|
||||
"mime-types": "^2.1.35",
|
||||
|
||||
@@ -47,7 +47,7 @@ export function addSendOptions(cmd: Command): Command {
|
||||
.addOption(
|
||||
new Option(
|
||||
"--behavior <behavior>",
|
||||
"Active-turn behavior (agent default: steer waits for turn end; otherwise: interrupt)",
|
||||
"Active-turn behavior (agent default: steer; otherwise: interrupt)",
|
||||
).choices(["interrupt", "steer"]),
|
||||
)
|
||||
.option("--no-wait", "Return immediately without waiting for completion");
|
||||
@@ -218,7 +218,7 @@ export async function runSendCommand(
|
||||
status: receipt.deliveryStatus ?? "sent",
|
||||
message:
|
||||
receipt.deliveryStatus === "queued"
|
||||
? "Message queued for delivery after two quiet seconds and the current turn ends, unless interrupt was requested"
|
||||
? "Message queued for delivery after two quiet seconds"
|
||||
: "Message sent, not waiting for completion",
|
||||
},
|
||||
schema: agentSendSchema,
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import path from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { buildWorkspaceSource } from "./create.js";
|
||||
|
||||
@@ -8,6 +9,49 @@ describe("workspace create source", () => {
|
||||
).toEqual({ kind: "directory", path: "/tmp/project", projectId: "project-1" });
|
||||
});
|
||||
|
||||
it("resolves a relative path against the directory the command runs in", () => {
|
||||
const daemonTarget = { kind: "instance" as const, home: "/tmp/paseo-home" };
|
||||
expect(buildWorkspaceSource({ daemonTarget, isolation: "local", path: "." })).toEqual({
|
||||
kind: "directory",
|
||||
path: process.cwd(),
|
||||
});
|
||||
expect(
|
||||
buildWorkspaceSource({ daemonTarget, isolation: "worktree", path: "../sibling" }),
|
||||
).toEqual({
|
||||
kind: "worktree",
|
||||
cwd: path.resolve(process.cwd(), "../sibling"),
|
||||
action: "branch-off",
|
||||
});
|
||||
});
|
||||
|
||||
it("sends a relative path to an explicit daemon endpoint as written", () => {
|
||||
const daemonTarget = { kind: "endpoint" as const, host: "other-box:6767" };
|
||||
expect(buildWorkspaceSource({ daemonTarget, isolation: "local", path: "repo" })).toEqual({
|
||||
kind: "directory",
|
||||
path: "repo",
|
||||
});
|
||||
});
|
||||
|
||||
it("passes an absolute path from another operating system through unchanged", () => {
|
||||
expect(buildWorkspaceSource({ isolation: "local", path: "C:\\repos\\project" })).toEqual({
|
||||
kind: "directory",
|
||||
path: "C:\\repos\\project",
|
||||
});
|
||||
});
|
||||
|
||||
it("leaves a home-relative path for the daemon to expand", () => {
|
||||
const daemonTarget = { kind: "instance" as const, home: "/tmp/paseo-home" };
|
||||
expect(buildWorkspaceSource({ daemonTarget, isolation: "local", path: "~/repo" })).toEqual({
|
||||
kind: "directory",
|
||||
path: "~/repo",
|
||||
});
|
||||
expect(buildWorkspaceSource({ daemonTarget, isolation: "worktree", path: "~" })).toEqual({
|
||||
kind: "worktree",
|
||||
cwd: "~",
|
||||
action: "branch-off",
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps branch names separate from managed worktree slugs", () => {
|
||||
expect(
|
||||
buildWorkspaceSource({
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
import { isAbsolute as isPosixAbsolute } from "node:path/posix";
|
||||
import { isAbsolute as isWindowsAbsolute } from "node:path/win32";
|
||||
import { resolve } from "node:path";
|
||||
import type { Command } from "commander";
|
||||
import { connectToDaemon, getDaemonHost } from "../../utils/client.js";
|
||||
import { resolveCallerAgentId } from "../../utils/caller-agent.js";
|
||||
import type { DaemonTarget } from "../../utils/daemon-target.js";
|
||||
import type { CommandError, CommandOptions, SingleResult } from "../../output/index.js";
|
||||
import { toWorkspaceRow, workspaceSchema, type WorkspaceRow } from "./shared.js";
|
||||
|
||||
@@ -121,12 +125,26 @@ function buildWorktreeWorkspaceSource(options: WorkspaceCreateOptions, path: str
|
||||
}
|
||||
}
|
||||
|
||||
// A relative --path names a directory relative to where the command runs, so
|
||||
// it is made absolute here for a local daemon, which would otherwise resolve
|
||||
// it against its own working directory. For an explicit endpoint the path is
|
||||
// sent as written, the same rule as resolveRepositoryDirectory. An absolute
|
||||
// path can target a daemon on a different operating system, and the daemon
|
||||
// expands a leading ~ to its own home directory.
|
||||
function resolveCallerPath(input: string, daemonTarget: DaemonTarget): string {
|
||||
const isHomeRelative = input === "~" || input.startsWith("~/");
|
||||
if (isHomeRelative || isPosixAbsolute(input) || isWindowsAbsolute(input)) return input;
|
||||
return daemonTarget.kind === "instance" ? resolve(input) : input;
|
||||
}
|
||||
|
||||
export function buildWorkspaceSource(options: WorkspaceCreateOptions) {
|
||||
const callerPath =
|
||||
options.path === undefined ? undefined : resolveCallerPath(options.path, options.daemonTarget);
|
||||
if (options.isolation === "local") {
|
||||
return buildLocalWorkspaceSource(options, options.path ?? process.cwd());
|
||||
return buildLocalWorkspaceSource(options, callerPath ?? process.cwd());
|
||||
}
|
||||
if (options.isolation === "worktree") {
|
||||
const sourcePath = options.path ?? (options.project ? undefined : process.cwd());
|
||||
const sourcePath = callerPath ?? (options.project ? undefined : process.cwd());
|
||||
return buildWorktreeWorkspaceSource(options, sourcePath);
|
||||
}
|
||||
throw new Error(`Unsupported workspace isolation: ${String(options.isolation)}`);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@getpaseo/client",
|
||||
"version": "0.16.0",
|
||||
"version": "0.16.2",
|
||||
"description": "Paseo client SDK package",
|
||||
"license": "Apache-2.0",
|
||||
"files": [
|
||||
@@ -49,8 +49,8 @@
|
||||
"measure:diff-materialization": "tsx scripts/measure-diff-materialization.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"@getpaseo/protocol": "0.16.0",
|
||||
"@getpaseo/relay": "0.16.0",
|
||||
"@getpaseo/protocol": "0.16.2",
|
||||
"@getpaseo/relay": "0.16.2",
|
||||
"ws": "^8.20.0",
|
||||
"zod": "^4.4.3"
|
||||
},
|
||||
|
||||
@@ -483,7 +483,7 @@ export interface SendMessageOptions {
|
||||
sourceAgentServerId?: string;
|
||||
sessionMode?: string;
|
||||
messageId?: string;
|
||||
/** Agent sources wait for turn end unless interrupt is explicit. Human sources default to interrupt. */
|
||||
/** What happens when the agent is mid-turn. The daemon interrupts the turn when omitted. */
|
||||
activeTurnBehavior?: ActiveTurnBehavior;
|
||||
images?: Array<{ data: string; mimeType: string }>;
|
||||
attachments?: SendAgentMessageRequest["attachments"];
|
||||
|
||||
@@ -11,9 +11,6 @@ if not exist "%APP_EXECUTABLE%" (
|
||||
|
||||
set "ELECTRON_RUN_AS_NODE=1"
|
||||
set "PASEO_NODE_ENV=production"
|
||||
rem PASEO_DESKTOP_MANAGED marks daemons started through this bundled CLI as
|
||||
rem desktop-managed, so the desktop app restarts them when it upgrades.
|
||||
set "PASEO_DESKTOP_MANAGED=1"
|
||||
set "PASEO_CLI=%~f0"
|
||||
"%APP_EXECUTABLE%" --disable-warning=DEP0040 "%RESOURCES_DIR%\app.asar.unpacked\dist\daemon\node-entrypoint-runner.js" node-script "%RESOURCES_DIR%\app.asar\node_modules\@getpaseo\cli\dist\index.js" %*
|
||||
exit /b %errorlevel%
|
||||
|
||||
@@ -41,16 +41,24 @@ savePersistedConfig(home, {
|
||||
},
|
||||
});
|
||||
const main = path.join(root, "main.cjs");
|
||||
const updatedMain = path.join(root, "updated-main.cjs");
|
||||
const managerPath = path.join(repo, "packages/desktop/dist/daemon/daemon-manager.js");
|
||||
const desktopMain = (setup) =>
|
||||
`const { app } = require("electron"); ${setup} app.setPath("userData", ${JSON.stringify(path.join(root, "user-data"))}); app.whenReady().then(() => { global.lifecycle = require(${JSON.stringify(managerPath)}); });`;
|
||||
await writeFile(main, desktopMain(""));
|
||||
// An unpackaged Desktop reads its version from packages/desktop/package.json. This entry
|
||||
// reports a newer version, standing in for the Desktop an update installs.
|
||||
await writeFile(
|
||||
main,
|
||||
`const { app } = require("electron"); app.setPath("userData", ${JSON.stringify(path.join(root, "user-data"))}); app.whenReady().then(() => { global.lifecycle = require(${JSON.stringify(managerPath)}); });`,
|
||||
updatedMain,
|
||||
desktopMain(
|
||||
`const fs = require("node:fs"); const path = require("node:path"); const readFileSync = fs.readFileSync; fs.readFileSync = (file, ...rest) => typeof file === "string" && path.relative(${JSON.stringify(path.join(repo, "packages/desktop"))}, file) === "package.json" ? JSON.stringify({ version: "999.0.0" }) : readFileSync(file, ...rest);`,
|
||||
),
|
||||
);
|
||||
let desktop;
|
||||
let captured;
|
||||
async function openDesktop() {
|
||||
async function openDesktop(entry = main) {
|
||||
desktop = await electron.launch({
|
||||
args: ["--no-sandbox", "--ozone-platform=headless", main],
|
||||
args: ["--no-sandbox", "--ozone-platform=headless", entry],
|
||||
env: {
|
||||
...env,
|
||||
PASEO_LISTEN: "127.0.0.1:1",
|
||||
@@ -78,27 +86,31 @@ async function command(name, args) {
|
||||
);
|
||||
}
|
||||
try {
|
||||
// Simulate a legacy independent launch that carries the old Desktop flag.
|
||||
// A daemon the user started through the CLI, which Desktop must never stop on its own.
|
||||
// Older bundled CLIs exported PASEO_DESKTOP_MANAGED, and the CLI launch must not record it.
|
||||
const launch = await startDaemonInstance({
|
||||
home,
|
||||
command: process.execPath,
|
||||
args: [path.join(repo, "packages/server/dist/scripts/supervisor-entrypoint.js")],
|
||||
env,
|
||||
env: { ...env, PASEO_DESKTOP_MANAGED: "1" },
|
||||
mode: "deployment",
|
||||
desktopManaged: true,
|
||||
timeoutMs: 30_000,
|
||||
});
|
||||
captured = launch.instance;
|
||||
await openDesktop();
|
||||
const attached = await command("start_desktop_daemon");
|
||||
assert.equal(attached.pid, captured.pid);
|
||||
assert.equal(attached.desktopManaged, true);
|
||||
assert.equal(attached.desktopManaged, false);
|
||||
assert.equal(attached.ownedByDesktop, false);
|
||||
for (const reason of ["quit", "settings", "app_update", "host_remove", "version_mismatch"]) {
|
||||
const status = await command("stop_desktop_daemon", { reason });
|
||||
assert.equal(status.pid, captured.pid, `${reason} stopped an attached daemon`);
|
||||
process.kill(captured.pid, 0);
|
||||
}
|
||||
await closeDesktop();
|
||||
await openDesktop(updatedMain);
|
||||
const afterUpdate = await command("start_desktop_daemon");
|
||||
assert.equal(afterUpdate.pid, captured.pid, "a newer Desktop replaced a daemon the user started");
|
||||
const restarted = await command("restart_desktop_daemon");
|
||||
assert.equal(restarted.pid, captured.pid);
|
||||
await assert.rejects(
|
||||
@@ -134,18 +146,37 @@ try {
|
||||
desktop = null;
|
||||
process.kill(captured.pid, 0);
|
||||
await openDesktop();
|
||||
assert.equal((await command("start_desktop_daemon")).ownedByDesktop, false);
|
||||
await command("stop_desktop_daemon", { reason: "quit" });
|
||||
// The next session attaches to the daemon Desktop launched before it quit.
|
||||
const survivor = await command("start_desktop_daemon");
|
||||
assert.equal(survivor.pid, captured.pid);
|
||||
assert.equal(survivor.desktopManaged, true);
|
||||
assert.equal(survivor.ownedByDesktop, false);
|
||||
for (const reason of ["quit", "settings", "host_remove"]) {
|
||||
await command("stop_desktop_daemon", { reason });
|
||||
process.kill(captured.pid, 0);
|
||||
}
|
||||
// With management off, Desktop leaves the daemon running through an update.
|
||||
await command("patch_desktop_settings", { daemon: { manageBuiltInDaemon: false } });
|
||||
await command("stop_desktop_daemon", { reason: "app_update" });
|
||||
process.kill(captured.pid, 0);
|
||||
await command("stop_desktop_daemon", {
|
||||
reason: "manual_ipc",
|
||||
pid: captured.pid,
|
||||
startedAt: captured.startedAt,
|
||||
});
|
||||
await command("patch_desktop_settings", { daemon: { manageBuiltInDaemon: true } });
|
||||
// Installing an update stops it, so the updated Desktop starts its own daemon.
|
||||
const beforeInstall = await command("stop_desktop_daemon", { reason: "app_update" });
|
||||
assert.equal(beforeInstall.status, "stopped", "app_update left Desktop's daemon running");
|
||||
captured = null;
|
||||
const next = await command("start_desktop_daemon");
|
||||
captured = await readDaemonInstance(home);
|
||||
assert.equal(next.ownedByDesktop, true);
|
||||
await closeDesktop();
|
||||
process.kill(captured.pid, 0);
|
||||
// A newer Desktop replaces the daemon an older Desktop launched and kept running.
|
||||
const outdated = captured;
|
||||
await openDesktop(updatedMain);
|
||||
const replaced = await command("start_desktop_daemon");
|
||||
captured = await readDaemonInstance(home);
|
||||
assert.notEqual(replaced.pid, outdated.pid, "a newer Desktop kept the outdated daemon");
|
||||
assert.equal(replaced.ownedByDesktop, true);
|
||||
assert.throws(() => process.kill(outdated.pid, 0), "the outdated daemon is still running");
|
||||
await command("stop_desktop_daemon", { reason: "quit" });
|
||||
assert.equal(await readDaemonInstance(home), null);
|
||||
captured = null;
|
||||
@@ -195,7 +226,7 @@ try {
|
||||
);
|
||||
}
|
||||
console.log(
|
||||
"PASS: attached legacy daemon survives automatic actions; explicit captured stop, owned launch, managed settings, worker restart, and next-session attachment.",
|
||||
"PASS: a user-started daemon survives automatic actions and updates; explicit captured stop, owned launch, managed settings, worker restart, next-session attachment, and update replacement of an earlier session's daemon.",
|
||||
);
|
||||
} finally {
|
||||
await closeDesktop();
|
||||
|
||||
@@ -5,18 +5,25 @@ import { fileURLToPath } from "node:url";
|
||||
import { _electron as electron, expect } from "playwright/test";
|
||||
|
||||
const root = await mkdtemp(path.join(tmpdir(), "paseo-window-startup-"));
|
||||
const modulePath = fileURLToPath(new URL("../dist/window/show-when-ready.js", import.meta.url));
|
||||
const showWhenReadyPath = fileURLToPath(
|
||||
new URL("../dist/window/show-when-ready.js", import.meta.url),
|
||||
);
|
||||
const rendererRecoveryPath = fileURLToPath(
|
||||
new URL("../dist/window/renderer-recovery.js", import.meta.url),
|
||||
);
|
||||
|
||||
async function launchWindowWithoutHiddenFrames() {
|
||||
async function launchDesktopWindow() {
|
||||
const main = path.join(root, "main.cjs");
|
||||
await writeFile(
|
||||
main,
|
||||
`const { app, BrowserWindow } = require("electron");
|
||||
const { showWindowWhenReady } = require(${JSON.stringify(modulePath)});
|
||||
const { showWindowWhenReady } = require(${JSON.stringify(showWhenReadyPath)});
|
||||
const { reloadWhenRendererExits } = require(${JSON.stringify(rendererRecoveryPath)});
|
||||
app.setPath("userData", ${JSON.stringify(path.join(root, "user-data"))});
|
||||
app.whenReady().then(async () => {
|
||||
const win = global.mainWindow = new BrowserWindow({ show: false, paintWhenInitiallyHidden: false });
|
||||
showWindowWhenReady(win, { showOnLoad: true });
|
||||
reloadWhenRendererExits(win);
|
||||
await win.loadURL("data:text/html,<h1>Desktop ready</h1>");
|
||||
global.visibleAfterLoad = win.isVisible();
|
||||
});`,
|
||||
@@ -37,11 +44,32 @@ async function expectLoadedDesktopIsShown(desktop) {
|
||||
await expect(page.getByRole("heading", { name: "Desktop ready" })).toBeVisible();
|
||||
}
|
||||
|
||||
function rendererPid(desktop) {
|
||||
return desktop.evaluate(() => global.mainWindow.webContents.getOSProcessId());
|
||||
}
|
||||
|
||||
async function expectDesktopReloadsAfterRendererIsTerminated(desktop) {
|
||||
const terminated = await rendererPid(desktop);
|
||||
process.kill(terminated, "SIGTERM");
|
||||
await expect.poll(() => rendererPid(desktop), { timeout: 15_000 }).not.toBe(terminated);
|
||||
await expect
|
||||
.poll(
|
||||
() =>
|
||||
desktop.evaluate(() =>
|
||||
global.mainWindow.webContents.executeJavaScript("document.body.textContent"),
|
||||
),
|
||||
{ timeout: 15_000 },
|
||||
)
|
||||
.toBe("Desktop ready");
|
||||
}
|
||||
|
||||
let desktop;
|
||||
try {
|
||||
desktop = await launchWindowWithoutHiddenFrames();
|
||||
desktop = await launchDesktopWindow();
|
||||
await expectLoadedDesktopIsShown(desktop);
|
||||
console.log("Loaded desktop is visible without hidden compositor frames");
|
||||
await expectDesktopReloadsAfterRendererIsTerminated(desktop);
|
||||
console.log("Desktop reloads its window after the renderer is terminated");
|
||||
} finally {
|
||||
await desktop?.close();
|
||||
await rm(root, { recursive: true, force: true });
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@getpaseo/desktop",
|
||||
"version": "0.16.0",
|
||||
"version": "0.16.2",
|
||||
"private": true,
|
||||
"description": "Paseo desktop app (Electron wrapper)",
|
||||
"homepage": "https://paseo.sh",
|
||||
|
||||
@@ -269,7 +269,7 @@ function normalizeVersion(version: string | null): string | null {
|
||||
}
|
||||
|
||||
function shouldRestartForVersion(current: DesktopDaemonStatus): boolean {
|
||||
if (!current.ownedByDesktop) return false;
|
||||
if (!current.desktopManaged) return false;
|
||||
const appVersion = normalizeVersion(resolveDesktopAppVersion());
|
||||
const daemonVersion = normalizeVersion(current.version);
|
||||
return Boolean(appVersion && daemonVersion && appVersion !== daemonVersion);
|
||||
@@ -336,12 +336,13 @@ export async function stopDesktopDaemon(
|
||||
): Promise<DesktopDaemonStatus> {
|
||||
const home = getPaseoHome();
|
||||
const instance = await readDaemonInstance(home);
|
||||
const owned = Boolean(
|
||||
const launchedThisSession = Boolean(
|
||||
instance &&
|
||||
ownedLaunch &&
|
||||
ownedLaunch.home === home &&
|
||||
isSameDaemonInstance(instance, ownedLaunch.instance),
|
||||
);
|
||||
const owned = launchedThisSession || (await replacesDesktopDaemon(reason, instance));
|
||||
const explicit =
|
||||
reason === "manual_ipc" &&
|
||||
confirmedInstance &&
|
||||
@@ -361,10 +362,28 @@ export async function stopDesktopDaemon(
|
||||
keepTerminals,
|
||||
});
|
||||
await stopCapturedDaemon({ home, instance, reason, keepTerminals });
|
||||
if (owned) ownedLaunch = null;
|
||||
if (launchedThisSession) ownedLaunch = null;
|
||||
return resolveDesktopDaemonStatus();
|
||||
}
|
||||
|
||||
/** An app update or a version mismatch replaces the daemon with the one this Desktop bundles. */
|
||||
function isReplacement(reason: DesktopDaemonStopReason): boolean {
|
||||
return reason === "app_update" || reason === "version_mismatch";
|
||||
}
|
||||
|
||||
/**
|
||||
* While Desktop manages the built-in daemon, a replacement applies to every daemon Desktop
|
||||
* launched, which `paseo.pid` records as `desktopManaged`. That includes one an earlier Desktop
|
||||
* session left running. Other automatic stops apply only to a daemon this session launched.
|
||||
*/
|
||||
async function replacesDesktopDaemon(
|
||||
reason: DesktopDaemonStopReason,
|
||||
instance: DaemonInstance | null,
|
||||
): Promise<boolean> {
|
||||
if (!isReplacement(reason) || instance?.desktopManaged !== true) return false;
|
||||
return (await getDesktopSettingsStore().get()).daemon.manageBuiltInDaemon;
|
||||
}
|
||||
|
||||
export interface StopCapturedDaemonInput {
|
||||
home: string;
|
||||
instance: DaemonInstance;
|
||||
@@ -428,7 +447,7 @@ export function keepsTerminalsOnStop(
|
||||
platform: NodeJS.Platform,
|
||||
): boolean {
|
||||
if (platform === "win32") return false;
|
||||
return reason === "app_update" || reason === "version_mismatch";
|
||||
return isReplacement(reason);
|
||||
}
|
||||
|
||||
async function restartDaemon(): Promise<DesktopDaemonStatus> {
|
||||
|
||||
@@ -46,6 +46,7 @@ import {
|
||||
buildStandardContextMenuItems,
|
||||
} from "./window/window-manager.js";
|
||||
import { setupDarwinCompositorWatchdog } from "./window/compositor-watchdog/index.js";
|
||||
import { reloadWhenRendererExits } from "./window/renderer-recovery.js";
|
||||
import { showWindowWhenReady } from "./window/show-when-ready.js";
|
||||
import { resolveDesktopWindowChromeMode, windowChromeModeArgument } from "./window/chrome.js";
|
||||
import { registerDialogHandlers } from "./features/dialogs.js";
|
||||
@@ -734,6 +735,7 @@ async function createWindow(
|
||||
}
|
||||
|
||||
setupDarwinCompositorWatchdog(mainWindow);
|
||||
reloadWhenRendererExits(mainWindow);
|
||||
setupWindowResizeEvents(mainWindow);
|
||||
if (windowStateStore) {
|
||||
setupWindowStatePersistence(mainWindow, windowStateStore);
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
import { EventEmitter } from "node:events";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { reloadWhenRendererExits } from "./renderer-recovery.js";
|
||||
|
||||
class Contents extends EventEmitter {
|
||||
reloads = 0;
|
||||
url = "paseo://app/";
|
||||
getURL() {
|
||||
return this.url;
|
||||
}
|
||||
reload() {
|
||||
this.reloads += 1;
|
||||
}
|
||||
exit(reason: string) {
|
||||
this.emit("render-process-gone", {}, { reason, exitCode: reason === "clean-exit" ? 0 : 15 });
|
||||
}
|
||||
}
|
||||
|
||||
class Window {
|
||||
webContents = new Contents();
|
||||
destroyed = false;
|
||||
isDestroyed() {
|
||||
return this.destroyed;
|
||||
}
|
||||
}
|
||||
|
||||
function recoverableWindow() {
|
||||
const win = new Window();
|
||||
let time = 0;
|
||||
reloadWhenRendererExits(win, { now: () => time });
|
||||
return {
|
||||
win,
|
||||
advance(ms: number) {
|
||||
time += ms;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe("reloadWhenRendererExits", () => {
|
||||
it("reloads the window when its renderer is killed", () => {
|
||||
const { win } = recoverableWindow();
|
||||
win.webContents.exit("killed");
|
||||
expect(win.webContents.reloads).toBe(1);
|
||||
});
|
||||
|
||||
it("reloads after a renderer crash or out-of-memory exit", () => {
|
||||
const { win, advance } = recoverableWindow();
|
||||
win.webContents.exit("crashed");
|
||||
advance(120_000);
|
||||
win.webContents.exit("oom");
|
||||
expect(win.webContents.reloads).toBe(2);
|
||||
});
|
||||
|
||||
it("leaves a renderer that exited cleanly alone", () => {
|
||||
const { win } = recoverableWindow();
|
||||
win.webContents.exit("clean-exit");
|
||||
expect(win.webContents.reloads).toBe(0);
|
||||
});
|
||||
|
||||
it("leaves a renderer that exits before the first page commits to Chromium", () => {
|
||||
const { win } = recoverableWindow();
|
||||
win.webContents.url = "";
|
||||
win.webContents.exit("killed");
|
||||
expect(win.webContents.reloads).toBe(0);
|
||||
});
|
||||
|
||||
it("leaves a closed window closed", () => {
|
||||
const { win } = recoverableWindow();
|
||||
win.destroyed = true;
|
||||
win.webContents.exit("killed");
|
||||
expect(win.webContents.reloads).toBe(0);
|
||||
});
|
||||
|
||||
it("stops reloading a renderer that keeps exiting, and recovers again later", () => {
|
||||
const { win, advance } = recoverableWindow();
|
||||
for (let exit = 0; exit < 5; exit += 1) {
|
||||
win.webContents.exit("crashed");
|
||||
advance(1_000);
|
||||
}
|
||||
expect(win.webContents.reloads).toBe(3);
|
||||
|
||||
advance(60_000);
|
||||
win.webContents.exit("killed");
|
||||
expect(win.webContents.reloads).toBe(4);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,56 @@
|
||||
import log from "electron-log/main";
|
||||
|
||||
// A window whose renderer exits keeps its frame but shows nothing until it is
|
||||
// reloaded. Reload it, but stop when the renderer keeps exiting so a page that
|
||||
// crashes on load does not restart in a loop.
|
||||
const MAX_RELOADS_PER_WINDOW = 3;
|
||||
const RELOAD_WINDOW_MS = 60_000;
|
||||
|
||||
interface RendererExit {
|
||||
reason: string;
|
||||
exitCode: number;
|
||||
}
|
||||
|
||||
interface RecoverableWindow {
|
||||
isDestroyed(): boolean;
|
||||
webContents: {
|
||||
on(
|
||||
event: "render-process-gone",
|
||||
listener: (event: unknown, details: RendererExit) => void,
|
||||
): unknown;
|
||||
getURL(): string;
|
||||
reload(): void;
|
||||
};
|
||||
}
|
||||
|
||||
export function reloadWhenRendererExits(
|
||||
win: RecoverableWindow,
|
||||
options: { now?: () => number } = {},
|
||||
): void {
|
||||
const now = options.now ?? Date.now;
|
||||
let reloadTimes: number[] = [];
|
||||
|
||||
win.webContents.on("render-process-gone", (_event, details) => {
|
||||
if (details.reason === "clean-exit" || win.isDestroyed()) return;
|
||||
// Before the first page commits, Chromium finishes the navigation in a new
|
||||
// renderer by itself. Reloading then would abort the window's initial load.
|
||||
if (win.webContents.getURL() === "") return;
|
||||
|
||||
const time = now();
|
||||
reloadTimes = reloadTimes.filter((reloadTime) => time - reloadTime < RELOAD_WINDOW_MS);
|
||||
if (reloadTimes.length >= MAX_RELOADS_PER_WINDOW) {
|
||||
log.error(
|
||||
`[renderer-recovery] Renderer exited (${details.reason}, code ${details.exitCode}); ` +
|
||||
`not reloading after ${reloadTimes.length} reloads in the last minute`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
reloadTimes.push(time);
|
||||
log.warn(
|
||||
`[renderer-recovery] Renderer exited (${details.reason}, code ${details.exitCode}); ` +
|
||||
`reloading the window (reload ${reloadTimes.length} in the last minute)`,
|
||||
);
|
||||
win.webContents.reload();
|
||||
});
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@getpaseo/expo-two-way-audio",
|
||||
"version": "0.16.0",
|
||||
"version": "0.16.2",
|
||||
"description": "Native module for two way audio streaming",
|
||||
"keywords": [
|
||||
"ExpoTwoWayAudio",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@getpaseo/highlight",
|
||||
"version": "0.16.0",
|
||||
"version": "0.16.2",
|
||||
"license": "Apache-2.0",
|
||||
"files": [
|
||||
"dist",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@getpaseo/plugin",
|
||||
"version": "0.16.0",
|
||||
"version": "0.16.2",
|
||||
"description": "Paseo plugin SDK package",
|
||||
"license": "Apache-2.0",
|
||||
"files": [
|
||||
@@ -78,8 +78,8 @@
|
||||
"use-sync-external-store": "^1.6.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@getpaseo/client": "0.16.0",
|
||||
"@getpaseo/protocol": "0.16.0",
|
||||
"@getpaseo/client": "0.16.2",
|
||||
"@getpaseo/protocol": "0.16.2",
|
||||
"@types/node": "^20.9.0",
|
||||
"@types/react": "~19.2.0",
|
||||
"react": "19.2.3",
|
||||
@@ -89,8 +89,8 @@
|
||||
"zod": "^4.4.3"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@getpaseo/client": "0.16.0",
|
||||
"@getpaseo/protocol": "0.16.0",
|
||||
"@getpaseo/client": "0.16.2",
|
||||
"@getpaseo/protocol": "0.16.2",
|
||||
"react": ">=19.1.0 <20",
|
||||
"react-native": ">=0.81.5",
|
||||
"zod": "^4.4.3"
|
||||
|
||||
@@ -88,8 +88,6 @@ export interface PluginSessionOpenRequest {
|
||||
readonly background: boolean;
|
||||
readonly labels: Readonly<Record<string, string>>;
|
||||
readonly metadata: Readonly<Record<string, JsonValue>>;
|
||||
/** Instructions appended for this open; not saved on the agent. */
|
||||
appendSystemPrompt?: string[];
|
||||
tools: AgentToolDefinition[];
|
||||
env: Record<string, string>;
|
||||
mcpServers: NonNullable<AgentSessionConfig["mcpServers"]>;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@getpaseo/protocol",
|
||||
"version": "0.16.0",
|
||||
"version": "0.16.2",
|
||||
"description": "Paseo shared protocol schemas and wire types",
|
||||
"license": "Apache-2.0",
|
||||
"files": [
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@getpaseo/relay",
|
||||
"version": "0.16.0",
|
||||
"version": "0.16.2",
|
||||
"description": "Paseo relay for bridging daemon and client connections",
|
||||
"license": "Apache-2.0",
|
||||
"files": [
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@getpaseo/server",
|
||||
"version": "0.16.0",
|
||||
"version": "0.16.2",
|
||||
"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.246",
|
||||
"@anthropic-ai/claude-agent-sdk": "0.3.326",
|
||||
"@anthropic-ai/sdk": "^0.104.2",
|
||||
"@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",
|
||||
"@getpaseo/client": "0.16.2",
|
||||
"@getpaseo/highlight": "0.16.2",
|
||||
"@getpaseo/plugin": "0.16.2",
|
||||
"@getpaseo/protocol": "0.16.2",
|
||||
"@getpaseo/relay": "0.16.2",
|
||||
"@isaacs/ttlcache": "^2.1.4",
|
||||
"@modelcontextprotocol/sdk": "1.29.0",
|
||||
"@opencode-ai/sdk": "1.14.46",
|
||||
|
||||
@@ -26,8 +26,7 @@ import { buildStoredAgentPayload, toAgentPayload } from "./agent-projections.js"
|
||||
import type { ProviderOptions } from "@getpaseo/protocol/agent-types";
|
||||
import { projectTimelineRows } from "./timeline-projection.js";
|
||||
import { getOpenAgentTabLabel, PARENT_AGENT_ID_LABEL } from "@getpaseo/protocol/agent-labels";
|
||||
import { createAgentMessageDelivery } from "./agent-messages/index.js";
|
||||
import { AgentTurnBusyError, sendPreparedPromptToAgent, startAgentRun } from "./agent-prompt.js";
|
||||
import { startAgentRun } from "./agent-prompt.js";
|
||||
import { StaleProviderSessionError } from "./stale-provider-session-error.js";
|
||||
import { ensureAgentLoaded, ensureUnarchivedAgentLoaded } from "./agent-loading.js";
|
||||
import type { StoredAgentRecord } from "./agent-storage.js";
|
||||
@@ -674,48 +673,6 @@ async function startAndSteerThroughManager(
|
||||
return { manager, agentId: agent.id, workdir };
|
||||
}
|
||||
|
||||
test("OpenCode persistence excludes launch-only instructions from storage and clients", async () => {
|
||||
const workdir = mkdtempSync(join(tmpdir(), "agent-plugin-persistence-"));
|
||||
const harness = new V2Harness();
|
||||
harness.info.location.directory = workdir;
|
||||
const storage = new AgentStorage(join(workdir, "agents"), logger);
|
||||
const client = new OpenCodeV2AgentClient({ logger, runtime: harness.runtime });
|
||||
const manager = new AgentManager({
|
||||
clients: { opencode: client },
|
||||
registry: storage,
|
||||
logger,
|
||||
appendSystemPrompt: "Daemon instruction",
|
||||
pluginLifecycle: {
|
||||
emit: () => {},
|
||||
before: async (name, request) =>
|
||||
name === "agent.open.before"
|
||||
? { ...request, appendSystemPrompt: ["Plugin instruction"] }
|
||||
: request,
|
||||
},
|
||||
});
|
||||
const agent = await manager.createAgent({ provider: "opencode", cwd: workdir }, undefined, {
|
||||
workspaceId: undefined,
|
||||
});
|
||||
try {
|
||||
expect(harness.instructions.get("paseo")).toBe("Daemon instruction\n\nPlugin instruction");
|
||||
await manager.flush();
|
||||
const record = await storage.get(agent.id);
|
||||
expect(record?.persistence?.metadata).not.toHaveProperty("pluginAppendSystemPrompt");
|
||||
expect(record?.persistence?.metadata).not.toHaveProperty("daemonAppendSystemPrompt");
|
||||
const live = manager.getAgent(agent.id)!;
|
||||
expect(toAgentPayload(live).persistence?.metadata).not.toHaveProperty(
|
||||
"pluginAppendSystemPrompt",
|
||||
);
|
||||
expect(toAgentPayload(live).persistence?.metadata).not.toHaveProperty(
|
||||
"daemonAppendSystemPrompt",
|
||||
);
|
||||
} finally {
|
||||
await manager.closeAgent(agent.id);
|
||||
await client.shutdown();
|
||||
rmSync(workdir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("stops an OpenCode execution already active when its conversation is reopened", async () => {
|
||||
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-opencode-resume-"));
|
||||
onTestFinished(() => rmSync(workdir, { recursive: true, force: true }));
|
||||
@@ -3469,6 +3426,101 @@ test("cancelAgentRun succeeds when the provider queues completion before rejecti
|
||||
}
|
||||
});
|
||||
|
||||
test.each([
|
||||
{ binding: "foreground", agentId: "00000000-0000-4000-8000-000000000307" },
|
||||
{ binding: "autonomous", agentId: "00000000-0000-4000-8000-000000000308" },
|
||||
] as const)(
|
||||
"cancelAgentRun settles a $binding run bound to an already finalized turn",
|
||||
async ({ binding, agentId }) => {
|
||||
const fixture = await createControlledInterruptFixture({
|
||||
name: `interrupt-finalized-${binding}`,
|
||||
agentId,
|
||||
turnId: "finalized-turn",
|
||||
interrupt: async () => {},
|
||||
});
|
||||
|
||||
try {
|
||||
await fixture.startForegroundRun();
|
||||
await expect(fixture.manager.cancelAgentRun(fixture.agentId)).resolves.toEqual({
|
||||
status: "settled",
|
||||
});
|
||||
|
||||
if (binding === "foreground") {
|
||||
await fixture.startForegroundRun();
|
||||
} else {
|
||||
const running = waitForAgentLifecycle(fixture.manager, fixture.agentId, "running");
|
||||
fixture.session.pushEvent({
|
||||
type: "turn_started",
|
||||
provider: "codex",
|
||||
turnId: "finalized-turn",
|
||||
});
|
||||
await running;
|
||||
}
|
||||
|
||||
const cancellation = await Promise.race([
|
||||
fixture.manager.cancelAgentRun(fixture.agentId),
|
||||
new Promise<"pending">((resolve) => setTimeout(() => resolve("pending"), 3_000)),
|
||||
]);
|
||||
expect(cancellation).toEqual({ status: "settled" });
|
||||
expect(fixture.manager.getAgent(fixture.agentId)).toMatchObject({
|
||||
lifecycle: "idle",
|
||||
activeForegroundTurnId: null,
|
||||
});
|
||||
|
||||
await expect(fixture.manager.cancelAgentRun(fixture.agentId)).resolves.toEqual({
|
||||
status: "not_running",
|
||||
});
|
||||
await fixture.startForegroundRun();
|
||||
expect(fixture.manager.getAgent(fixture.agentId)).toMatchObject({
|
||||
lifecycle: "running",
|
||||
activeForegroundTurnId: "finalized-turn",
|
||||
});
|
||||
} finally {
|
||||
await fixture.cleanup();
|
||||
}
|
||||
},
|
||||
10_000,
|
||||
);
|
||||
|
||||
test("the provider's terminal for a run bound to an already finalized turn settles the run", async () => {
|
||||
const fixture = await createControlledInterruptFixture({
|
||||
name: "interrupt-finalized-provider-terminal",
|
||||
agentId: "00000000-0000-4000-8000-000000000309",
|
||||
turnId: "finalized-provider-terminal-turn",
|
||||
interrupt: async () => {},
|
||||
});
|
||||
|
||||
try {
|
||||
await fixture.startForegroundRun();
|
||||
await expect(fixture.manager.cancelAgentRun(fixture.agentId)).resolves.toEqual({
|
||||
status: "settled",
|
||||
});
|
||||
|
||||
await fixture.startForegroundRun();
|
||||
const idle = waitForAgentLifecycle(fixture.manager, fixture.agentId, "idle");
|
||||
fixture.session.pushEvent({
|
||||
type: "turn_completed",
|
||||
provider: "codex",
|
||||
turnId: "finalized-provider-terminal-turn",
|
||||
});
|
||||
const settlement = await Promise.race([
|
||||
idle.then(() => "idle" as const),
|
||||
new Promise<"pending">((resolve) => setTimeout(() => resolve("pending"), 1_000)),
|
||||
]);
|
||||
|
||||
expect(settlement).toBe("idle");
|
||||
expect(fixture.manager.getAgent(fixture.agentId)).toMatchObject({
|
||||
lifecycle: "idle",
|
||||
activeForegroundTurnId: null,
|
||||
});
|
||||
await expect(fixture.manager.cancelAgentRun(fixture.agentId)).resolves.toEqual({
|
||||
status: "not_running",
|
||||
});
|
||||
} finally {
|
||||
await fixture.cleanup();
|
||||
}
|
||||
}, 10_000);
|
||||
|
||||
test("listProviderAvailability uses registered client keys, including custom providers", async () => {
|
||||
const customClient: AgentClient = {
|
||||
provider: "zai",
|
||||
@@ -12388,18 +12440,11 @@ test("authoritative timeline records a daemon-handled submitted prompt before it
|
||||
test("tryRunOutOfBand gives providers the command another agent sent, not its envelope", async () => {
|
||||
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-agent-out-of-band-"));
|
||||
const seenPrompts: AgentPromptInput[] = [];
|
||||
const acceptanceOrder: string[] = [];
|
||||
|
||||
class SlashCommandSession extends TestAgentSession {
|
||||
override tryHandleOutOfBand(prompt: AgentPromptInput) {
|
||||
seenPrompts.push(prompt);
|
||||
return prompt === "/handled"
|
||||
? {
|
||||
run: async () => {
|
||||
acceptanceOrder.push("run");
|
||||
},
|
||||
}
|
||||
: null;
|
||||
return prompt === "/handled" ? { run: async () => {} } : null;
|
||||
}
|
||||
}
|
||||
const client = new (class extends TestAgentClient {
|
||||
@@ -12414,22 +12459,12 @@ test("tryRunOutOfBand gives providers the command another agent sent, not its en
|
||||
|
||||
try {
|
||||
const fromAgent = prepareAgentMessage("/handled", { kind: "agent-message", agentId: "sender" });
|
||||
expect(
|
||||
await manager.tryRunOutOfBand(agent.id, fromAgent.prompt, undefined, () => {
|
||||
acceptanceOrder.push("accepted");
|
||||
}),
|
||||
).toBe(true);
|
||||
await vi.waitFor(() => expect(acceptanceOrder).toEqual(["accepted", "run"]));
|
||||
expect(await manager.tryRunOutOfBand(agent.id, fromAgent.prompt)).toBe(true);
|
||||
expect(seenPrompts).toEqual(["/handled"]);
|
||||
|
||||
// A human who pastes an envelope gets it quoted, and it stays a plain prompt.
|
||||
const pasted = prepareAgentMessage(String(fromAgent.prompt));
|
||||
expect(
|
||||
await manager.tryRunOutOfBand(agent.id, pasted.prompt, undefined, () => {
|
||||
acceptanceOrder.push("unexpected");
|
||||
}),
|
||||
).toBe(false);
|
||||
expect(acceptanceOrder).toEqual(["accepted", "run"]);
|
||||
expect(await manager.tryRunOutOfBand(agent.id, pasted.prompt)).toBe(false);
|
||||
expect(seenPrompts.at(-1)).toBe(pasted.prompt);
|
||||
} finally {
|
||||
await manager.closeAgent(agent.id);
|
||||
@@ -14655,309 +14690,3 @@ test("idle cleanup gives a newly restored runtime a fresh idle window while keep
|
||||
expect((await h.sweep({ now: h.later(61) })).collected).toHaveLength(1);
|
||||
expect(h.closes).toBe(closesBeforeRestore + 1);
|
||||
});
|
||||
|
||||
test.each([
|
||||
["supported", "turn_completed"],
|
||||
["supported", "turn_canceled"],
|
||||
["supported", "turn_failed"],
|
||||
["unsupported", "turn_completed"],
|
||||
["unsupported", "turn_canceled"],
|
||||
["unsupported", "turn_failed"],
|
||||
] as const)(
|
||||
"queued delivery after %s provider %s never steers or interrupts",
|
||||
async (support, ending) => {
|
||||
const workdir = mkdtempSync(join(tmpdir(), "agent-queued-terminal-"));
|
||||
const session =
|
||||
support === "supported"
|
||||
? new SteeringTestSession({ provider: "codex", cwd: workdir })
|
||||
: new UnsupportedSteeringSession({ provider: "codex", cwd: workdir });
|
||||
const client = new (class extends TestAgentClient {
|
||||
override async createSession(): Promise<AgentSession> {
|
||||
return session;
|
||||
}
|
||||
})();
|
||||
const manager = new AgentManager({ clients: { codex: client }, logger });
|
||||
const agent = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, {
|
||||
workspaceId: undefined,
|
||||
});
|
||||
let tick = () => {};
|
||||
const delivery = createAgentMessageDelivery({
|
||||
isRunning: (id) => manager.hasInFlightRun(id),
|
||||
subscribe: (notify) =>
|
||||
manager.subscribe(
|
||||
(event) => {
|
||||
if (event.type === "agent_state") notify(event.agent.id);
|
||||
},
|
||||
{ replayState: false },
|
||||
),
|
||||
schedule: (_delay, callback) => {
|
||||
tick = callback;
|
||||
return () => {};
|
||||
},
|
||||
dispatch: async (request) =>
|
||||
(
|
||||
await startAgentRun(manager, agent.id, request.prompt, logger, {
|
||||
idleOnly: request.idleOnly,
|
||||
replaceRunning: true,
|
||||
activeTurnBehavior: request.activeTurnBehavior,
|
||||
})
|
||||
).disposition,
|
||||
onError: (error) => {
|
||||
throw error;
|
||||
},
|
||||
});
|
||||
const providerStarted = new Promise<void>((resolve) => {
|
||||
const unsubscribe = session.subscribe((event) => {
|
||||
if (event.type === "turn_started") {
|
||||
unsubscribe();
|
||||
resolve();
|
||||
}
|
||||
});
|
||||
});
|
||||
try {
|
||||
await startAgentRun(manager, agent.id, "original", logger);
|
||||
await manager.waitForAgentRunStart(agent.id);
|
||||
const receipt = delivery.enqueue({
|
||||
recipientId: agent.id,
|
||||
prompt: "queued",
|
||||
source: { kind: "agent-message", agentId: "child" },
|
||||
});
|
||||
tick();
|
||||
expect(session.startCount).toBe(1);
|
||||
expect(session.interruptCount).toBe(0);
|
||||
const turnId = support === "supported" ? "active-turn-1" : "unsupported-turn-1";
|
||||
await providerStarted;
|
||||
session.pushEvent({
|
||||
type: ending,
|
||||
provider: "codex",
|
||||
turnId,
|
||||
...(ending === "turn_failed" ? { error: "test failure" } : {}),
|
||||
} as AgentStreamEvent);
|
||||
await receipt.dispatched;
|
||||
await manager.waitForAgentRunStart(agent.id);
|
||||
expect(session.startCount).toBe(2);
|
||||
expect(session.interruptCount).toBe(0);
|
||||
} finally {
|
||||
await delivery.close();
|
||||
await manager.closeAgent(agent.id);
|
||||
rmSync(workdir, { recursive: true, force: true });
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
test.each(["turn_completed", "turn_failed", "turn_canceled"] as const)(
|
||||
"an autonomous %s publishes readiness after settling its run",
|
||||
async (ending) => {
|
||||
const workdir = mkdtempSync(join(tmpdir(), "agent-autonomous-delivery-"));
|
||||
const session = new SteeringTestSession({ provider: "codex", cwd: workdir });
|
||||
const client = new (class extends TestAgentClient {
|
||||
override async createSession(): Promise<AgentSession> {
|
||||
return session;
|
||||
}
|
||||
})();
|
||||
const manager = new AgentManager({ clients: { codex: client }, logger });
|
||||
const agent = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, {
|
||||
workspaceId: undefined,
|
||||
});
|
||||
let tick = () => {};
|
||||
const settledStates: boolean[] = [];
|
||||
const delivery = createAgentMessageDelivery({
|
||||
isRunning: (id) => manager.hasInFlightRun(id),
|
||||
subscribe: (notify) =>
|
||||
manager.subscribe(
|
||||
(event) => {
|
||||
if (event.type !== "agent_state") return;
|
||||
if (event.agent.lifecycle !== "running")
|
||||
settledStates.push(manager.hasInFlightRun(agent.id));
|
||||
notify(event.agent.id);
|
||||
},
|
||||
{ agentId: agent.id, replayState: false },
|
||||
),
|
||||
schedule: (_delay, callback) => {
|
||||
tick = callback;
|
||||
return () => {};
|
||||
},
|
||||
dispatch: async (request) =>
|
||||
(
|
||||
await startAgentRun(manager, agent.id, request.prompt, logger, {
|
||||
idleOnly: request.idleOnly,
|
||||
})
|
||||
).disposition,
|
||||
onError: (error) => {
|
||||
throw error;
|
||||
},
|
||||
});
|
||||
try {
|
||||
session.pushEvent({ type: "turn_started", provider: "codex", turnId: "autonomous" });
|
||||
await vi.waitFor(() => expect(manager.hasInFlightRun(agent.id)).toBe(true));
|
||||
delivery.enqueue({
|
||||
recipientId: agent.id,
|
||||
prompt: "queued report",
|
||||
source: { kind: "agent-message", agentId: "child" },
|
||||
});
|
||||
tick();
|
||||
expect(session.startCount).toBe(0);
|
||||
session.pushEvent({
|
||||
type: ending,
|
||||
provider: "codex",
|
||||
turnId: "autonomous",
|
||||
...(ending === "turn_failed" ? { error: "test failure" } : {}),
|
||||
} as AgentStreamEvent);
|
||||
await new Promise<void>((resolve) => setImmediate(resolve));
|
||||
expect(settledStates).toEqual([false]);
|
||||
expect(session.startCount).toBe(1);
|
||||
} finally {
|
||||
await delivery.close();
|
||||
await manager.closeAgent(agent.id);
|
||||
rmSync(workdir, { recursive: true, force: true });
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
test("an idle-only prompt rejects a busy recipient before changing its mode", async () => {
|
||||
const workdir = mkdtempSync(join(tmpdir(), "agent-queued-mode-"));
|
||||
class ModeSession extends SteeringTestSession {
|
||||
mode = "plan";
|
||||
applied: string[] = [];
|
||||
startedModes: string[] = [];
|
||||
override async setMode(mode?: string) {
|
||||
if (!mode) throw new Error("Mode required");
|
||||
this.mode = mode;
|
||||
this.applied.push(mode);
|
||||
}
|
||||
override async getCurrentMode() {
|
||||
return this.mode;
|
||||
}
|
||||
override async startTurn(prompt: AgentPromptInput) {
|
||||
this.startedModes.push(this.mode);
|
||||
return super.startTurn(prompt);
|
||||
}
|
||||
}
|
||||
const session = new ModeSession({ provider: "codex", cwd: workdir });
|
||||
const client = new (class extends TestAgentClient {
|
||||
override async createSession(): Promise<AgentSession> {
|
||||
return session;
|
||||
}
|
||||
})();
|
||||
const storage = new AgentStorage(join(workdir, "agents"), logger);
|
||||
const manager = new AgentManager({ clients: { codex: client }, registry: storage, logger });
|
||||
const agent = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, {
|
||||
workspaceId: undefined,
|
||||
});
|
||||
await manager.setAgentMode(agent.id, "plan");
|
||||
session.applied.length = 0;
|
||||
const providerStarted = new Promise<void>((resolve) => {
|
||||
const unsubscribe = session.subscribe((event) => {
|
||||
if (event.type === "turn_started") {
|
||||
unsubscribe();
|
||||
resolve();
|
||||
}
|
||||
});
|
||||
});
|
||||
const startOther = async () => {
|
||||
await startAgentRun(manager, agent.id, "other turn", logger);
|
||||
await manager.waitForAgentRunStart(agent.id);
|
||||
};
|
||||
try {
|
||||
await startOther();
|
||||
await expect(
|
||||
sendPreparedPromptToAgent({
|
||||
agentManager: manager,
|
||||
agentStorage: storage,
|
||||
agentId: agent.id,
|
||||
prompt: "queued follow-up",
|
||||
sessionMode: "full-access",
|
||||
idleOnly: true,
|
||||
logger,
|
||||
}),
|
||||
).rejects.toBeInstanceOf(AgentTurnBusyError);
|
||||
expect(session.mode).toBe("plan");
|
||||
expect(session.applied).toEqual([]);
|
||||
expect(session.startedModes).toEqual(["plan"]);
|
||||
await providerStarted;
|
||||
session.pushEvent({ type: "turn_completed", provider: "codex", turnId: "active-turn-1" });
|
||||
await vi.waitFor(() => expect(manager.hasInFlightRun(agent.id)).toBe(false));
|
||||
await sendPreparedPromptToAgent({
|
||||
agentManager: manager,
|
||||
agentStorage: storage,
|
||||
agentId: agent.id,
|
||||
prompt: "queued follow-up",
|
||||
sessionMode: "full-access",
|
||||
idleOnly: true,
|
||||
logger,
|
||||
});
|
||||
await manager.waitForAgentRunStart(agent.id);
|
||||
expect(session.mode).toBe("full-access");
|
||||
expect(session.applied).toEqual(["full-access"]);
|
||||
expect(session.startedModes).toEqual(["plan", "full-access"]);
|
||||
} finally {
|
||||
await manager.closeAgent(agent.id);
|
||||
rmSync(workdir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("plugin instructions are recomputed for each launch without changing saved config", async () => {
|
||||
const workdir = mkdtempSync(join(tmpdir(), "agent-plugin-prompt-"));
|
||||
const storage = new AgentStorage(join(workdir, "agents"), logger);
|
||||
const client = new TestAgentClient();
|
||||
let additions = ["Plugin one", "Plugin two"];
|
||||
const manager = new AgentManager({
|
||||
clients: { codex: client },
|
||||
registry: storage,
|
||||
logger,
|
||||
appendSystemPrompt: "Daemon",
|
||||
pluginLifecycle: {
|
||||
emit: () => {},
|
||||
before: async (name, request) =>
|
||||
name === "agent.open.before" ? { ...request, appendSystemPrompt: additions } : request,
|
||||
},
|
||||
});
|
||||
const snapshot = await manager.createAgent(
|
||||
{ provider: "codex", cwd: workdir, systemPrompt: "Saved" },
|
||||
undefined,
|
||||
{ workspaceId: undefined },
|
||||
);
|
||||
expect(client.createdConfigs[0]).toMatchObject({
|
||||
systemPrompt: "Saved",
|
||||
daemonAppendSystemPrompt: "Daemon",
|
||||
pluginAppendSystemPrompt: ["Plugin one", "Plugin two"],
|
||||
});
|
||||
expect(snapshot.config.systemPrompt).toBe("Saved");
|
||||
expect((await storage.get(snapshot.id))?.config?.systemPrompt).toBe("Saved");
|
||||
const handle: AgentPersistenceHandle = {
|
||||
provider: "codex",
|
||||
sessionId: "prompt-session",
|
||||
metadata: { provider: "codex", cwd: workdir, systemPrompt: "Saved" },
|
||||
};
|
||||
await manager.closeAgent(snapshot.id);
|
||||
await manager.resumeAgentFromPersistence(
|
||||
handle,
|
||||
{ cwd: workdir, systemPrompt: "Saved" },
|
||||
snapshot.id,
|
||||
);
|
||||
expect(client.resumeOverrides.at(-1)?.pluginAppendSystemPrompt).toEqual([
|
||||
"Plugin one",
|
||||
"Plugin two",
|
||||
]);
|
||||
additions = ["Changed"];
|
||||
await manager.closeAgent(snapshot.id);
|
||||
await manager.resumeAgentFromPersistence(
|
||||
handle,
|
||||
{ cwd: workdir, systemPrompt: "Saved" },
|
||||
snapshot.id,
|
||||
);
|
||||
expect(client.resumeOverrides.at(-1)?.pluginAppendSystemPrompt).toEqual(["Changed"]);
|
||||
additions = ["Refreshed"];
|
||||
await manager.reloadAgentSession(snapshot.id);
|
||||
expect(client.resumeOverrides.at(-1)?.pluginAppendSystemPrompt).toEqual(["Refreshed"]);
|
||||
additions = [];
|
||||
await manager.closeAgent(snapshot.id);
|
||||
await manager.resumeAgentFromPersistence(
|
||||
handle,
|
||||
{ cwd: workdir, systemPrompt: "Saved" },
|
||||
snapshot.id,
|
||||
);
|
||||
expect(client.resumeOverrides.at(-1)?.systemPrompt).toBe("Saved");
|
||||
expect(client.resumeOverrides.at(-1)?.daemonAppendSystemPrompt).toBe("Daemon");
|
||||
expect((await storage.get(snapshot.id))?.config?.systemPrompt).toBe("Saved");
|
||||
});
|
||||
|
||||
@@ -634,12 +634,7 @@ function normalizePersistenceForConfig(
|
||||
if (!handle) {
|
||||
return null;
|
||||
}
|
||||
const {
|
||||
mcpServers: _launchMcpServers,
|
||||
pluginAppendSystemPrompt: _pluginAppendSystemPrompt,
|
||||
daemonAppendSystemPrompt: _daemonAppendSystemPrompt,
|
||||
...metadata
|
||||
} = handle.metadata ?? {};
|
||||
const { mcpServers: _launchMcpServers, ...metadata } = handle.metadata ?? {};
|
||||
return {
|
||||
...handle,
|
||||
metadata: {
|
||||
@@ -1122,10 +1117,6 @@ export class AgentManager {
|
||||
return new Date(nextMs).toISOString();
|
||||
}
|
||||
|
||||
hasPendingPermissions(agentId: string): boolean {
|
||||
return (this.agents.get(agentId)?.pendingPermissions.size ?? 0) > 0;
|
||||
}
|
||||
|
||||
hasInFlightRun(agentId: string): boolean {
|
||||
const agent = this.agents.get(agentId);
|
||||
if (!agent) {
|
||||
@@ -1736,10 +1727,7 @@ export class AgentManager {
|
||||
...(record ? { metadata: record.metadata, attention: extractAttention(record) } : {}),
|
||||
workspaceId,
|
||||
launchEnv,
|
||||
persistence:
|
||||
purpose === "interactive" && session.persistenceUpdatedOnResume
|
||||
? (session.describePersistence() ?? handle)
|
||||
: handle,
|
||||
persistence: handle,
|
||||
restoring: true,
|
||||
});
|
||||
}
|
||||
@@ -3042,7 +3030,6 @@ export class AgentManager {
|
||||
agentId: string,
|
||||
prompt: AgentPromptInput,
|
||||
options?: AgentRunOptions,
|
||||
onAccepted?: () => void,
|
||||
): Promise<boolean> {
|
||||
if (this.collectingRuntimes.has(agentId) || !this.agents.has(agentId)) {
|
||||
await this.waitForAgentClose(agentId);
|
||||
@@ -3062,7 +3049,6 @@ export class AgentManager {
|
||||
if (!handler) {
|
||||
return false;
|
||||
}
|
||||
onAccepted?.();
|
||||
this.touchUpdatedAt(agent);
|
||||
if (options?.clientMessageId) {
|
||||
this.recordSubmittedPrompt(agent, prompt, options.clientMessageId, "accepted");
|
||||
@@ -5083,7 +5069,8 @@ export class AgentManager {
|
||||
if (
|
||||
eventTurnId &&
|
||||
isTurnTerminalEvent(event) &&
|
||||
this.runs.hasFinalizedTurn(agent, eventTurnId)
|
||||
this.runs.hasFinalizedTurn(agent, eventTurnId) &&
|
||||
this.runs.getTurnId(agent.id) !== eventTurnId
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
@@ -5127,9 +5114,6 @@ export class AgentManager {
|
||||
this.runs.settleTerminalRun(agent.id, eventTurnId);
|
||||
if (isForegroundEvent) {
|
||||
this.finalizeForegroundTurn(agent, eventTurnId);
|
||||
} else if (terminalDisposition !== "stale" && !agent.activeForegroundTurnId) {
|
||||
// Publish autonomous readiness only after the tracked run has settled.
|
||||
this.emitState(agent);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5399,6 +5383,7 @@ export class AgentManager {
|
||||
!agent.pendingReplacement
|
||||
) {
|
||||
(agent as ActiveManagedAgent).lifecycle = "idle";
|
||||
this.emitState(agent);
|
||||
}
|
||||
void this.refreshRuntimeInfo(agent);
|
||||
}
|
||||
@@ -5439,6 +5424,9 @@ export class AgentManager {
|
||||
options,
|
||||
);
|
||||
this.resolvePendingPermissionsForAgent(agent, event.provider, options, "Turn failed");
|
||||
if (!isForegroundEvent && !agent.activeForegroundTurnId) {
|
||||
this.emitState(agent);
|
||||
}
|
||||
}
|
||||
|
||||
private onStreamTurnCanceled(params: {
|
||||
@@ -5472,6 +5460,9 @@ export class AgentManager {
|
||||
}
|
||||
agent.lastError = undefined;
|
||||
this.resolvePendingPermissionsForAgent(agent, event.provider, options, "Interrupted");
|
||||
if (!isForegroundEvent && !agent.activeForegroundTurnId) {
|
||||
this.emitState(agent);
|
||||
}
|
||||
}
|
||||
|
||||
private onStreamTurnStarted(params: {
|
||||
@@ -6181,7 +6172,6 @@ export class AgentManager {
|
||||
// A plugin changing during this open must still make the resulting session stale.
|
||||
const generation = this.sessionOpenGeneration;
|
||||
this.detachPluginTools(agentId);
|
||||
let appendSystemPrompt: string[] | undefined;
|
||||
let mcpServers: AgentSessionConfig["mcpServers"];
|
||||
let mcpServerOwners: Record<string, string> | undefined;
|
||||
if (this.pluginLifecycle) {
|
||||
@@ -6203,14 +6193,12 @@ export class AgentManager {
|
||||
env = transformed.env;
|
||||
if (request.purpose === "interactive") {
|
||||
this.attachedPluginTools.set(agentId, transformed.tools as AttachedAgentTool[]);
|
||||
appendSystemPrompt = transformed.appendSystemPrompt;
|
||||
mcpServers = transformed.mcpServers;
|
||||
mcpServerOwners = transformed.mcpServerOwners;
|
||||
}
|
||||
}
|
||||
const context: AgentLaunchContext = {
|
||||
agentId,
|
||||
...pluginPromptContext(appendSystemPrompt),
|
||||
mcpServers,
|
||||
mcpServerOwners,
|
||||
env: {
|
||||
@@ -6257,7 +6245,6 @@ export class AgentManager {
|
||||
throw new Error(`MCP server '${name}' from plugin ${owner} collides with ${existingOwner}`);
|
||||
}
|
||||
}
|
||||
launchConfig = { ...launchConfig, pluginAppendSystemPrompt: launchContext.appendSystemPrompt };
|
||||
const merged =
|
||||
Object.keys(launchContext.mcpServers ?? {}).length > 0
|
||||
? {
|
||||
@@ -6395,9 +6382,3 @@ export function commandMayHaveChangedExternalState(command: string): boolean {
|
||||
/\bgit\s+fetch\b/.test(normalized)
|
||||
);
|
||||
}
|
||||
|
||||
function pluginPromptContext(
|
||||
appendSystemPrompt: string[] | undefined,
|
||||
): Pick<AgentLaunchContext, "appendSystemPrompt"> {
|
||||
return appendSystemPrompt?.length ? { appendSystemPrompt } : {};
|
||||
}
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { AgentTurnBusyError } from "../agent-prompt.js";
|
||||
import { expect, test } from "vitest";
|
||||
import { createAgentMessageDelivery, parseAgentMessages } from "./index.js";
|
||||
import type { AgentPromptInput } from "../agent-sdk-types.js";
|
||||
@@ -118,6 +117,7 @@ test("explicit interrupt and conflicting session modes retain ordered dispatch b
|
||||
const delivery = createAgentMessageDelivery({
|
||||
dispatch: async (request) => {
|
||||
sent.push(request);
|
||||
request.onDispatch("steered");
|
||||
return "steered";
|
||||
},
|
||||
onError: (error) => {
|
||||
@@ -313,555 +313,3 @@ test("runtime safety sees queued messages until provider dispatch settles", asyn
|
||||
await delivery.close();
|
||||
expect(delivery.hasPending("parent")).toBe(false);
|
||||
});
|
||||
|
||||
test("messages wait across quiet windows and batch after the recipient turn ends", async () => {
|
||||
const clock = createClock();
|
||||
let running = true;
|
||||
const sent: Array<readonly string[]> = [];
|
||||
const delivery = createAgentMessageDelivery({
|
||||
schedule: clock.schedule,
|
||||
isRunning: () => running,
|
||||
dispatch: async (request) => {
|
||||
sent.push(request.messageIds);
|
||||
return "turn_started";
|
||||
},
|
||||
onError: (error) => {
|
||||
throw error;
|
||||
},
|
||||
});
|
||||
const source = { kind: "agent-message" as const, agentId: "child" };
|
||||
const report = delivery.enqueue({
|
||||
recipientId: "parent",
|
||||
messageId: "report",
|
||||
source,
|
||||
prompt: "report",
|
||||
});
|
||||
clock.advance(2000);
|
||||
await Promise.resolve();
|
||||
expect(sent).toEqual([]);
|
||||
clock.advance(13000);
|
||||
const finish = delivery.enqueue({
|
||||
recipientId: "parent",
|
||||
messageId: "finish",
|
||||
source: { kind: "agent-notification", agentId: "child", event: "finished" },
|
||||
prompt: "finished",
|
||||
activeTurnBehavior: "steer",
|
||||
});
|
||||
clock.advance(2000);
|
||||
await Promise.resolve();
|
||||
expect(sent).toEqual([]);
|
||||
running = false;
|
||||
clock.advance(2000);
|
||||
await Promise.all([report.dispatched, finish.dispatched]);
|
||||
expect(sent).toEqual([["report", "finish"]]);
|
||||
await delivery.close();
|
||||
});
|
||||
|
||||
test("a turn starting during dispatch preparation keeps receipts queued and joins later arrivals", async () => {
|
||||
const clock = createClock();
|
||||
let busy = true;
|
||||
const sent: Array<readonly string[]> = [];
|
||||
const delivery = createAgentMessageDelivery({
|
||||
schedule: clock.schedule,
|
||||
dispatch: async (request) => {
|
||||
if (busy) throw new AgentTurnBusyError("concurrent turn");
|
||||
sent.push(request.messageIds);
|
||||
return "turn_started";
|
||||
},
|
||||
onError: (error) => {
|
||||
throw error;
|
||||
},
|
||||
});
|
||||
const message = {
|
||||
recipientId: "parent",
|
||||
source: { kind: "agent-message" as const, agentId: "child" },
|
||||
prompt: "report",
|
||||
};
|
||||
const first = delivery.enqueue({ ...message, messageId: "first" });
|
||||
clock.advance(2000);
|
||||
await new Promise<void>((resolve) => setImmediate(resolve));
|
||||
expect(delivery.hasPending("parent")).toBe(true);
|
||||
const second = delivery.enqueue({ ...message, messageId: "second" });
|
||||
busy = false;
|
||||
clock.advance(2000);
|
||||
await Promise.all([first.dispatched, second.dispatched]);
|
||||
expect(sent).toEqual([["first", "second"]]);
|
||||
await delivery.close();
|
||||
});
|
||||
|
||||
test("explicit interrupt bypasses a running turn while ordinary messages keep waiting", async () => {
|
||||
const clock = createClock();
|
||||
const sent: Array<readonly string[]> = [];
|
||||
const delivery = createAgentMessageDelivery({
|
||||
schedule: clock.schedule,
|
||||
isRunning: () => true,
|
||||
dispatch: async (request) => {
|
||||
sent.push(request.messageIds);
|
||||
return "turn_started";
|
||||
},
|
||||
onError: (error) => {
|
||||
throw error;
|
||||
},
|
||||
});
|
||||
const message = {
|
||||
recipientId: "parent",
|
||||
source: { kind: "agent-message" as const, agentId: "child" },
|
||||
prompt: "report",
|
||||
};
|
||||
delivery.enqueue({ ...message, messageId: "wait" });
|
||||
const interrupt = delivery.enqueue({
|
||||
...message,
|
||||
messageId: "interrupt",
|
||||
activeTurnBehavior: "interrupt",
|
||||
});
|
||||
clock.advance(2000);
|
||||
await interrupt.dispatched;
|
||||
expect(sent).toEqual([["interrupt"]]);
|
||||
expect(delivery.hasPending("parent")).toBe(true);
|
||||
await delivery.close();
|
||||
expect(sent).toEqual([["interrupt"], ["wait"]]);
|
||||
});
|
||||
|
||||
test("shutdown flushes a dispatch that discovered a concurrent turn during preparation", async () => {
|
||||
const clock = createClock();
|
||||
let release!: () => void;
|
||||
const preparing = new Promise<void>((resolve) => {
|
||||
release = resolve;
|
||||
});
|
||||
const modes: boolean[] = [];
|
||||
const delivery = createAgentMessageDelivery({
|
||||
schedule: clock.schedule,
|
||||
dispatch: async (request) => {
|
||||
modes.push(request.idleOnly);
|
||||
if (request.idleOnly) {
|
||||
await preparing;
|
||||
throw new AgentTurnBusyError("busy");
|
||||
}
|
||||
return "turn_started";
|
||||
},
|
||||
onError: () => {},
|
||||
});
|
||||
const receipt = delivery.enqueue({
|
||||
recipientId: "parent",
|
||||
prompt: "report",
|
||||
source: { kind: "agent-message", agentId: "child" },
|
||||
});
|
||||
clock.advance(2000);
|
||||
await new Promise<void>((resolve) => setImmediate(resolve));
|
||||
const closing = delivery.close();
|
||||
release();
|
||||
await closing;
|
||||
await expect(receipt.dispatched).resolves.toBe("turn_started");
|
||||
expect(modes).toEqual([true, false]);
|
||||
});
|
||||
|
||||
test("conflicting modes dispatch on separate turn ends without changing the active turn mode", async () => {
|
||||
const clock = createClock();
|
||||
let busy = false;
|
||||
let mode = "initial";
|
||||
let wake!: (recipientId: string) => void;
|
||||
const sent: Array<{ ids: readonly string[]; mode?: string }> = [];
|
||||
const delivery = createAgentMessageDelivery({
|
||||
schedule: clock.schedule,
|
||||
isRunning: () => busy,
|
||||
subscribe: (listener) => {
|
||||
wake = listener;
|
||||
return () => {};
|
||||
},
|
||||
dispatch: async (request) => {
|
||||
// Mode preparation precedes run admission in the real dispatcher.
|
||||
mode = request.sessionMode ?? mode;
|
||||
if (busy) throw new AgentTurnBusyError("concurrent turn");
|
||||
sent.push({ ids: request.messageIds, mode });
|
||||
busy = true;
|
||||
return "turn_started";
|
||||
},
|
||||
onError: (error) => {
|
||||
throw error;
|
||||
},
|
||||
});
|
||||
const message = {
|
||||
recipientId: "parent",
|
||||
source: { kind: "agent-message" as const, agentId: "child" },
|
||||
prompt: "message",
|
||||
};
|
||||
const a = delivery.enqueue({ ...message, messageId: "A", sessionMode: "plan" });
|
||||
const b = delivery.enqueue({ ...message, messageId: "B", sessionMode: "default" });
|
||||
clock.advance(2000);
|
||||
await a.dispatched;
|
||||
await new Promise<void>((resolve) => setImmediate(resolve));
|
||||
expect(mode).toBe("plan");
|
||||
expect(sent).toEqual([{ ids: ["A"], mode: "plan" }]);
|
||||
busy = false;
|
||||
wake("parent");
|
||||
await b.dispatched;
|
||||
expect(mode).toBe("default");
|
||||
expect(sent).toEqual([
|
||||
{ ids: ["A"], mode: "plan" },
|
||||
{ ids: ["B"], mode: "default" },
|
||||
]);
|
||||
await delivery.close();
|
||||
});
|
||||
|
||||
test("interrupts retain separate mode choices while the recipient is busy", async () => {
|
||||
const clock = createClock();
|
||||
const sent: Array<{ ids: readonly string[]; mode?: string }> = [];
|
||||
const delivery = createAgentMessageDelivery({
|
||||
schedule: clock.schedule,
|
||||
isRunning: () => true,
|
||||
dispatch: async (request) => {
|
||||
sent.push({ ids: request.messageIds, mode: request.sessionMode });
|
||||
return "turn_started";
|
||||
},
|
||||
onError: (error) => {
|
||||
throw error;
|
||||
},
|
||||
});
|
||||
const message = {
|
||||
recipientId: "parent",
|
||||
source: { kind: "agent-message" as const, agentId: "child" },
|
||||
prompt: "message",
|
||||
activeTurnBehavior: "interrupt" as const,
|
||||
};
|
||||
const a = delivery.enqueue({ ...message, messageId: "A", sessionMode: "plan" });
|
||||
const b = delivery.enqueue({ ...message, messageId: "B", sessionMode: "default" });
|
||||
clock.advance(2000);
|
||||
await Promise.all([a.dispatched, b.dispatched]);
|
||||
expect(sent).toEqual([
|
||||
{ ids: ["A"], mode: "plan" },
|
||||
{ ids: ["B"], mode: "default" },
|
||||
]);
|
||||
await delivery.close();
|
||||
});
|
||||
|
||||
test("a settled-turn event releases a ready batch without waiting for the next timer sample", async () => {
|
||||
const clock = createClock();
|
||||
let running = true;
|
||||
let settled: (id: string) => void = () => {};
|
||||
let subscribed = true;
|
||||
const sent: string[] = [];
|
||||
const delivery = createAgentMessageDelivery({
|
||||
schedule: clock.schedule,
|
||||
isRunning: () => running,
|
||||
subscribe: (listener) => {
|
||||
settled = listener;
|
||||
return () => {
|
||||
subscribed = false;
|
||||
};
|
||||
},
|
||||
dispatch: async (request) => {
|
||||
sent.push(request.recipientId);
|
||||
return "turn_started";
|
||||
},
|
||||
onError: (error) => {
|
||||
throw error;
|
||||
},
|
||||
});
|
||||
delivery.enqueue({
|
||||
recipientId: "parent",
|
||||
prompt: "report",
|
||||
source: { kind: "agent-message", agentId: "child" },
|
||||
});
|
||||
clock.advance(2000);
|
||||
expect(sent).toEqual([]);
|
||||
running = false;
|
||||
settled("parent");
|
||||
await new Promise<void>((resolve) => setImmediate(resolve));
|
||||
expect(sent).toEqual(["parent"]);
|
||||
running = true;
|
||||
await delivery.close();
|
||||
expect(subscribed).toBe(false);
|
||||
});
|
||||
|
||||
test.each([false, true])(
|
||||
"completion waits report permission checkpoints without draining messages (initial: %s)",
|
||||
async (initial) => {
|
||||
const clock = createClock();
|
||||
let permission = initial;
|
||||
let changed: (id: string) => void = () => {};
|
||||
let reported = false;
|
||||
let sent = 0;
|
||||
const delivery = createAgentMessageDelivery({
|
||||
schedule: clock.schedule,
|
||||
isRunning: () => true,
|
||||
hasPendingPermission: () => permission,
|
||||
subscribe: (listener) => {
|
||||
changed = listener;
|
||||
return () => {};
|
||||
},
|
||||
dispatch: async () => {
|
||||
sent++;
|
||||
return "turn_started";
|
||||
},
|
||||
onError: (error) => {
|
||||
throw error;
|
||||
},
|
||||
});
|
||||
delivery.enqueue({
|
||||
recipientId: "child",
|
||||
prompt: "follow up",
|
||||
source: { kind: "agent-message", agentId: "parent" },
|
||||
});
|
||||
const wait = delivery.waitForDispatch("child", new AbortController().signal).then(() => {
|
||||
reported = true;
|
||||
return undefined;
|
||||
});
|
||||
permission = true;
|
||||
changed("child");
|
||||
await new Promise<void>((resolve) => setImmediate(resolve));
|
||||
expect(reported).toBe(true);
|
||||
expect(sent).toBe(0);
|
||||
expect(delivery.hasPending("child")).toBe(true);
|
||||
await wait;
|
||||
await delivery.close();
|
||||
},
|
||||
);
|
||||
|
||||
test("a busy admission retry stays ready for the next settled-turn event", async () => {
|
||||
const clock = createClock();
|
||||
let running = false;
|
||||
let raced = true;
|
||||
let notify: (id: string) => void = () => {};
|
||||
const sent: string[] = [];
|
||||
const delivery = createAgentMessageDelivery({
|
||||
schedule: clock.schedule,
|
||||
isRunning: () => running,
|
||||
subscribe: (listener) => {
|
||||
notify = listener;
|
||||
return () => {};
|
||||
},
|
||||
dispatch: async (request) => {
|
||||
if (raced) {
|
||||
running = true;
|
||||
throw new AgentTurnBusyError("next turn started");
|
||||
}
|
||||
sent.push(request.recipientId);
|
||||
return "turn_started";
|
||||
},
|
||||
onError: (error) => {
|
||||
throw error;
|
||||
},
|
||||
});
|
||||
delivery.enqueue({
|
||||
recipientId: "parent",
|
||||
prompt: "report",
|
||||
source: { kind: "agent-message", agentId: "child" },
|
||||
});
|
||||
clock.advance(2000);
|
||||
await new Promise<void>((resolve) => setImmediate(resolve));
|
||||
raced = false;
|
||||
running = false;
|
||||
notify("parent");
|
||||
await new Promise<void>((resolve) => setImmediate(resolve));
|
||||
expect(sent).toEqual(["parent"]);
|
||||
await delivery.close();
|
||||
});
|
||||
|
||||
test("out-of-band acceptance owns callbacks and receipts; a failed attempt does not block waiting messages", async () => {
|
||||
const clock = createClock();
|
||||
let running = true;
|
||||
let wake!: (recipientId: string) => void;
|
||||
const callbacks: string[] = [];
|
||||
const sent: string[] = [];
|
||||
const errors: unknown[] = [];
|
||||
const failure = new Error("recipient could not load");
|
||||
const delivery = createAgentMessageDelivery({
|
||||
schedule: clock.schedule,
|
||||
isRunning: () => running,
|
||||
subscribe: (listener) => {
|
||||
wake = listener;
|
||||
return () => {};
|
||||
},
|
||||
tryRunOutOfBand: async (request, onAccepted) => {
|
||||
const text = parseAgentMessages(String(request.prompt))[0]!.text;
|
||||
if (text === "failure") throw failure;
|
||||
if (text !== "/handled") return false;
|
||||
onAccepted();
|
||||
callbacks.push("command ran");
|
||||
return true;
|
||||
},
|
||||
dispatch: async (request) => {
|
||||
sent.push(...parseAgentMessages(String(request.prompt)).map((message) => message.text));
|
||||
return "turn_started";
|
||||
},
|
||||
onError: (error) => {
|
||||
errors.push(error);
|
||||
},
|
||||
});
|
||||
const message = {
|
||||
recipientId: "parent",
|
||||
source: { kind: "agent-message" as const, agentId: "child" },
|
||||
};
|
||||
const ordinary = delivery.enqueue({
|
||||
...message,
|
||||
prompt: "ordinary",
|
||||
beforeDispatch: () => {
|
||||
callbacks.push("ordinary");
|
||||
},
|
||||
});
|
||||
const failed = delivery.enqueue({
|
||||
...message,
|
||||
prompt: "failure",
|
||||
beforeDispatch: () => {
|
||||
callbacks.push("failure");
|
||||
},
|
||||
});
|
||||
const command = delivery.enqueue({
|
||||
...message,
|
||||
prompt: "/handled",
|
||||
beforeDispatch: () => {
|
||||
callbacks.push("command accepted");
|
||||
},
|
||||
onDispatch: (disposition) => {
|
||||
callbacks.push(disposition);
|
||||
},
|
||||
});
|
||||
clock.advance(2000);
|
||||
await expect(failed.dispatched).rejects.toBe(failure);
|
||||
await expect(command.dispatched).resolves.toBe("out_of_band");
|
||||
expect(errors).toEqual([failure]);
|
||||
expect(callbacks).toEqual(["command accepted", "command ran", "out_of_band"]);
|
||||
expect(sent).toEqual([]);
|
||||
running = false;
|
||||
wake("parent");
|
||||
await ordinary.dispatched;
|
||||
expect(callbacks.at(-1)).toBe("ordinary");
|
||||
expect(sent).toEqual(["ordinary"]);
|
||||
await delivery.close();
|
||||
});
|
||||
|
||||
test("shutdown waits for an in-flight out-of-band attempt and drains its unhandled message", async () => {
|
||||
const clock = createClock();
|
||||
let release!: () => void;
|
||||
let attempted!: () => void;
|
||||
const started = new Promise<void>((resolve) => {
|
||||
attempted = resolve;
|
||||
});
|
||||
const gate = new Promise<void>((resolve) => {
|
||||
release = resolve;
|
||||
});
|
||||
const dispatched: boolean[] = [];
|
||||
const delivery = createAgentMessageDelivery({
|
||||
schedule: clock.schedule,
|
||||
isRunning: () => true,
|
||||
tryRunOutOfBand: async () => {
|
||||
attempted();
|
||||
await gate;
|
||||
return false;
|
||||
},
|
||||
dispatch: async (request) => {
|
||||
dispatched.push(request.idleOnly);
|
||||
return "turn_started";
|
||||
},
|
||||
onError: (error) => {
|
||||
throw error;
|
||||
},
|
||||
});
|
||||
const receipt = delivery.enqueue({
|
||||
recipientId: "parent",
|
||||
prompt: "ordinary",
|
||||
source: { kind: "agent-message", agentId: "child" },
|
||||
});
|
||||
clock.advance(2000);
|
||||
await started;
|
||||
const closing = delivery.close();
|
||||
release();
|
||||
await closing;
|
||||
await expect(receipt.dispatched).resolves.toBe("turn_started");
|
||||
expect(dispatched).toEqual([false]);
|
||||
});
|
||||
|
||||
test("a declined out-of-band message is offered once across running-turn retries", async () => {
|
||||
const clock = createClock();
|
||||
let running = true;
|
||||
let accepts = false;
|
||||
let offers = 0;
|
||||
let dispatched = 0;
|
||||
let wake!: (recipientId: string) => void;
|
||||
const delivery = createAgentMessageDelivery({
|
||||
schedule: clock.schedule,
|
||||
isRunning: () => running,
|
||||
subscribe: (listener) => {
|
||||
wake = listener;
|
||||
return () => {};
|
||||
},
|
||||
tryRunOutOfBand: async (_request, onAccepted) => {
|
||||
offers++;
|
||||
if (accepts) onAccepted();
|
||||
return accepts;
|
||||
},
|
||||
dispatch: async () => {
|
||||
dispatched++;
|
||||
return "turn_started";
|
||||
},
|
||||
onError: (error) => {
|
||||
throw error;
|
||||
},
|
||||
});
|
||||
const receipt = delivery.enqueue({
|
||||
recipientId: "parent",
|
||||
prompt: "message",
|
||||
source: { kind: "agent-message", agentId: "child" },
|
||||
});
|
||||
clock.advance(2000);
|
||||
await new Promise<void>((resolve) => setImmediate(resolve));
|
||||
expect(offers).toBe(1);
|
||||
// A later provider state change does not reinterpret a declined message.
|
||||
accepts = true;
|
||||
for (let retry = 0; retry < 3; retry++) {
|
||||
clock.advance(2000);
|
||||
await new Promise<void>((resolve) => setImmediate(resolve));
|
||||
}
|
||||
expect(offers).toBe(1);
|
||||
expect(dispatched).toBe(0);
|
||||
running = false;
|
||||
wake("parent");
|
||||
await receipt.dispatched;
|
||||
expect(dispatched).toBe(1);
|
||||
await delivery.close();
|
||||
});
|
||||
|
||||
test("a command with an explicit mode waits for turn end without an out-of-band offer", async () => {
|
||||
const clock = createClock();
|
||||
let running = true;
|
||||
let offers = 0;
|
||||
let wake!: (recipientId: string) => void;
|
||||
const dispatched: Array<{ prompt: AgentPromptInput; sessionMode?: string }> = [];
|
||||
const delivery = createAgentMessageDelivery({
|
||||
schedule: clock.schedule,
|
||||
isRunning: () => running,
|
||||
subscribe: (listener) => {
|
||||
wake = listener;
|
||||
return () => {};
|
||||
},
|
||||
tryRunOutOfBand: async (_request, onAccepted) => {
|
||||
offers++;
|
||||
onAccepted();
|
||||
return true;
|
||||
},
|
||||
dispatch: async (request) => {
|
||||
dispatched.push(request);
|
||||
return "out_of_band";
|
||||
},
|
||||
onError: (error) => {
|
||||
throw error;
|
||||
},
|
||||
});
|
||||
const receipt = delivery.enqueue({
|
||||
recipientId: "parent",
|
||||
prompt: "/handled",
|
||||
sessionMode: "plan",
|
||||
source: { kind: "agent-message", agentId: "child" },
|
||||
});
|
||||
clock.advance(2000);
|
||||
await new Promise<void>((resolve) => setImmediate(resolve));
|
||||
expect(offers).toBe(0);
|
||||
expect(dispatched).toEqual([]);
|
||||
running = false;
|
||||
wake("parent");
|
||||
await receipt.dispatched;
|
||||
expect(dispatched).toHaveLength(1);
|
||||
expect(dispatched[0]!.sessionMode).toBe("plan");
|
||||
expect(parseAgentMessages(String(dispatched[0]!.prompt))![0]!.text).toBe("/handled");
|
||||
await delivery.close();
|
||||
});
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { AgentTurnBusyError, type PromptDispatchDisposition } from "../agent-prompt.js";
|
||||
import type { PromptDispatchDisposition } from "../agent-prompt.js";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import type { AgentPromptInput, AgentPromptContentBlock } from "../agent-sdk-types.js";
|
||||
import { prepareAgentMessage, type AgentPromptSource } from "./envelope.js";
|
||||
@@ -21,8 +21,6 @@ interface Receipt {
|
||||
dispatched: Promise<PromptDispatchDisposition>;
|
||||
}
|
||||
interface Admitted extends Message {
|
||||
sequence: number;
|
||||
outOfBandDeclined: boolean;
|
||||
receipt: Receipt;
|
||||
resolve(disposition: PromptDispatchDisposition): void;
|
||||
reject(error: unknown): void;
|
||||
@@ -32,18 +30,12 @@ interface DispatchRequest {
|
||||
messageIds: readonly string[];
|
||||
prompt: AgentPromptInput;
|
||||
activeTurnBehavior: "steer" | "interrupt";
|
||||
idleOnly: boolean;
|
||||
sessionMode?: string;
|
||||
clearPendingPermissions: boolean;
|
||||
unarchive: boolean;
|
||||
onDispatch(disposition: PromptDispatchDisposition): void;
|
||||
}
|
||||
interface Dependencies {
|
||||
/** Includes admitted starts and provider turns, including compaction. */
|
||||
isRunning?: (recipientId: string) => boolean;
|
||||
hasPendingPermission?: (recipientId: string) => boolean;
|
||||
/** Notify when recipient state changes; admission still checks whether it is idle. */
|
||||
subscribe?: (listener: (recipientId: string) => void) => () => void;
|
||||
tryRunOutOfBand?(request: DispatchRequest, onAccepted: () => void): Promise<boolean>;
|
||||
dispatch(request: DispatchRequest): Promise<PromptDispatchDisposition>;
|
||||
onError(error: unknown, request: DispatchRequest): void;
|
||||
/** Return a cancellation function. Production uses the daemon's event loop. */
|
||||
@@ -55,7 +47,7 @@ export interface AgentMessageDelivery {
|
||||
hasPending(recipientId: string): boolean;
|
||||
/** Stop admission, flush pending messages, and await provider dispatch acknowledgments. */
|
||||
close(): Promise<void>;
|
||||
/** Completion waits include admitted messages, but return at permission checkpoints. */
|
||||
/** Existing completion waits include agent messages admitted before the wait. */
|
||||
waitForDispatch(recipientId: string, signal: AbortSignal): Promise<void>;
|
||||
}
|
||||
|
||||
@@ -67,14 +59,12 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
|
||||
const timer = setTimeout(callback, delayMs);
|
||||
return () => clearTimeout(timer);
|
||||
});
|
||||
const pending = new Map<string, { messages: Admitted[]; ready: boolean; cancel(): void }>();
|
||||
const pending = new Map<string, { messages: Admitted[]; cancel(): void }>();
|
||||
const dispatching = new Map<string, Promise<void>>();
|
||||
const receipts = new Map<string, Set<Receipt>>();
|
||||
let sequence = 0;
|
||||
let closed = false;
|
||||
let closing: Promise<void> | undefined;
|
||||
|
||||
function requestFor(recipientId: string, messages: Admitted[]): DispatchRequest {
|
||||
function dispatch(recipientId: string, messages: Admitted[]): void {
|
||||
const prompts = messages.map(
|
||||
(message) =>
|
||||
prepareAgentMessage(message.prompt, message.source, message.receipt.messageId).prompt,
|
||||
@@ -84,55 +74,39 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
|
||||
: prompts.flatMap((entry): AgentPromptContentBlock[] =>
|
||||
typeof entry === "string" ? [{ type: "text", text: entry }] : entry,
|
||||
);
|
||||
return {
|
||||
const request: DispatchRequest = {
|
||||
recipientId,
|
||||
idleOnly: !closed && messages[0]!.activeTurnBehavior !== "interrupt",
|
||||
messageIds: messages.map((message) => message.receipt.messageId),
|
||||
prompt,
|
||||
activeTurnBehavior: messages[0]!.activeTurnBehavior ?? "steer",
|
||||
sessionMode: messages.find((message) => message.sessionMode)?.sessionMode,
|
||||
clearPendingPermissions: messages.some((message) => message.clearPendingPermissions),
|
||||
unarchive: messages.some((message) => message.unarchive !== false),
|
||||
};
|
||||
}
|
||||
|
||||
function dispatch(recipientId: string, messages: Admitted[]): void {
|
||||
const request = requestFor(recipientId, messages);
|
||||
queueDispatch(recipientId, async () => {
|
||||
try {
|
||||
for (const message of messages) message.beforeDispatch?.();
|
||||
let disposition: PromptDispatchDisposition;
|
||||
try {
|
||||
disposition = await dependencies.dispatch(request);
|
||||
} catch (error) {
|
||||
if (!(error instanceof AgentTurnBusyError) || !closed) throw error;
|
||||
// Shutdown drains admitted messages before closing the recipients.
|
||||
disposition = await dependencies.dispatch({ ...request, idleOnly: false });
|
||||
}
|
||||
onDispatch: (disposition) => {
|
||||
for (const message of messages) {
|
||||
try {
|
||||
message.onDispatch?.(disposition);
|
||||
} catch (error) {
|
||||
dependencies.onError(error, request);
|
||||
}
|
||||
message.resolve(disposition);
|
||||
}
|
||||
return undefined;
|
||||
} catch (error) {
|
||||
if (error instanceof AgentTurnBusyError && !closed) {
|
||||
requeue(recipientId, messages);
|
||||
return;
|
||||
}
|
||||
for (const message of messages) message.reject(error);
|
||||
dependencies.onError(error, request);
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function queueDispatch(recipientId: string, operation: () => Promise<void>): void {
|
||||
},
|
||||
};
|
||||
const previous = dispatching.get(recipientId) ?? Promise.resolve();
|
||||
const dispatched = previous.catch(() => undefined).then(operation);
|
||||
const dispatched = previous
|
||||
.catch(() => undefined)
|
||||
.then(async () => {
|
||||
try {
|
||||
for (const message of messages) message.beforeDispatch?.();
|
||||
const disposition = await dependencies.dispatch(request);
|
||||
for (const message of messages) message.resolve(disposition);
|
||||
return undefined;
|
||||
} catch (error) {
|
||||
for (const message of messages) message.reject(error);
|
||||
dependencies.onError(error, request);
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
dispatching.set(recipientId, dispatched);
|
||||
void dispatched
|
||||
.finally(() => {
|
||||
@@ -141,121 +115,30 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
|
||||
.catch(() => undefined);
|
||||
}
|
||||
|
||||
function requeue(recipientId: string, messages: Admitted[]): void {
|
||||
const entry = pending.get(recipientId) ?? {
|
||||
messages: [],
|
||||
ready: true,
|
||||
cancel: () => {},
|
||||
};
|
||||
entry.cancel();
|
||||
entry.messages.push(...messages);
|
||||
entry.messages.sort((a, b) => a.sequence - b.sequence);
|
||||
entry.cancel = schedule(2000, () => flush(recipientId));
|
||||
pending.set(recipientId, entry);
|
||||
}
|
||||
|
||||
function flush(recipientId: string): void {
|
||||
const entry = pending.get(recipientId);
|
||||
if (!entry) return;
|
||||
entry.ready = true;
|
||||
entry.cancel();
|
||||
if (!closed && dependencies.isRunning?.(recipientId)) {
|
||||
const interrupts = entry.messages.filter(
|
||||
(message) => message.activeTurnBehavior === "interrupt",
|
||||
);
|
||||
entry.messages = entry.messages.filter(
|
||||
(message) => message.activeTurnBehavior !== "interrupt",
|
||||
);
|
||||
if (interrupts.length) dispatchGroups(recipientId, interrupts);
|
||||
if (entry.messages.length && dependencies.tryRunOutOfBand) {
|
||||
pending.delete(recipientId);
|
||||
offerOutOfBand(recipientId, entry.messages);
|
||||
} else if (entry.messages.length) {
|
||||
entry.cancel = schedule(2000, () => flush(recipientId));
|
||||
} else {
|
||||
pending.delete(recipientId);
|
||||
}
|
||||
return;
|
||||
}
|
||||
pending.delete(recipientId);
|
||||
dispatchGroups(recipientId, entry.messages);
|
||||
}
|
||||
|
||||
function offerOutOfBand(recipientId: string, messages: Admitted[]): void {
|
||||
queueDispatch(recipientId, async () => {
|
||||
const waiting: Admitted[] = [];
|
||||
for (const message of messages) {
|
||||
if (
|
||||
message.outOfBandDeclined ||
|
||||
message.sessionMode !== undefined ||
|
||||
closed ||
|
||||
!dependencies.isRunning?.(recipientId)
|
||||
) {
|
||||
waiting.push(message);
|
||||
continue;
|
||||
}
|
||||
const request = requestFor(recipientId, [message]);
|
||||
try {
|
||||
const accepted = await dependencies.tryRunOutOfBand!(request, () =>
|
||||
message.beforeDispatch?.(),
|
||||
);
|
||||
if (!accepted) {
|
||||
message.outOfBandDeclined = true;
|
||||
waiting.push(message);
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
message.onDispatch?.("out_of_band");
|
||||
} catch (error) {
|
||||
dependencies.onError(error, request);
|
||||
}
|
||||
message.resolve("out_of_band");
|
||||
} catch (error) {
|
||||
message.reject(error);
|
||||
dependencies.onError(error, request);
|
||||
}
|
||||
}
|
||||
if (waiting.length) requeue(recipientId, waiting);
|
||||
if (closed || (pending.get(recipientId)?.ready && !dependencies.isRunning?.(recipientId)))
|
||||
flush(recipientId);
|
||||
});
|
||||
}
|
||||
|
||||
function dispatchGroups(recipientId: string, messages: Admitted[]): void {
|
||||
const groups: Admitted[][] = [];
|
||||
entry.cancel();
|
||||
let group: Admitted[] = [];
|
||||
let mode: string | undefined;
|
||||
for (const message of messages) {
|
||||
for (const message of entry.messages) {
|
||||
// Explicitly conflicting send options require separate, ordered dispatches.
|
||||
if (
|
||||
group.length &&
|
||||
((message.activeTurnBehavior ?? "steer") !== (group[0]!.activeTurnBehavior ?? "steer") ||
|
||||
(mode && message.sessionMode && mode !== message.sessionMode))
|
||||
) {
|
||||
groups.push(group);
|
||||
dispatch(recipientId, group);
|
||||
group = [];
|
||||
mode = undefined;
|
||||
}
|
||||
group.push(message);
|
||||
mode ??= message.sessionMode;
|
||||
}
|
||||
if (group.length) groups.push(group);
|
||||
let started = false;
|
||||
for (const batch of groups) {
|
||||
if (!closed && started && batch[0]!.activeTurnBehavior !== "interrupt") {
|
||||
requeue(recipientId, batch);
|
||||
} else {
|
||||
dispatch(recipientId, batch);
|
||||
started = true;
|
||||
}
|
||||
}
|
||||
if (group.length) dispatch(recipientId, group);
|
||||
}
|
||||
|
||||
const unsubscribe = dependencies.subscribe?.((recipientId) => {
|
||||
if (pending.get(recipientId)?.ready && !dependencies.isRunning?.(recipientId))
|
||||
flush(recipientId);
|
||||
});
|
||||
|
||||
return {
|
||||
hasPending: (recipientId) => pending.has(recipientId) || dispatching.has(recipientId),
|
||||
enqueue(message) {
|
||||
@@ -272,47 +155,17 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
|
||||
messageId: message.messageId ?? randomUUID(),
|
||||
dispatched,
|
||||
};
|
||||
const owned = receipts.get(message.recipientId) ?? new Set<Receipt>();
|
||||
owned.add(receipt);
|
||||
receipts.set(message.recipientId, owned);
|
||||
void dispatched
|
||||
.finally(() => {
|
||||
owned.delete(receipt);
|
||||
if (!owned.size) receipts.delete(message.recipientId);
|
||||
})
|
||||
.catch(() => undefined);
|
||||
const entry = pending.get(message.recipientId) ?? {
|
||||
messages: [],
|
||||
ready: false,
|
||||
cancel: () => {},
|
||||
};
|
||||
const entry = pending.get(message.recipientId) ?? { messages: [], cancel: () => {} };
|
||||
entry.cancel();
|
||||
entry.ready = false;
|
||||
entry.messages.push({
|
||||
...message,
|
||||
receipt,
|
||||
resolve,
|
||||
reject,
|
||||
sequence: sequence++,
|
||||
outOfBandDeclined: false,
|
||||
});
|
||||
entry.messages.push({ ...message, receipt, resolve, reject });
|
||||
entry.cancel = schedule(2000, () => flush(message.recipientId));
|
||||
pending.set(message.recipientId, entry);
|
||||
return receipt;
|
||||
},
|
||||
async waitForDispatch(recipientId, signal) {
|
||||
signal.throwIfAborted();
|
||||
const admitted = Array.from(receipts.get(recipientId) ?? [], (receipt) => receipt.dispatched);
|
||||
let unsubscribePermission: (() => void) | undefined;
|
||||
const permission = new Promise<void>((resolve) => {
|
||||
const check = () => {
|
||||
if (dependencies.hasPendingPermission?.(recipientId)) resolve();
|
||||
};
|
||||
unsubscribePermission = dependencies.subscribe?.((agentId) => {
|
||||
if (agentId === recipientId) check();
|
||||
});
|
||||
check();
|
||||
});
|
||||
const admitted =
|
||||
pending.get(recipientId)?.messages.map((message) => message.receipt.dispatched) ?? [];
|
||||
let aborted!: () => void;
|
||||
const cancellation = new Promise<never>((_resolve, reject) => {
|
||||
aborted = () => reject(new DOMException("Wait aborted", "AbortError"));
|
||||
@@ -322,22 +175,17 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
|
||||
await Promise.race([
|
||||
Promise.all([dispatching.get(recipientId), ...admitted]),
|
||||
cancellation,
|
||||
permission,
|
||||
]);
|
||||
} finally {
|
||||
signal.removeEventListener("abort", aborted);
|
||||
unsubscribePermission?.();
|
||||
}
|
||||
},
|
||||
close() {
|
||||
if (closing) return closing;
|
||||
closed = true;
|
||||
unsubscribe?.();
|
||||
for (const recipientId of pending.keys()) flush(recipientId);
|
||||
// Each failure is reported and rejects its receipts; shutdown still drains other recipients.
|
||||
closing = Promise.allSettled(
|
||||
[...receipts.values()].flatMap((owned) => [...owned].map((receipt) => receipt.dispatched)),
|
||||
).then(() => undefined);
|
||||
closing = Promise.allSettled(dispatching.values()).then(() => undefined);
|
||||
return closing;
|
||||
},
|
||||
};
|
||||
|
||||
@@ -337,7 +337,6 @@ describe("toAgentPayload", () => {
|
||||
nativeHandle: { id: "native" } as unknown,
|
||||
metadata: {
|
||||
restored: new Date("2025-03-01T00:00:00.000Z"),
|
||||
paseoInstructionReceipt: { threadId: "persist-99", digest: "internal-digest" },
|
||||
empty: {},
|
||||
mcpServers: {
|
||||
hub: {
|
||||
@@ -388,8 +387,6 @@ describe("toAgentPayload", () => {
|
||||
sessionId: "persist-stored",
|
||||
metadata: {
|
||||
conversationId: "conversation-stored",
|
||||
pluginAppendSystemPrompt: ["plugin instruction"],
|
||||
daemonAppendSystemPrompt: "daemon instruction",
|
||||
mcpServers: {
|
||||
hub: {
|
||||
type: "http",
|
||||
@@ -405,8 +402,6 @@ describe("toAgentPayload", () => {
|
||||
|
||||
expect(record.persistence?.metadata).toEqual({
|
||||
conversationId: "conversation-stored",
|
||||
pluginAppendSystemPrompt: ["plugin instruction"],
|
||||
daemonAppendSystemPrompt: "daemon instruction",
|
||||
mcpServers: {
|
||||
hub: {
|
||||
type: "http",
|
||||
|
||||
@@ -495,9 +495,6 @@ function projectPersistenceHandleForWire(
|
||||
return projected;
|
||||
}
|
||||
delete projected.metadata.mcpServers;
|
||||
delete projected.metadata.pluginAppendSystemPrompt;
|
||||
delete projected.metadata.daemonAppendSystemPrompt;
|
||||
delete projected.metadata.paseoInstructionReceipt;
|
||||
if (Object.keys(projected.metadata).length === 0) {
|
||||
delete projected.metadata;
|
||||
}
|
||||
|
||||
@@ -23,10 +23,7 @@ export type AgentRunController = Pick<
|
||||
reloadAgentSession(agentId: string): Promise<unknown>;
|
||||
};
|
||||
|
||||
export class AgentTurnBusyError extends Error {}
|
||||
|
||||
export interface StartAgentRunOptions {
|
||||
idleOnly?: boolean;
|
||||
/** Called after selecting the run, before consuming its events. */
|
||||
onDispatch?: (disposition: PromptDispatchDisposition) => void;
|
||||
replaceRunning?: boolean;
|
||||
@@ -139,12 +136,7 @@ async function startAgentRunInner(
|
||||
options?: StartAgentRunOptions,
|
||||
): Promise<{ disposition: PromptDispatchDisposition }> {
|
||||
const snapshot = agentManager.getAgent(agentId);
|
||||
const steered = options?.idleOnly
|
||||
? null
|
||||
: await steerOrReplaceActiveRun(agentManager, agentId, prompt, options);
|
||||
if (options?.idleOnly && agentManager.hasInFlightRun(agentId)) {
|
||||
throw new AgentTurnBusyError(`Agent ${agentId} is running`);
|
||||
}
|
||||
const steered = await steerOrReplaceActiveRun(agentManager, agentId, prompt, options);
|
||||
if (steered?.disposition === "steered") {
|
||||
options?.onDispatch?.("steered");
|
||||
return steered;
|
||||
@@ -218,7 +210,6 @@ export async function unarchiveAgentState(
|
||||
}
|
||||
|
||||
export interface SendPromptToAgentParams {
|
||||
idleOnly?: boolean;
|
||||
/** Awaited after the agent is loaded and its mode is set, before the prompt is handed to a run. */
|
||||
beforeDispatch?: () => Promise<void>;
|
||||
onDispatch?: StartAgentRunOptions["onDispatch"];
|
||||
@@ -364,17 +355,13 @@ export async function sendPreparedPromptToAgent(
|
||||
throw error;
|
||||
}
|
||||
|
||||
if (params.idleOnly && params.agentManager.hasInFlightRun(params.agentId)) {
|
||||
throw new AgentTurnBusyError(`Agent ${params.agentId} is running`);
|
||||
}
|
||||
if (params.sessionMode) {
|
||||
await params.agentManager.setAgentMode(params.agentId, params.sessionMode);
|
||||
}
|
||||
|
||||
await params.beforeDispatch?.();
|
||||
return await startAgentRun(params.agentManager, params.agentId, params.prompt, params.logger, {
|
||||
replaceRunning: !params.idleOnly,
|
||||
idleOnly: params.idleOnly,
|
||||
replaceRunning: true,
|
||||
onDispatch: params.onDispatch,
|
||||
activeTurnBehavior: params.activeTurnBehavior,
|
||||
clearPendingPermissions: params.clearPendingPermissions,
|
||||
|
||||
@@ -621,8 +621,6 @@ export interface AgentSessionConfig {
|
||||
* persisted into agent config so daemon setting changes apply cleanly.
|
||||
*/
|
||||
daemonAppendSystemPrompt?: string;
|
||||
/** Plugin instructions for this launch; never persisted. */
|
||||
pluginAppendSystemPrompt?: string[];
|
||||
modeId?: string;
|
||||
model?: string;
|
||||
thinkingOptionId?: string;
|
||||
@@ -638,8 +636,6 @@ export interface AgentSessionConfig {
|
||||
}
|
||||
|
||||
export interface AgentLaunchContext {
|
||||
/** Launch-only instructions contributed by plugins. */
|
||||
appendSystemPrompt?: string[];
|
||||
/** Launch-only plugin MCP servers and their owners; never persisted. */
|
||||
mcpServers?: Record<string, McpServerConfig>;
|
||||
mcpServerOwners?: Record<string, string>;
|
||||
@@ -692,8 +688,6 @@ export interface AgentUsageSession {
|
||||
}
|
||||
|
||||
export interface AgentSession {
|
||||
/** Persist the session's current handle immediately after an interactive resume. */
|
||||
readonly persistenceUpdatedOnResume?: boolean;
|
||||
usageSession?(): AgentUsageSession | null;
|
||||
readonly provider: AgentProvider;
|
||||
readonly id: string | null;
|
||||
|
||||
@@ -498,26 +498,3 @@ test("finish recovery protects callers before durable intent has loaded", async
|
||||
expect(recovered.hasPendingForCaller("parent")).toBe(true);
|
||||
expect(recovered.hasPendingForCaller("unrelated")).toBe(false);
|
||||
});
|
||||
|
||||
test("an undispatched follow-up does not block the running child's permission notification", async () => {
|
||||
const state = await scenario();
|
||||
await state.service.register(intent);
|
||||
await until(() => state.observation.waits.length === 1);
|
||||
await state.service.register(intent, true);
|
||||
const result = outcome("running");
|
||||
result.status = "permission";
|
||||
result.final!.pendingPermissions = [
|
||||
{
|
||||
id: "approval",
|
||||
provider: "codex",
|
||||
name: "Bash",
|
||||
kind: "tool",
|
||||
input: { command: "run tests" },
|
||||
} as NonNullable<typeof result.final>["pendingPermissions"][number],
|
||||
];
|
||||
state.observation.waits[0]!.result.resolve(result);
|
||||
await until(() => state.delivery.prompts.length === 1);
|
||||
expect(state.delivery.prompts[0]).toContain("needs permission");
|
||||
expect(state.delivery.prompts[0]).toContain("approval");
|
||||
expect(await state.store.list()).toHaveLength(2);
|
||||
});
|
||||
|
||||
@@ -267,9 +267,7 @@ export function createFinishSubscriptions(deps: Dependencies): FinishSubscriptio
|
||||
continue;
|
||||
}
|
||||
if (signal.aborted) return;
|
||||
// A queued follow-up cannot start until the current permission is answered.
|
||||
// Its pending registration must not hold the running turn's checkpoint.
|
||||
if (pending.status !== "permission" || watch.pending) await decisions(group);
|
||||
await decisions(group);
|
||||
if (signal.aborted) return;
|
||||
if (await suppressed(record, pending)) {
|
||||
await remove(watch);
|
||||
|
||||
@@ -298,7 +298,7 @@ export function createHostResolver(input: {
|
||||
status: agent.status,
|
||||
guidance:
|
||||
receipt.deliveryStatus === "queued"
|
||||
? "Queued for delivery after two quiet seconds and the current turn ends, unless interrupt was requested. You will get notified when the prompted agent finishes, errors, or needs permission unless notifyOnFinish is false."
|
||||
? "Queued for delivery after two quiet seconds. You will get notified when the prompted agent finishes, errors, or needs permission unless notifyOnFinish is false."
|
||||
: "Dispatch acknowledged. Observe completion using get_agent_status/get_agent_activity or SDK/RPC subscriptions and wait APIs.",
|
||||
});
|
||||
},
|
||||
|
||||
@@ -172,12 +172,11 @@ function registeredTool(
|
||||
async function invokeToolWithParsedInput(
|
||||
tool: RegisteredMcpToolWithHandler,
|
||||
input: Record<string, unknown>,
|
||||
awaitDispatch = true,
|
||||
) {
|
||||
const parsed = await tool.inputSchema.safeParseAsync(input);
|
||||
expect(parsed.success).toBe(true);
|
||||
const response = await tool.handler(parsed.data);
|
||||
if (awaitDispatch && response.structuredContent.deliveryStatus === "queued") {
|
||||
if (response.structuredContent.deliveryStatus === "queued") {
|
||||
await toolDeliveries
|
||||
.get(tool)!
|
||||
.waitForDispatch(input.agentId as string, new AbortController().signal);
|
||||
@@ -265,6 +264,7 @@ function buildAgentManagerSpies() {
|
||||
archiveAgent: vi.fn().mockResolvedValue({ archivedAt: new Date().toISOString() }),
|
||||
notifyAgentState: vi.fn(),
|
||||
getAgent: vi.fn(),
|
||||
getAgentBackgroundWorkSummary: vi.fn().mockReturnValue(undefined),
|
||||
listAgents: vi.fn().mockReturnValue([]),
|
||||
getTimeline: vi.fn().mockReturnValue([]),
|
||||
resumeAgentFromPersistence: vi.fn(),
|
||||
@@ -275,7 +275,6 @@ function buildAgentManagerSpies() {
|
||||
effectiveOptionsFor: (_provider: string, own?: Record<string, unknown>) => own ?? {},
|
||||
reloadStalePluginSession: async () => {},
|
||||
hasInFlightRun: vi.fn().mockReturnValue(false),
|
||||
hasPendingPermissions: () => false,
|
||||
steerOrReplaceActiveTurn: async () => ({ status: "inactive" as const }),
|
||||
tryRunOutOfBand: vi.fn().mockReturnValue(false),
|
||||
subscribe: vi.fn().mockReturnValue(() => {}),
|
||||
@@ -625,12 +624,6 @@ class FakeBrowserToolsBroker {
|
||||
}
|
||||
|
||||
class BoundaryAgentManagerFake {
|
||||
subscribe() {
|
||||
return () => {};
|
||||
}
|
||||
hasPendingPermissions() {
|
||||
return false;
|
||||
}
|
||||
public getPluginTools(): [] {
|
||||
return [];
|
||||
}
|
||||
@@ -885,9 +878,8 @@ function createPaseoWorktreeForMcpTest(options: {
|
||||
async function createAgentMcpServer(
|
||||
options: Parameters<typeof createAgentMcpServerWithDependencies>[0],
|
||||
subscriptionStore?: FinishSubscriptionStore,
|
||||
schedule?: (delayMs: number, callback: () => void) => () => void,
|
||||
) {
|
||||
const messages = createTestAgentMessages({ ...options, schedule });
|
||||
const messages = createTestAgentMessages(options);
|
||||
const records = new Map<string, FinishSubscription>();
|
||||
const subscriptions = createFinishSubscriptions({
|
||||
store: subscriptionStore ?? {
|
||||
@@ -3686,15 +3678,15 @@ class HeldTurnAgentClient implements AgentClient {
|
||||
|
||||
describe("send_agent_prompt MCP tool", () => {
|
||||
it.each([
|
||||
{ agentScoped: true, behavior: undefined, available: true },
|
||||
{ agentScoped: true, behavior: "interrupt", available: true },
|
||||
{ agentScoped: true, behavior: "steer", available: true },
|
||||
{ agentScoped: false, behavior: undefined, available: true },
|
||||
{ agentScoped: false, behavior: "steer", available: true },
|
||||
{ agentScoped: true, behavior: undefined, available: false },
|
||||
{ agentScoped: true, behavior: undefined, available: true, steered: true },
|
||||
{ agentScoped: true, behavior: "interrupt", available: true, steered: false },
|
||||
{ agentScoped: true, behavior: "steer", available: true, steered: true },
|
||||
{ agentScoped: false, behavior: undefined, available: true, steered: false },
|
||||
{ agentScoped: false, behavior: "steer", available: true, steered: true },
|
||||
{ agentScoped: true, behavior: undefined, available: false, steered: false },
|
||||
] as const)(
|
||||
"dispatches behavior $behavior for agent-scoped=$agentScoped, steering available=$available",
|
||||
async ({ agentScoped, behavior, available }) => {
|
||||
async ({ agentScoped, behavior, available, steered }) => {
|
||||
const workdir = await mkdtemp(join(tmpdir(), "mcp-send-behavior-"));
|
||||
const storage = new AgentStorage(join(workdir, "agents"), logger);
|
||||
const client = new HeldTurnAgentClient("codex", true, {
|
||||
@@ -3726,33 +3718,18 @@ describe("send_agent_prompt MCP tool", () => {
|
||||
notifyOnFinish: false,
|
||||
});
|
||||
const originalTurn = manager.getAgent(child.id)!.activeTurnId;
|
||||
const queued = agentScoped && behavior !== "interrupt";
|
||||
const steered = !agentScoped && behavior === "steer";
|
||||
const response = await invokeToolWithParsedInput(
|
||||
tool,
|
||||
{
|
||||
agentId: child.id,
|
||||
prompt: "New message",
|
||||
notifyOnFinish: false,
|
||||
...(behavior ? { activeTurnBehavior: behavior } : {}),
|
||||
},
|
||||
!queued,
|
||||
);
|
||||
const response = await invokeToolWithParsedInput(tool, {
|
||||
agentId: child.id,
|
||||
prompt: "New message",
|
||||
notifyOnFinish: false,
|
||||
...(behavior ? { activeTurnBehavior: behavior } : {}),
|
||||
});
|
||||
expect(response.structuredContent).toMatchObject({
|
||||
success: true,
|
||||
...(agentScoped
|
||||
? { deliveryStatus: "queued" }
|
||||
: { disposition: steered ? "steered" : "turn_started" }),
|
||||
});
|
||||
if (queued) {
|
||||
expect(client.sessions[1]!.prompts).toHaveLength(1);
|
||||
expect(client.sessions[1]!.steeredPrompts).toEqual([]);
|
||||
expect(manager.getAgent(child.id)!.activeTurnId).toBe(originalTurn);
|
||||
client.sessions[1]!.finishTurn();
|
||||
await serverDeliveries
|
||||
.get(server)!
|
||||
.waitForDispatch(child.id, new AbortController().signal);
|
||||
}
|
||||
expect(client.sessions[1]!.prompts).toHaveLength(steered ? 1 : 2);
|
||||
expect(client.sessions[1]!.steeredPrompts).toHaveLength(steered ? 1 : 0);
|
||||
expect(manager.getAgent(child.id)!.activeTurnId === originalTurn).toBe(steered);
|
||||
@@ -3764,16 +3741,18 @@ describe("send_agent_prompt MCP tool", () => {
|
||||
|
||||
it.each([
|
||||
{ rejected: false, priorNotification: false },
|
||||
{ rejected: false, priorNotification: true },
|
||||
{ rejected: true, priorNotification: false },
|
||||
{ rejected: true, priorNotification: true },
|
||||
{ rejected: false, priorNotification: true },
|
||||
])(
|
||||
"keeps completion tied to queued dispatch acknowledgement (rejected: $rejected, prior notification: $priorNotification)",
|
||||
"buffers completion until steer acknowledgement (rejected: $rejected, prior notification: $priorNotification)",
|
||||
async ({ rejected, priorNotification }) => {
|
||||
const workdir = await mkdtemp(join(tmpdir(), "mcp-queued-ack-"));
|
||||
const workdir = await mkdtemp(join(tmpdir(), "mcp-send-behavior-"));
|
||||
const storage = new AgentStorage(join(workdir, "agents"), logger);
|
||||
const options: HeldTurnOptions = {};
|
||||
const client = new HeldTurnAgentClient("codex", true, options);
|
||||
const client = new HeldTurnAgentClient("codex", true, {
|
||||
steerResult: "accepted",
|
||||
finishDuringSteer: true,
|
||||
rejectSteer: rejected,
|
||||
});
|
||||
const manager = new AgentManager({ clients: { codex: client }, registry: storage, logger });
|
||||
let mcpClient: Client | undefined;
|
||||
try {
|
||||
@@ -3795,47 +3774,104 @@ describe("send_agent_prompt MCP tool", () => {
|
||||
logger,
|
||||
});
|
||||
mcpClient = await connectInMemoryMcpClient(server);
|
||||
await sendMcpAndAwaitDispatch(mcpClient, server, {
|
||||
const send = (input: Record<string, unknown>) =>
|
||||
sendMcpAndAwaitDispatch(mcpClient!, server, input);
|
||||
await send({
|
||||
agentId: child.id,
|
||||
prompt: "Original work",
|
||||
notifyOnFinish: priorNotification,
|
||||
});
|
||||
const session = client.sessions[1]!;
|
||||
const release = session.holdTurnStart();
|
||||
options.finishTurnsDuringStart = true;
|
||||
if (rejected) session.rejectNextTurnStart(new Error("Start rejected"));
|
||||
const response = await mcpClient.callTool({
|
||||
name: "send_agent_prompt",
|
||||
arguments: { agentId: child.id, prompt: "New message", notifyOnFinish: true },
|
||||
const sending = send({
|
||||
agentId: child.id,
|
||||
prompt: "New message",
|
||||
notifyOnFinish: true,
|
||||
});
|
||||
expect(response.structuredContent).toMatchObject({
|
||||
success: true,
|
||||
deliveryStatus: "queued",
|
||||
});
|
||||
const dispatch = serverDeliveries
|
||||
.get(server)!
|
||||
.waitForDispatch(child.id, new AbortController().signal);
|
||||
const rejectedDispatch = rejected
|
||||
? expect(dispatch).rejects.toThrow("Start rejected")
|
||||
: null;
|
||||
expect(client.sessions[0]!.prompts).toHaveLength(0);
|
||||
session.finishTurn();
|
||||
await vi.waitFor(() => expect(session.prompts).toHaveLength(2));
|
||||
expect(client.sessions[0]!.prompts).toHaveLength(0);
|
||||
release();
|
||||
if (rejectedDispatch) await rejectedDispatch;
|
||||
else await dispatch;
|
||||
if (!rejected || priorNotification) {
|
||||
await vi.waitFor(() => expect(client.sessions[0]!.prompts).toHaveLength(1), {
|
||||
timeout: 5000,
|
||||
});
|
||||
expect(parseAgentMessage(client.sessions[0]!.prompts[0])).toMatchObject({
|
||||
source: { kind: "agent-notification", agentId: child.id, event: "finished" },
|
||||
});
|
||||
} else {
|
||||
await serverSubscriptions.get(server)!.close();
|
||||
if (rejected) {
|
||||
await expect(sending).rejects.toThrow("Steer rejected");
|
||||
// Flush asynchronous notification work before checking that a rejected
|
||||
// dispatch did not notify. Then prove a later successful send still can.
|
||||
await new Promise((resolve) => setTimeout(resolve, 50));
|
||||
expect(client.sessions[0]!.prompts).toHaveLength(0);
|
||||
await send({
|
||||
agentId: child.id,
|
||||
prompt: "Retry after rejection",
|
||||
});
|
||||
client.sessions[1]!.finishTurn();
|
||||
} else {
|
||||
const response = await sending;
|
||||
expect(response.structuredContent).toMatchObject({
|
||||
success: true,
|
||||
deliveryStatus: "queued",
|
||||
});
|
||||
}
|
||||
await vi.waitFor(() => expect(client.sessions[0]!.prompts).toHaveLength(1));
|
||||
expect(parseAgentMessage(client.sessions[0]!.prompts[0])).toMatchObject({
|
||||
source: { kind: "agent-notification", agentId: child.id, event: "finished" },
|
||||
});
|
||||
} finally {
|
||||
await mcpClient?.close();
|
||||
await removeAgentStateDir(manager, storage, workdir);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it.each([false, true])(
|
||||
"preserves the original notification after rejection (completion during send: %s)",
|
||||
async (finishDuringSteer) => {
|
||||
const workdir = await mkdtemp(join(tmpdir(), "mcp-send-behavior-"));
|
||||
const storage = new AgentStorage(join(workdir, "agents"), logger);
|
||||
const client = new HeldTurnAgentClient("codex", true, {
|
||||
steerResult: "accepted",
|
||||
finishDuringSteer,
|
||||
rejectSteer: true,
|
||||
});
|
||||
const manager = new AgentManager({ clients: { codex: client }, registry: storage, logger });
|
||||
let mcpClient: Client | undefined;
|
||||
try {
|
||||
const parent = await manager.createAgent(
|
||||
{ provider: "codex", cwd: existingCwd },
|
||||
undefined,
|
||||
{
|
||||
workspaceId: "wks_parent",
|
||||
},
|
||||
);
|
||||
const child = await manager.createAgent(
|
||||
{ provider: "codex", cwd: existingCwd },
|
||||
undefined,
|
||||
{
|
||||
workspaceId: "wks_parent",
|
||||
},
|
||||
);
|
||||
const server = await createAgentMcpServer({
|
||||
agentManager: manager,
|
||||
agentStorage: storage,
|
||||
callerAgentId: parent.id,
|
||||
providerSnapshotManager: createOpenCodeManager().manager,
|
||||
logger,
|
||||
});
|
||||
mcpClient = await connectInMemoryMcpClient(server);
|
||||
const send = (input: Record<string, unknown>) =>
|
||||
sendMcpAndAwaitDispatch(mcpClient!, server, input);
|
||||
await send({
|
||||
agentId: child.id,
|
||||
prompt: "Original work",
|
||||
notifyOnFinish: true,
|
||||
});
|
||||
const sending = send({
|
||||
agentId: child.id,
|
||||
prompt: "New message",
|
||||
notifyOnFinish: true,
|
||||
});
|
||||
await expect(sending).rejects.toThrow("Steer rejected");
|
||||
if (!finishDuringSteer) {
|
||||
await new Promise((resolve) => setTimeout(resolve, 50));
|
||||
expect(client.sessions[0]!.prompts).toHaveLength(0);
|
||||
client.sessions[1]!.finishTurn();
|
||||
}
|
||||
await vi.waitFor(() => expect(client.sessions[0]!.prompts).toHaveLength(1));
|
||||
expect(parseAgentMessage(client.sessions[0]!.prompts[0])).toMatchObject({
|
||||
source: { kind: "agent-notification", agentId: child.id, event: "finished" },
|
||||
});
|
||||
} finally {
|
||||
await mcpClient?.close();
|
||||
await removeAgentStateDir(manager, storage, workdir);
|
||||
@@ -3977,7 +4013,7 @@ describe("send_agent_prompt MCP tool", () => {
|
||||
const response = await tool.handler(parsed.data as Record<string, unknown>);
|
||||
|
||||
expect(response.structuredContent).toMatchObject({ deliveryStatus: "queued" });
|
||||
expect(serverSubscriptionRecords.get(server)!.size).toBe(1);
|
||||
expect(spies.agentManager.subscribe).not.toHaveBeenCalled();
|
||||
await serverDeliveries
|
||||
.get(server)!
|
||||
.waitForDispatch("child-agent", new AbortController().signal);
|
||||
@@ -4018,7 +4054,7 @@ describe("send_agent_prompt MCP tool", () => {
|
||||
|
||||
await tool.handler(parsed.data as Record<string, unknown>);
|
||||
|
||||
expect(serverSubscriptionRecords.get(server)!.size).toBe(0);
|
||||
expect(spies.agentManager.subscribe).not.toHaveBeenCalled();
|
||||
expect(spies.agentManager.waitForAgentEvent).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
@@ -4061,7 +4097,7 @@ describe("send_agent_prompt MCP tool", () => {
|
||||
notifyOnFinish: false,
|
||||
});
|
||||
|
||||
expect(serverSubscriptionRecords.get(server)!.size).toBe(0);
|
||||
expect(spies.agentManager.subscribe).not.toHaveBeenCalled();
|
||||
expect(spies.agentManager.waitForAgentEvent).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
@@ -4185,15 +4221,11 @@ describe("send_agent_prompt MCP tool", () => {
|
||||
notifyOnFinish: false,
|
||||
});
|
||||
if (scenario !== "startup_failure") {
|
||||
const response = await invokeToolWithParsedInput(
|
||||
tool,
|
||||
{
|
||||
agentId: child.id,
|
||||
prompt: "/side-command",
|
||||
activeTurnBehavior: scenario === "out_of_band_interrupt" ? "interrupt" : "steer",
|
||||
},
|
||||
scenario !== "out_of_band",
|
||||
);
|
||||
const response = await invokeToolWithParsedInput(tool, {
|
||||
agentId: child.id,
|
||||
prompt: "/side-command",
|
||||
activeTurnBehavior: scenario === "out_of_band_interrupt" ? "interrupt" : "steer",
|
||||
});
|
||||
expect(response.structuredContent).toMatchObject({
|
||||
success: true,
|
||||
deliveryStatus: "queued",
|
||||
@@ -4205,9 +4237,6 @@ describe("send_agent_prompt MCP tool", () => {
|
||||
});
|
||||
expect(parentClient.sessions[0]!.prompts).toHaveLength(0);
|
||||
childClient.sessions[0]!.finishTurn("Ongoing task done");
|
||||
await serverDeliveries
|
||||
.get(server)!
|
||||
.waitForDispatch(child.id, new AbortController().signal);
|
||||
await vi.waitFor(() => {
|
||||
expect(parentClient.sessions[0]!.prompts).toHaveLength(1);
|
||||
expect(parentClient.sessions[0]!.prompts[0]).toContain("finished.");
|
||||
@@ -4215,11 +4244,7 @@ describe("send_agent_prompt MCP tool", () => {
|
||||
} else {
|
||||
childClient.sessions[0]!.rejectNextTurnStart(new Error("Requested turn could not start"));
|
||||
await expect(
|
||||
invokeToolWithParsedInput(tool, {
|
||||
agentId: child.id,
|
||||
prompt: "Replacement task",
|
||||
activeTurnBehavior: "interrupt",
|
||||
}),
|
||||
invokeToolWithParsedInput(tool, { agentId: child.id, prompt: "Replacement task" }),
|
||||
).rejects.toThrow("Requested turn could not start");
|
||||
// A later real turn must not inherit a subscription from the rejected dispatch.
|
||||
await invokeToolWithParsedInput(tool, {
|
||||
@@ -4330,7 +4355,6 @@ describe("send_agent_prompt MCP tool", () => {
|
||||
const sent = await invokeToolWithParsedInput(registeredTool(server, "send_agent_prompt"), {
|
||||
agentId: childId,
|
||||
prompt: "Stop and reply instead",
|
||||
activeTurnBehavior: "interrupt",
|
||||
});
|
||||
expect(sent.structuredContent).toMatchObject({
|
||||
success: true,
|
||||
@@ -4494,7 +4518,7 @@ describe("send_agent_prompt MCP tool to an OMP child", () => {
|
||||
const logger = createTestLogger();
|
||||
const existingCwd = process.cwd();
|
||||
|
||||
async function setupOmpChild(schedule?: (delayMs: number, callback: () => void) => () => void) {
|
||||
async function setupOmpChild() {
|
||||
const workdir = await mkdtemp(join(tmpdir(), "mcp-omp-child-"));
|
||||
const storage = new AgentStorage(join(workdir, "agents"), logger);
|
||||
const parentClient = new HeldTurnAgentClient("claude", false);
|
||||
@@ -4522,17 +4546,13 @@ describe("send_agent_prompt MCP tool to an OMP child", () => {
|
||||
undefined,
|
||||
{ workspaceId: "wks_parent" },
|
||||
);
|
||||
const server = await createAgentMcpServer(
|
||||
{
|
||||
agentManager,
|
||||
agentStorage: storage,
|
||||
callerAgentId: parent.id,
|
||||
providerSnapshotManager: createOpenCodeManager().manager,
|
||||
logger,
|
||||
},
|
||||
undefined,
|
||||
schedule,
|
||||
);
|
||||
const server = await createAgentMcpServer({
|
||||
agentManager,
|
||||
agentStorage: storage,
|
||||
callerAgentId: parent.id,
|
||||
providerSnapshotManager: createOpenCodeManager().manager,
|
||||
logger,
|
||||
});
|
||||
return {
|
||||
agentManager,
|
||||
storage,
|
||||
@@ -4562,63 +4582,37 @@ describe("send_agent_prompt MCP tool to an OMP child", () => {
|
||||
{ command: "follow-up", streamingBehavior: "followUp" },
|
||||
{ command: "steer", streamingBehavior: "steer" },
|
||||
] as const)(
|
||||
"delivers /$command to a running OMP child while ordinary messages in the same quiet window wait",
|
||||
"delivers /$command into a turn OMP started on its own, without aborting it",
|
||||
async ({ command, streamingBehavior }) => {
|
||||
let flush!: () => void;
|
||||
const { agentManager, storage, workdir, ompSession, childId, tool } = await setupOmpChild(
|
||||
(_delay, callback) => {
|
||||
flush = callback;
|
||||
return () => {};
|
||||
},
|
||||
);
|
||||
const { agentManager, storage, workdir, parentClient, ompSession, childId, tool } =
|
||||
await setupOmpChild();
|
||||
try {
|
||||
ompSession.beginTurn();
|
||||
ompSession.streamAssistantText("background job finished, working on it");
|
||||
await vi.waitFor(() => {
|
||||
expect(agentManager.getAgent(childId)?.activeTurnId).toMatch(/^autonomous-/);
|
||||
});
|
||||
const activeTurnId = agentManager.getAgent(childId)?.activeTurnId;
|
||||
const delivery = toolDeliveries.get(tool)!;
|
||||
let ordinaryBeforeDispatch = 0;
|
||||
const ordinary = delivery.enqueue({
|
||||
recipientId: childId,
|
||||
source: { kind: "agent-message", agentId: "parent" },
|
||||
prompt: "ordinary follow-up",
|
||||
beforeDispatch: () => {
|
||||
ordinaryBeforeDispatch++;
|
||||
},
|
||||
|
||||
const response = await invokeToolWithParsedInput(tool, {
|
||||
agentId: childId,
|
||||
prompt: `/${command} then summarize the logs`,
|
||||
});
|
||||
const response = await invokeToolWithParsedInput(
|
||||
tool,
|
||||
{
|
||||
agentId: childId,
|
||||
prompt: `/${command} then summarize the logs`,
|
||||
},
|
||||
false,
|
||||
);
|
||||
flush();
|
||||
await vi.waitFor(() => {
|
||||
expect(ompSession.prompts).toEqual([
|
||||
{ message: "then summarize the logs", imageCount: 0, streamingBehavior },
|
||||
]);
|
||||
});
|
||||
expect(ordinaryBeforeDispatch).toBe(0);
|
||||
expect(agentManager.getAgent(childId)?.activeTurnId).toBe(activeTurnId);
|
||||
|
||||
expect(response.structuredContent).toMatchObject({
|
||||
success: true,
|
||||
deliveryStatus: "queued",
|
||||
status: "running",
|
||||
});
|
||||
await vi.waitFor(() => {
|
||||
expect(ompSession.prompts).toEqual([
|
||||
{ message: "then summarize the logs", imageCount: 0, streamingBehavior },
|
||||
]);
|
||||
});
|
||||
expect(ompSession.abortRequested).toBe(false);
|
||||
expect(agentManager.getAgent(childId)?.lifecycle).toBe("running");
|
||||
|
||||
ompSession.finishTurn();
|
||||
await ordinary.dispatched;
|
||||
expect(ordinaryBeforeDispatch).toBe(1);
|
||||
expect(ompSession.prompts).toHaveLength(2);
|
||||
expect(ompSession.prompts[1]!.message).toContain("ordinary follow-up");
|
||||
ompSession.beginTurn();
|
||||
ompSession.finishTurn();
|
||||
await expectOneFinishNotification(agentManager, parentClient, childId);
|
||||
} finally {
|
||||
await removeAgentStateDir(agentManager, storage, workdir);
|
||||
}
|
||||
@@ -6188,6 +6182,36 @@ describe("agent snapshot MCP serialization", () => {
|
||||
expect(structured.agents[0]).not.toHaveProperty("pendingPermissions");
|
||||
});
|
||||
|
||||
it("reports an idle agent's background work from get_agent_status and list_agents", async () => {
|
||||
const { agentManager, agentStorage, spies } = createTestDeps();
|
||||
const agent = createManagedAgent({ id: "agent-with-shell", cwd: REPO_CWD });
|
||||
spies.agentManager.getAgent.mockReturnValue(agent);
|
||||
spies.agentManager.listAgents.mockReturnValue([agent]);
|
||||
spies.agentManager.getAgentBackgroundWorkSummary.mockReturnValue({ count: 1 });
|
||||
|
||||
const server = await createAgentMcpServer({
|
||||
agentManager,
|
||||
agentStorage,
|
||||
providerSnapshotManager: createOpenCodeManager().manager,
|
||||
logger,
|
||||
});
|
||||
const status = await registeredTool(server, "get_agent_status").handler({
|
||||
agentId: "agent-with-shell",
|
||||
});
|
||||
const list = await registeredTool(server, "list_agents").handler({});
|
||||
|
||||
expect(status.structuredContent).toEqual({
|
||||
status: "idle",
|
||||
snapshot: expect.objectContaining({ status: "idle", backgroundWork: { count: 1 } }),
|
||||
});
|
||||
expect(list.structuredContent).toEqual({
|
||||
agents: [expect.objectContaining({ status: "idle", backgroundWork: { count: 1 } })],
|
||||
});
|
||||
expect(spies.agentManager.getAgentBackgroundWorkSummary).toHaveBeenCalledWith(
|
||||
"agent-with-shell",
|
||||
);
|
||||
});
|
||||
|
||||
it("returns archived agent snapshots from storage for get_agent_status", async () => {
|
||||
const { agentManager, agentStorage, spies } = createTestDeps();
|
||||
const record = createStoredRecord({
|
||||
|
||||
@@ -1949,11 +1949,7 @@ function mapSessionConfig(
|
||||
return {
|
||||
cwd: config.cwd,
|
||||
env: createProviderEnv({ baseEnv: {}, overlays: [launchContext?.env] }),
|
||||
systemPrompt: combineSystemPrompts(
|
||||
config.systemPrompt,
|
||||
config.daemonAppendSystemPrompt,
|
||||
...(config.pluginAppendSystemPrompt ?? []),
|
||||
),
|
||||
systemPrompt: combineSystemPrompts(config.systemPrompt, config.daemonAppendSystemPrompt),
|
||||
mcpServers: { ...config.mcpServers },
|
||||
toolPolicy: config.toolPolicy
|
||||
? { preapproved: config.toolPolicy.preapproved.map((grant) => ({ ...grant })) }
|
||||
@@ -1972,9 +1968,8 @@ function mapSessionConfig(
|
||||
function combineSystemPrompts(
|
||||
systemPrompt: string | undefined,
|
||||
daemonPrompt: string | undefined,
|
||||
...pluginPrompts: string[]
|
||||
): string | undefined {
|
||||
const parts = [systemPrompt, daemonPrompt, ...pluginPrompts].filter(
|
||||
const parts = [systemPrompt, daemonPrompt].filter(
|
||||
(value): value is string => typeof value === "string" && value.trim().length > 0,
|
||||
);
|
||||
return parts.length > 0 ? parts.join("\n\n") : undefined;
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user