mirror of
https://github.com/getpaseo/paseo.git
synced 2026-11-18 14:25:25 +00:00
Compare commits
53
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
25011369e1 | ||
|
|
bab16c6d09 | ||
|
|
99ab18c473 | ||
|
|
3e34be1228 | ||
|
|
20d7ae6cd5 | ||
|
|
32e7df0554 | ||
|
|
91e7293773 | ||
|
|
63a33ac3fd | ||
|
|
a5edd91f91 | ||
|
|
e44edf5b35 | ||
|
|
59d6018dac | ||
|
|
b24eab785b | ||
|
|
1821ac3f93 | ||
|
|
a1088a787d | ||
|
|
576d0320c8 | ||
|
|
c8e3d67e29 | ||
|
|
95f2c7d16a | ||
|
|
2c2385f362 | ||
|
|
7f0fe57c48 | ||
|
|
94f2df6263 | ||
|
|
02124454bc | ||
|
|
c71d41f687 | ||
|
|
689e3412b4 | ||
|
|
349a2e43ea | ||
|
|
eabbd3d97c | ||
|
|
0bac18f359 | ||
|
|
3eedffc4ac | ||
|
|
e5352c9890 | ||
|
|
ce09360241 | ||
|
|
8f3752ecb9 | ||
|
|
73c22f7917 | ||
|
|
038a9ca00d | ||
|
|
3a7e216b7d | ||
|
|
6ef188416f | ||
|
|
791bbd3596 | ||
|
|
b95f1bbf31 | ||
|
|
c2a24ae81e | ||
|
|
6eb94611b3 | ||
|
|
a8cadae0ee | ||
|
|
5a78c1cd16 | ||
|
|
8522d18ed8 | ||
|
|
be92e85a4e | ||
|
|
3d30aaec42 | ||
|
|
a302e65c85 | ||
|
|
d49991318f | ||
|
|
33259746db | ||
|
|
41c294c785 | ||
|
|
e19980a6c9 | ||
|
|
fa8ba1bd3b | ||
|
|
e7e1b44ec8 | ||
|
|
ee3a3ba8c5 | ||
|
|
d15190803a | ||
|
|
ade3817a45 |
@@ -1,26 +1,5 @@
|
||||
# Changelog
|
||||
|
||||
## 0.16.2 - 2026-11-18
|
||||
|
||||
### Fixed
|
||||
|
||||
- Fixed Collapse turns hiding a finished reply when Claude answers a later background task notification ([#10092](https://github.com/getpaseo/paseo/pull/10092))
|
||||
- Fixed detached worktree commits getting lost when archiving a workspace ([#10009](https://github.com/getpaseo/paseo/pull/10009) by [@ragokan](https://github.com/ragokan))
|
||||
- Fixed Desktop updates leaving an older daemon running when an earlier Desktop session started it ([#10067](https://github.com/getpaseo/paseo/pull/10067))
|
||||
- Fixed daemons losing their Hub connection after execution permissions changed ([#10113](https://github.com/getpaseo/paseo/pull/10113))
|
||||
- Fixed saved hosts disappearing when one stored entry could not be read ([#9847](https://github.com/getpaseo/paseo/pull/9847) by [@ragokan](https://github.com/ragokan))
|
||||
- Fixed worktree creation timing out while scanning large ignored folders that `.worktreeinclude` does not name ([#10020](https://github.com/getpaseo/paseo/pull/10020) by [@mgranderath](https://github.com/mgranderath))
|
||||
- Fixed Steer cancelling a Claude compaction in progress ([#10028](https://github.com/getpaseo/paseo/pull/10028) by [@NightMachinery](https://github.com/NightMachinery))
|
||||
- Fixed agents getting stuck after a second Stop when the provider reused the cancelled turn ID ([#9774](https://github.com/getpaseo/paseo/pull/9774) by [@DAnaeto](https://github.com/DAnaeto))
|
||||
- Fixed Desktop staying blank after its renderer exited unexpectedly ([#10035](https://github.com/getpaseo/paseo/pull/10035))
|
||||
- Fixed failed file downloads taking over the app window on web and Desktop ([#9937](https://github.com/getpaseo/paseo/pull/9937) by [@panta82](https://github.com/panta82))
|
||||
- Fixed Import Session losing its scroll position when you select Load more ([#9974](https://github.com/getpaseo/paseo/pull/9974))
|
||||
- Fixed terminals failing to open when the home filesystem refuses Unix sockets, such as on AFS ([#9214](https://github.com/getpaseo/paseo/pull/9214) by [@bendavid](https://github.com/bendavid))
|
||||
- Fixed timed-out Git watchers repeatedly rescanning large repositories ([#9828](https://github.com/getpaseo/paseo/pull/9828) by [@Spshulem](https://github.com/Spshulem))
|
||||
- Fixed `paseo workspace create --path .` using the local daemon's directory instead of the caller's ([#10010](https://github.com/getpaseo/paseo/pull/10010))
|
||||
- Fixed MCP agent status and list responses omitting background work for idle agents ([#10022](https://github.com/getpaseo/paseo/pull/10022) by [@ortschun](https://github.com/ortschun))
|
||||
- Fixed the thinking selector showing an old level after OMP changes it ([#9841](https://github.com/getpaseo/paseo/pull/9841) by [@dsingal0](https://github.com/dsingal0))
|
||||
|
||||
## 0.16.1 - 2026-11-17
|
||||
|
||||
### Fixed
|
||||
|
||||
@@ -1,26 +1,5 @@
|
||||
# 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
|
||||
|
||||
### 修复
|
||||
|
||||
@@ -150,12 +150,13 @@ 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, 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.
|
||||
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.
|
||||
|
||||
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.
|
||||
admission within their original timeout and cancellation scope, and return permission checkpoints
|
||||
while messages are waiting.
|
||||
|
||||
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
|
||||
|
||||
@@ -121,6 +121,14 @@ from `packages/app/android`:
|
||||
|
||||
These check terminal arrow ownership, held-key repeats and modifiers, and ordinary text-field editing.
|
||||
|
||||
Run the display density regression tests the same way:
|
||||
|
||||
```bash
|
||||
./gradlew :paseo-display-metrics:connectedDebugAndroidTest --no-daemon --max-workers=2 -Dorg.gradle.parallel=false
|
||||
```
|
||||
|
||||
These check that React Native sizes text at the window's density when the window is on another display, such as Samsung DeX.
|
||||
|
||||
### Diagnostic logs without ADB
|
||||
|
||||
In a dogfood build, open Android's Files app → Downloads → **Paseo diagnostics** and share all
|
||||
|
||||
@@ -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 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.
|
||||
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.
|
||||
3. **Remote + relay**: Daemon behind firewall, relay bridges with E2E encryption
|
||||
|
||||
@@ -99,8 +99,10 @@ Register the adapter in `defaultForgeRegistry` with:
|
||||
|
||||
Current change-request lookup matches the branch and repository for both open and
|
||||
terminal requests. Prefer an open request, then a terminal request at the local
|
||||
HEAD, then the most recently updated terminal request. A reused branch can show
|
||||
its previous request until a new one opens. Auto-archive separately requires an
|
||||
HEAD, then the most recently updated terminal request. When the forge identifies
|
||||
the checkout's branch as the origin repository's default branch, only open
|
||||
requests are eligible. A reused feature branch can show its previous request
|
||||
until a new one opens. Auto-archive separately requires an
|
||||
observed open-to-merged transition and a fresh exact match between checkout HEAD
|
||||
and the PR head, along with the existing workspace safety checks.
|
||||
|
||||
|
||||
@@ -1,8 +0,0 @@
|
||||
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,8 +0,0 @@
|
||||
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,8 +0,0 @@
|
||||
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,8 +0,0 @@
|
||||
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-hN+Klz3jXugHs5MsVzIQIwIa/HGbpdJ04qolKvbsOuk=
|
||||
sha256-k7+5S/4tyAmHdZmUdhpuZ7GOc7hp9cG8wUBFdJI32ng=
|
||||
|
||||
Generated
+28
-28
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "paseo",
|
||||
"version": "0.16.2",
|
||||
"version": "0.16.1",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "paseo",
|
||||
"version": "0.16.2",
|
||||
"version": "0.16.1",
|
||||
"hasInstallScript": true,
|
||||
"license": "Apache-2.0",
|
||||
"workspaces": [
|
||||
@@ -37468,7 +37468,7 @@
|
||||
},
|
||||
"packages/app": {
|
||||
"name": "@getpaseo/app",
|
||||
"version": "0.16.2",
|
||||
"version": "0.16.1",
|
||||
"dependencies": {
|
||||
"@codemirror/commands": "6.10.4",
|
||||
"@codemirror/language": "6.12.4",
|
||||
@@ -39637,13 +39637,13 @@
|
||||
},
|
||||
"packages/cli": {
|
||||
"name": "@getpaseo/cli",
|
||||
"version": "0.16.2",
|
||||
"version": "0.16.1",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@clack/prompts": "^1.0.0",
|
||||
"@getpaseo/client": "0.16.2",
|
||||
"@getpaseo/protocol": "0.16.2",
|
||||
"@getpaseo/server": "0.16.2",
|
||||
"@getpaseo/client": "0.16.1",
|
||||
"@getpaseo/protocol": "0.16.1",
|
||||
"@getpaseo/server": "0.16.1",
|
||||
"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.2",
|
||||
"version": "0.16.1",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@getpaseo/protocol": "0.16.2",
|
||||
"@getpaseo/relay": "0.16.2",
|
||||
"@getpaseo/protocol": "0.16.1",
|
||||
"@getpaseo/relay": "0.16.1",
|
||||
"ws": "^8.20.0",
|
||||
"zod": "^4.4.3"
|
||||
},
|
||||
@@ -39906,7 +39906,7 @@
|
||||
},
|
||||
"packages/desktop": {
|
||||
"name": "@getpaseo/desktop",
|
||||
"version": "0.16.2",
|
||||
"version": "0.16.1",
|
||||
"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.2",
|
||||
"version": "0.16.1",
|
||||
"license": "MIT",
|
||||
"devDependencies": {
|
||||
"@types/jest": "^29.5.14",
|
||||
@@ -40195,7 +40195,7 @@
|
||||
},
|
||||
"packages/highlight": {
|
||||
"name": "@getpaseo/highlight",
|
||||
"version": "0.16.2",
|
||||
"version": "0.16.1",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@codemirror/language": "6.12.4",
|
||||
@@ -40225,7 +40225,7 @@
|
||||
},
|
||||
"packages/plugin": {
|
||||
"name": "@getpaseo/plugin",
|
||||
"version": "0.16.2",
|
||||
"version": "0.16.1",
|
||||
"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.2",
|
||||
"@getpaseo/protocol": "0.16.2",
|
||||
"@getpaseo/client": "0.16.1",
|
||||
"@getpaseo/protocol": "0.16.1",
|
||||
"@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.2",
|
||||
"@getpaseo/protocol": "0.16.2",
|
||||
"@getpaseo/client": "0.16.1",
|
||||
"@getpaseo/protocol": "0.16.1",
|
||||
"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.2",
|
||||
"version": "0.16.1",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"semver": "^7.8.5",
|
||||
@@ -40295,7 +40295,7 @@
|
||||
},
|
||||
"packages/relay": {
|
||||
"name": "@getpaseo/relay",
|
||||
"version": "0.16.2",
|
||||
"version": "0.16.1",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@noble/ciphers": "^2.4.0",
|
||||
@@ -40517,17 +40517,17 @@
|
||||
},
|
||||
"packages/server": {
|
||||
"name": "@getpaseo/server",
|
||||
"version": "0.16.2",
|
||||
"version": "0.16.1",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@agentclientprotocol/sdk": "^0.17.1",
|
||||
"@anthropic-ai/claude-agent-sdk": "0.3.326",
|
||||
"@anthropic-ai/sdk": "^0.104.2",
|
||||
"@getpaseo/client": "0.16.2",
|
||||
"@getpaseo/highlight": "0.16.2",
|
||||
"@getpaseo/plugin": "0.16.2",
|
||||
"@getpaseo/protocol": "0.16.2",
|
||||
"@getpaseo/relay": "0.16.2",
|
||||
"@getpaseo/client": "0.16.1",
|
||||
"@getpaseo/highlight": "0.16.1",
|
||||
"@getpaseo/plugin": "0.16.1",
|
||||
"@getpaseo/protocol": "0.16.1",
|
||||
"@getpaseo/relay": "0.16.1",
|
||||
"@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.2",
|
||||
"version": "0.16.1",
|
||||
"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.2",
|
||||
"version": "0.16.1",
|
||||
"dependencies": {
|
||||
"@getpaseo/plugin": "*",
|
||||
"zod": "^4.4.3"
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "paseo",
|
||||
"version": "0.16.2",
|
||||
"version": "0.16.1",
|
||||
"private": true,
|
||||
"description": "Paseo: voice-controlled development environment for local AI coding agents",
|
||||
"keywords": [
|
||||
|
||||
@@ -7,6 +7,7 @@ const withAndroidProfileable = require("./plugins/with-android-profileable");
|
||||
const withFdroidAutolinking = require("./plugins/with-fdroid-autolinking");
|
||||
const withPasteInput = require("./plugins/with-paste-input");
|
||||
const withAndroidScroll = require("./modules/paseo-scroll/app.plugin");
|
||||
const withAndroidDisplayMetrics = require("./modules/paseo-display-metrics/app.plugin");
|
||||
const { getNativeReleaseVersion } = require("./native-release-version");
|
||||
const appVariant = process.env.APP_VARIANT ?? "production";
|
||||
const isFdroidBuild = process.env.PASEO_FDROID_BUILD === "1";
|
||||
@@ -146,6 +147,7 @@ export default {
|
||||
"expo-router",
|
||||
withPasteInput,
|
||||
withAndroidScroll,
|
||||
withAndroidDisplayMetrics,
|
||||
[withAndroidAsyncStorageSize, 64],
|
||||
...buildProfile.cameraPlugins,
|
||||
withAndroidOptionalCamera,
|
||||
|
||||
@@ -2,10 +2,16 @@ import { copyPluginExample } from "../support/helpers/plugin-fixture";
|
||||
import { expect, test as base, type Page } from "../support/fixtures";
|
||||
import { gotoAppShell } from "../support/helpers/app";
|
||||
import { connectNewWorkspaceDaemonClient } from "../support/helpers/new-workspace";
|
||||
import { waitForSettledPosition } from "../support/helpers/sheet-layout";
|
||||
|
||||
async function openExample(page: Page, example: string) {
|
||||
await page.getByRole("button", { name: `Open ${example}`, exact: true }).click();
|
||||
await expect(page.getByText(`Modal example: ${example}`, { exact: true })).toBeVisible();
|
||||
const title = page.getByText(`Modal example: ${example}`, { exact: true });
|
||||
// A compact sheet holds below the viewport and then slides up, so a pointer placed before it
|
||||
// stops lands on whatever slides under it. The settle check starts once the slide has begun;
|
||||
// two equal reads during the hold would otherwise count as settled.
|
||||
await expect(title).toBeInViewport();
|
||||
await waitForSettledPosition(title);
|
||||
}
|
||||
|
||||
async function closeExample(page: Page) {
|
||||
|
||||
@@ -208,6 +208,35 @@ test.describe("Plugin sidebar items", () => {
|
||||
});
|
||||
});
|
||||
|
||||
test("a short desktop sidebar keeps workspaces usable while navigation scrolls", async ({
|
||||
page,
|
||||
}) => {
|
||||
await page.setViewportSize({ width: 1280, height: 480 });
|
||||
await gotoAppShell(page);
|
||||
await expect(botRow(page, "status")).toBeAttached();
|
||||
const workspace = visibleTestId(page, `sidebar-workspace-row-${getServerId()}:${workspaceId}`);
|
||||
await expect(workspace).toBeInViewport({ ratio: 1 });
|
||||
await expect(botRow(page, "status")).not.toBeInViewport();
|
||||
|
||||
await test.step("navigation stays within half the sidebar", async () => {
|
||||
const nav = await boxOf(visibleTestId(page, "sidebar-nav-scroll"));
|
||||
expect(nav.height).toBeLessThanOrEqual(480 / 2 + 1);
|
||||
});
|
||||
|
||||
await test.step("scrolling navigation reaches its last row without moving workspaces", async () => {
|
||||
const before = await boxOf(workspace);
|
||||
await visibleTestId(page, "sidebar-global-new-workspace").hover();
|
||||
await page.mouse.wheel(0, 800);
|
||||
await expect(botRow(page, "status")).toBeInViewport({ ratio: 1 });
|
||||
await expect(workspace).toBeInViewport({ ratio: 1 });
|
||||
expect((await boxOf(workspace)).y).toBe(before.y);
|
||||
await qaScreenshot(page, "desktop-short-sidebar-nav-scrolled");
|
||||
await botRow(page, "status").click();
|
||||
await expect(page.getByText("Bot status details", { exact: true })).toBeVisible();
|
||||
await page.getByRole("button", { name: "Close bot status", exact: true }).click();
|
||||
});
|
||||
});
|
||||
|
||||
test("a restored plugin screen waits for its catalog before rendering", async ({ page }) => {
|
||||
await page.setViewportSize(WIDE);
|
||||
await gotoWorkspace(page, workspaceId);
|
||||
@@ -333,6 +362,16 @@ test.describe("Plugin sidebar items", () => {
|
||||
});
|
||||
});
|
||||
|
||||
test("a plugin screen reads workspaces through the state hooks", async ({ page }) => {
|
||||
await page.setViewportSize(WIDE);
|
||||
await gotoWorkspace(page, workspaceId);
|
||||
await expect(headerRow(page, SHOWCASE_PLUGIN_ID, "deploys")).toBeVisible({ timeout: 30_000 });
|
||||
await runCommand(page, "Open plugin workspaces");
|
||||
await expect(screenTitle(page)).toHaveText("Workspaces");
|
||||
await expect(page.getByText(`Workspace ${workspaceId}`, { exact: true })).toBeVisible();
|
||||
await expect(page.getByText("Plugin failed", { exact: false })).toHaveCount(0);
|
||||
});
|
||||
|
||||
test("a header row's shortcut hint presses the row", async ({ page }) => {
|
||||
await page.setViewportSize(WIDE);
|
||||
await gotoWorkspace(page, workspaceId);
|
||||
|
||||
@@ -110,6 +110,7 @@ test.describe("Sidebar items in Appearance settings", () => {
|
||||
|
||||
await test.step("the sidebar starts in the default order", async () => {
|
||||
await expectSidebarOrder(page, ["new-workspace", "history", "search", "schedules"]);
|
||||
await expect(page.locator('[data-testid="sidebar-nav-separator"]:visible')).toHaveCount(1);
|
||||
});
|
||||
|
||||
await test.step("the Sidebar section lists every item in the same order", async () => {
|
||||
@@ -195,6 +196,9 @@ test.describe("Sidebar items in Appearance settings", () => {
|
||||
await expectSidebarItemHidden(page, "history");
|
||||
await expectSidebarItemHidden(page, "search");
|
||||
await expectSidebarItemHidden(page, "schedules");
|
||||
// Nothing is left above the Workspaces section: no drag strip, no empty divider.
|
||||
await expect(page.locator('[data-testid="sidebar-nav-drag-strip"]:visible')).toHaveCount(0);
|
||||
await expect(page.locator('[data-testid="sidebar-nav-separator"]:visible')).toHaveCount(0);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -73,35 +73,36 @@ function labelRow(page: import("@playwright/test").Page, name: string) {
|
||||
return page.getByTestId(`workspace-label-picker-row-${name}`);
|
||||
}
|
||||
|
||||
async function box(locator: import("@playwright/test").Locator) {
|
||||
const measured = await locator.boundingBox();
|
||||
if (!measured) throw new Error("expected a visible element to measure");
|
||||
return measured;
|
||||
}
|
||||
|
||||
async function size(locator: import("@playwright/test").Locator) {
|
||||
await settled(locator);
|
||||
const { width, height } = await box(locator);
|
||||
const { width, height } = await settled(locator);
|
||||
return { width, height };
|
||||
}
|
||||
|
||||
/**
|
||||
* Waits until an element stops moving.
|
||||
* Waits until an element is on screen and stops moving, and returns where it settled.
|
||||
*
|
||||
* The flyout scales in and the sidebar behind it re-lays out as the filter changes, so a rail
|
||||
* measured mid-animation is not a rail — and a measurement built from two `boundingBox()` calls
|
||||
* would take its two halves from two different frames.
|
||||
* would take its two halves from two different frames. A row that has not been laid out yet has
|
||||
* no box at all; that is not settled either, so the poll keeps waiting instead of failing.
|
||||
*/
|
||||
async function settled(locator: import("@playwright/test").Locator) {
|
||||
let previous = "";
|
||||
const last: { box: Awaited<ReturnType<typeof locator.boundingBox>>; key: string | null } = {
|
||||
box: null,
|
||||
key: null,
|
||||
};
|
||||
await expect
|
||||
.poll(async () => {
|
||||
const current = JSON.stringify(await box(locator));
|
||||
const stable = current === previous;
|
||||
previous = current;
|
||||
const current = await locator.boundingBox();
|
||||
const key = current ? JSON.stringify(current) : null;
|
||||
const stable = key !== null && key === last.key;
|
||||
last.box = current;
|
||||
last.key = key;
|
||||
return stable;
|
||||
})
|
||||
.toBe(true);
|
||||
if (!last.box) throw new Error("a settled element has a box");
|
||||
return last.box;
|
||||
}
|
||||
|
||||
async function expectAssigned(
|
||||
|
||||
@@ -170,6 +170,11 @@ export interface ModelTriggerLabelState {
|
||||
modelShown: boolean;
|
||||
modelText: string;
|
||||
modelTruncated: boolean;
|
||||
/**
|
||||
* The model label shows what its box fits right now: the full text when it fits, otherwise a
|
||||
* truncation that fits. False while the control has yet to catch up with a reflow.
|
||||
*/
|
||||
modelFitsBox: boolean;
|
||||
}
|
||||
|
||||
declare global {
|
||||
@@ -194,12 +199,18 @@ function readModelTriggerLabelStateInPage(): ModelTriggerLabelState {
|
||||
};
|
||||
const modelShown = model !== undefined && shown(model);
|
||||
const modelText = model?.textContent ?? "";
|
||||
const overflows = (node: Element) => node.scrollWidth > node.clientWidth;
|
||||
const modelOverflows = model !== undefined && overflows(model);
|
||||
// The label's box is sized by an invisible copy of the full text, its first child, so the box
|
||||
// follows a reflow at once while the shown text waits for the control's next layout event.
|
||||
const fullTextSizer = model?.parentElement?.parentElement?.firstElementChild;
|
||||
const fullTextFits = fullTextSizer ? !overflows(fullTextSizer) : true;
|
||||
return {
|
||||
modelShown,
|
||||
modelText,
|
||||
thinkingShown: modelShown && thinking !== undefined,
|
||||
modelTruncated:
|
||||
model !== undefined && (modelText.endsWith("…") || model.scrollWidth > model.clientWidth),
|
||||
modelTruncated: modelText.endsWith("…") || modelOverflows,
|
||||
modelFitsBox: !modelOverflows && modelText.endsWith("…") !== fullTextFits,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -217,13 +228,26 @@ export async function recordModelTriggerFramesFromLoad(page: Page): Promise<void
|
||||
})()`);
|
||||
}
|
||||
|
||||
/** The model control's labels once two reads 100ms apart agree. */
|
||||
/**
|
||||
* The model control's labels once it has caught up with its width: two reads 100ms apart agree
|
||||
* and the model label shows what its box fits. A resize reflows the page at once, but the control
|
||||
* chooses its labels again only when its layout events arrive, and on a slow runner that takes
|
||||
* longer than 100ms. Until then the label can be clipped by the browser beside the thinking
|
||||
* label, or truncated in a box that has since widened.
|
||||
*/
|
||||
export async function readSettledModelTriggerLabels(page: Page): Promise<ModelTriggerLabelState> {
|
||||
const deadline = Date.now() + 10_000;
|
||||
let previous = await page.evaluate(readModelTriggerLabelStateInPage);
|
||||
for (;;) {
|
||||
await page.waitForTimeout(100);
|
||||
const next = await page.evaluate(readModelTriggerLabelStateInPage);
|
||||
if (JSON.stringify(next) === JSON.stringify(previous)) return next;
|
||||
const agrees = JSON.stringify(next) === JSON.stringify(previous);
|
||||
if (agrees && next.modelFitsBox) return next;
|
||||
if (Date.now() > deadline) {
|
||||
throw new Error(
|
||||
`the model control never settled on a label that fits its box: ${JSON.stringify(next)}`,
|
||||
);
|
||||
}
|
||||
previous = next;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@ import {
|
||||
type ChildProcess,
|
||||
type SpawnOptions,
|
||||
} from "node:child_process";
|
||||
import { mkdtemp, rm, writeFile } from "node:fs/promises";
|
||||
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
||||
import net from "node:net";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
@@ -59,7 +59,17 @@ export async function getAvailableHostDaemonPort(): Promise<number> {
|
||||
return port;
|
||||
}
|
||||
|
||||
async function waitForServer(port: number, child: ChildProcess): Promise<void> {
|
||||
/**
|
||||
* Resolves once this daemon answers on its port. An open TCP port is not
|
||||
* enough: the port is released before the daemon binds it, and whatever takes
|
||||
* it in between also accepts connections while the daemon exits with
|
||||
* EADDRINUSE. Only the daemon's own status reports its server id.
|
||||
*/
|
||||
async function waitForServer(
|
||||
port: number,
|
||||
child: ChildProcess,
|
||||
identity: { serverId: string; paseoHome: string },
|
||||
): Promise<void> {
|
||||
const deadline = Date.now() + 90_000;
|
||||
let lastError: unknown = null;
|
||||
|
||||
@@ -70,22 +80,13 @@ async function waitForServer(port: number, child: ChildProcess): Promise<void> {
|
||||
);
|
||||
}
|
||||
try {
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
const socket = net.connect(port, "127.0.0.1", () => {
|
||||
socket.end();
|
||||
resolve();
|
||||
});
|
||||
socket.setTimeout(1_000, () => {
|
||||
socket.destroy();
|
||||
reject(new Error(`Connection timed out to isolated daemon port ${port}`));
|
||||
});
|
||||
socket.on("error", reject);
|
||||
});
|
||||
return;
|
||||
const serverId = await readServerId(port, identity.paseoHome);
|
||||
if (serverId === identity.serverId) return;
|
||||
lastError = new Error(`Port ${port} is served by ${serverId}, not ${identity.serverId}`);
|
||||
} catch (error) {
|
||||
lastError = error;
|
||||
await new Promise((resolve) => setTimeout(resolve, 100));
|
||||
}
|
||||
await new Promise((resolve) => setTimeout(resolve, 100));
|
||||
}
|
||||
|
||||
throw new Error(
|
||||
@@ -95,6 +96,25 @@ async function waitForServer(port: number, child: ChildProcess): Promise<void> {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the server id from the daemon's status route. The route needs a bearer
|
||||
* on a password-protected daemon; the daemon accepts the local credential it
|
||||
* writes into its home before listening, as the CLI does for local status.
|
||||
*/
|
||||
async function readServerId(port: number, paseoHome: string): Promise<string> {
|
||||
const localCredential = await readFile(path.join(paseoHome, "local-credential"), "utf8").then(
|
||||
(token) => token.trim(),
|
||||
() => null,
|
||||
);
|
||||
const response = await fetch(`http://127.0.0.1:${port}/api/status`, {
|
||||
headers: localCredential ? { authorization: `Bearer ${localCredential}` } : {},
|
||||
signal: AbortSignal.timeout(1_000),
|
||||
});
|
||||
if (!response.ok) throw new Error(`Status request to port ${port} returned ${response.status}`);
|
||||
const status = (await response.json()) as { serverId?: unknown };
|
||||
return String(status.serverId);
|
||||
}
|
||||
|
||||
function withMutableRelay(
|
||||
config: NonNullable<IsolatedHostDaemonOptions["config"]>,
|
||||
relay: NonNullable<IsolatedHostDaemonOptions["mutableRelay"]>,
|
||||
@@ -121,7 +141,7 @@ export async function startIsolatedHostDaemon(
|
||||
serverId: string,
|
||||
options: IsolatedHostDaemonOptions = {},
|
||||
): Promise<IsolatedHostDaemon> {
|
||||
const port = await getAvailableHostDaemonPort();
|
||||
let 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");
|
||||
@@ -221,7 +241,7 @@ export async function startIsolatedHostDaemon(
|
||||
});
|
||||
|
||||
try {
|
||||
await waitForServer(port, spawned);
|
||||
await waitForServer(port, spawned, { serverId, paseoHome });
|
||||
return spawned;
|
||||
} catch (error) {
|
||||
throw new Error(
|
||||
@@ -231,8 +251,25 @@ 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 spawnDaemon();
|
||||
await startOnFreePort();
|
||||
} catch (error) {
|
||||
await stopDaemon();
|
||||
if (!options.preserveHome) {
|
||||
|
||||
@@ -198,6 +198,14 @@ async function expectDetails(page: Page) {
|
||||
await expect(page.getByText("All systems operational", { exact: true })).toBeInViewport();
|
||||
}
|
||||
|
||||
// The details render before the daemon answers their event subscription, and reopened
|
||||
// details show the cached summary at once, so wait for the subscription id to arrive.
|
||||
async function readContentObservation(page: Page): Promise<string> {
|
||||
const observation = page.getByLabel("Content observation", { exact: true });
|
||||
await expect(observation).not.toHaveText("");
|
||||
return (await observation.textContent())!;
|
||||
}
|
||||
|
||||
function workspaceMenuRow(page: Page, title: string): Locator {
|
||||
return compactWorkspaceMenu(page).getByRole("menuitem", { name: title, exact: true });
|
||||
}
|
||||
@@ -354,14 +362,12 @@ export async function withButtonShowcase(
|
||||
test.step("closing and crashing content release its owner while sibling buttons and app remain live", async () => {
|
||||
await press(page, "Header status");
|
||||
await expectDetails(page);
|
||||
const observation = page.getByLabel("Content observation", { exact: true });
|
||||
await expect(observation).not.toHaveText("");
|
||||
const first = (await observation.textContent())!;
|
||||
const first = await readContentObservation(page);
|
||||
await press(page, "Close deployment details");
|
||||
await expect.poll(() => released.has(first)).toBe(true);
|
||||
await press(page, "Composer status");
|
||||
await expectDetails(page);
|
||||
const second = (await observation.textContent())!;
|
||||
const second = await readContentObservation(page);
|
||||
expect(second).not.toBe(first);
|
||||
await workspace.client.renameProject(workspace.projectId, "Observer control");
|
||||
await expect(page.getByText("Observed updates: 1", { exact: true })).toBeVisible();
|
||||
@@ -373,7 +379,7 @@ export async function withButtonShowcase(
|
||||
await page.keyboard.press("Escape");
|
||||
await press(page, "Header status");
|
||||
await expectDetails(page);
|
||||
const recovered = (await observation.textContent())!;
|
||||
const recovered = await readContentObservation(page);
|
||||
expect([first, second]).not.toContain(recovered);
|
||||
await showcase.setTitle("Healthy app after button failure");
|
||||
await expect(page.getByTestId("workspace-header-title")).toHaveText(
|
||||
@@ -687,9 +693,7 @@ export async function withButtonShowcase(
|
||||
page,
|
||||
page.getByRole("button", { name: "Close deployment details", exact: true }),
|
||||
);
|
||||
const observation = page.getByLabel("Content observation", { exact: true });
|
||||
await expect(observation).not.toHaveText("");
|
||||
const owner = (await observation.textContent())!;
|
||||
const owner = await readContentObservation(page);
|
||||
await showcase.disable();
|
||||
await expect.poll(() => released.has(owner)).toBe(true);
|
||||
await expect(
|
||||
|
||||
@@ -15,8 +15,18 @@ export const COMPACT = { width: 390, height: 844 };
|
||||
/** A plugin written against the current API: a screen, header and footer items, a command. */
|
||||
const SHOWCASE_SOURCE = `import React from "react";
|
||||
import { Pressable, Text, View } from "react-native";
|
||||
import { useWorkspaces } from "@getpaseo/plugin/client";
|
||||
import { SidebarRow } from "@getpaseo/plugin/client/ui";
|
||||
|
||||
function WorkspacesScreen({ theme }) {
|
||||
const workspaces = useWorkspaces();
|
||||
return (
|
||||
<View style={{ flex: 1, padding: 24, gap: 8 }}>
|
||||
{workspaces.map((ref) => <Text key={ref.id} style={{ color: theme.colors.foreground }}>{"Workspace " + ref.id}</Text>)}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function DeploysScreen({ theme }) {
|
||||
return <View style={{ flex: 1, padding: 24 }}><Text style={{ color: theme.colors.foreground }}>Deploys screen body</Text></View>;
|
||||
}
|
||||
@@ -63,11 +73,13 @@ function Broken() {
|
||||
|
||||
export default function contribute(client) {
|
||||
client.addScreen({ id: "deploys", title: "Deploys", Component: DeploysScreen });
|
||||
client.addScreen({ id: "workspaces", title: "Workspaces", Component: WorkspacesScreen });
|
||||
client.addSidebarHeaderItem({ id: "deploys", title: "Deploys", Component: DeploysItem });
|
||||
client.addSidebarHeaderItem({ id: "broken", title: "Broken header", Component: Broken });
|
||||
client.addSidebarFooterItem({ id: "sync", title: "Sync", Component: SyncItem });
|
||||
client.addSidebarFooterItem({ id: "broken", title: "Broken footer", Component: Broken });
|
||||
client.addCommandCenterItem({ id: "open-deploys", title: "Open deploys", icon: "Rocket", context: "global", onSelect: (ctx) => ctx.openScreen({ screenId: "deploys" }) });
|
||||
client.addCommandCenterItem({ id: "open-workspaces", title: "Open plugin workspaces", icon: "List", context: "global", onSelect: (ctx) => ctx.openScreen({ screenId: "workspaces" }) });
|
||||
return () => {};
|
||||
}
|
||||
`;
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
/android/.cxx/
|
||||
/android/build/
|
||||
@@ -0,0 +1,23 @@
|
||||
apply plugin: 'com.android.library'
|
||||
|
||||
group = 'sh.paseo.displaymetrics'
|
||||
version = '0.1.0'
|
||||
|
||||
def expoModulesCorePlugin = new File(project(":expo-modules-core").projectDir.absolutePath, "ExpoModulesCorePlugin.gradle")
|
||||
apply from: expoModulesCorePlugin
|
||||
applyKotlinExpoModulesCorePlugin()
|
||||
useCoreDependencies()
|
||||
useDefaultAndroidSdkVersions()
|
||||
|
||||
android {
|
||||
namespace "sh.paseo.displaymetrics"
|
||||
defaultConfig {
|
||||
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
|
||||
}
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation "com.facebook.react:react-android"
|
||||
androidTestImplementation 'androidx.test:runner:1.6.2'
|
||||
androidTestImplementation 'androidx.test.ext:junit:1.2.1'
|
||||
}
|
||||
+86
@@ -0,0 +1,86 @@
|
||||
package sh.paseo.displaymetrics
|
||||
|
||||
import android.util.DisplayMetrics
|
||||
import android.util.TypedValue
|
||||
import androidx.test.ext.junit.runners.AndroidJUnit4
|
||||
import androidx.test.platform.app.InstrumentationRegistry
|
||||
import com.facebook.react.uimanager.DisplayMetricsHolder
|
||||
import com.facebook.react.uimanager.PixelUtil
|
||||
import org.junit.After
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertSame
|
||||
import org.junit.Assert.assertThrows
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
|
||||
@RunWith(AndroidJUnit4::class)
|
||||
class PaseoDisplayMetricsTest {
|
||||
private lateinit var display: DisplayMetrics
|
||||
|
||||
@Before
|
||||
fun readDisplayLikeReactNative() {
|
||||
DisplayMetricsHolder.initDisplayMetrics(InstrumentationRegistry.getInstrumentation().targetContext)
|
||||
display = DisplayMetricsHolder.getScreenDisplayMetrics()
|
||||
}
|
||||
|
||||
@After
|
||||
fun forgetDisplay() {
|
||||
DisplayMetricsHolder.setScreenDisplayMetrics(null)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun reservesRoomForTextAtTheWindowDensity() {
|
||||
// A DeX window at two thirds of the phone's density (240 dpi on a 360 dpi phone). React Native
|
||||
// reads the font scale from the window but the density from the phone's display.
|
||||
val window = windowAt(display.densityDpi * 2 / 3)
|
||||
DisplayMetricsHolder.setScreenDisplayMetrics(
|
||||
DisplayMetrics().apply {
|
||||
setTo(display)
|
||||
scaledDensity = window.scaledDensity
|
||||
},
|
||||
)
|
||||
assertTrue(reservedTextPx(window) < drawnTextPx())
|
||||
|
||||
PaseoDisplayMetrics.syncWithWindow(window)
|
||||
|
||||
assertEquals(drawnTextPx(), reservedTextPx(window), 0.01f)
|
||||
assertEquals(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 16f, window), drawnTextPx(), 0.01f)
|
||||
val synced = DisplayMetricsHolder.getScreenDisplayMetrics()
|
||||
assertEquals(window.densityDpi, synced.densityDpi)
|
||||
assertEquals(display.widthPixels, synced.widthPixels)
|
||||
assertEquals(display.heightPixels, synced.heightPixels)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun leavesTheBuiltInDisplayAlone() {
|
||||
PaseoDisplayMetrics.syncWithWindow(windowAt(display.densityDpi))
|
||||
|
||||
assertSame(display, DisplayMetricsHolder.getScreenDisplayMetrics())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun waitsForReactNativeToReadTheDisplay() {
|
||||
DisplayMetricsHolder.setScreenDisplayMetrics(null)
|
||||
|
||||
PaseoDisplayMetrics.syncWithWindow(windowAt(display.densityDpi / 2))
|
||||
|
||||
assertThrows(IllegalStateException::class.java) { DisplayMetricsHolder.getScreenDisplayMetrics() }
|
||||
}
|
||||
|
||||
private fun windowAt(densityDpi: Int): DisplayMetrics =
|
||||
DisplayMetrics().apply {
|
||||
setTo(display)
|
||||
this.densityDpi = densityDpi
|
||||
density = densityDpi.toFloat() / DisplayMetrics.DENSITY_DEFAULT
|
||||
scaledDensity = density * display.scaledDensity / display.density
|
||||
}
|
||||
|
||||
/** A 16sp font as React Native draws it, in pixels. */
|
||||
private fun drawnTextPx(): Float = PixelUtil.toPixelFromSP(16f)
|
||||
|
||||
/** The box React Native lays out for that font, once the window renders it in pixels. */
|
||||
private fun reservedTextPx(window: DisplayMetrics): Float =
|
||||
PixelUtil.toDIPFromPixel(drawnTextPx()) * window.density
|
||||
}
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
package sh.paseo.displaymetrics
|
||||
|
||||
import android.app.Activity
|
||||
import android.util.DisplayMetrics
|
||||
import com.facebook.react.uimanager.DisplayMetricsHolder
|
||||
|
||||
/**
|
||||
* React Native 0.86 converts between px and dp, and so sizes text, with the density of the
|
||||
* device's built-in display, because `DisplayMetricsHolder` reads `Display.getRealMetrics()`.
|
||||
* Fabric lays out at the window's density. On a display with another density, such as a Samsung
|
||||
* DeX monitor, text boxes come out too small and clip their text.
|
||||
*
|
||||
* Backports react/react-native#59087 (`useWindowDensityForDisplayMetricsAndroid`): keep the
|
||||
* window's density and take only the size from the display. Remove once the app runs React Native
|
||||
* 0.89 or later with that flag on.
|
||||
*/
|
||||
object PaseoDisplayMetrics {
|
||||
/** Call right after React Native reads the display, which it does again on each configuration change. */
|
||||
@JvmStatic
|
||||
fun syncWithWindow(activity: Activity) {
|
||||
syncWithWindow(activity.resources.displayMetrics)
|
||||
}
|
||||
|
||||
@JvmStatic
|
||||
fun syncWithWindow(window: DisplayMetrics) {
|
||||
val screen =
|
||||
try {
|
||||
DisplayMetricsHolder.getScreenDisplayMetrics()
|
||||
} catch (_: IllegalStateException) {
|
||||
// React Native hasn't read the display yet, so there is nothing to correct.
|
||||
return
|
||||
}
|
||||
if (screen.densityDpi == window.densityDpi) return
|
||||
|
||||
DisplayMetricsHolder.setScreenDisplayMetrics(
|
||||
DisplayMetrics().apply {
|
||||
setTo(screen)
|
||||
density = window.density
|
||||
densityDpi = window.densityDpi
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
const { withMainActivity } = require("expo/config-plugins");
|
||||
|
||||
const ACTIVITY_CLASS = "class MainActivity : ReactActivity() {";
|
||||
const SYNC = "sh.paseo.displaymetrics.PaseoDisplayMetrics.syncWithWindow(this)";
|
||||
// React Native re-reads the built-in display's density when it creates the root view and on every
|
||||
// configuration change, so the window's density has to be restored right after each `super` call.
|
||||
const OVERRIDES = `
|
||||
override fun onContentChanged() {
|
||||
super.onContentChanged()
|
||||
${SYNC}
|
||||
}
|
||||
|
||||
override fun onConfigurationChanged(newConfig: android.content.res.Configuration) {
|
||||
super.onConfigurationChanged(newConfig)
|
||||
${SYNC}
|
||||
}
|
||||
`;
|
||||
|
||||
function configureDisplayMetricsActivity(contents) {
|
||||
if (contents.includes(SYNC)) return contents;
|
||||
if (
|
||||
!contents.includes(ACTIVITY_CLASS) ||
|
||||
/override fun on(ContentChanged|ConfigurationChanged)\(/.test(contents)
|
||||
) {
|
||||
throw new Error("Could not keep React Native text at the window's density in MainActivity");
|
||||
}
|
||||
return contents.replace(ACTIVITY_CLASS, `${ACTIVITY_CLASS}${OVERRIDES}`);
|
||||
}
|
||||
|
||||
module.exports = (config) =>
|
||||
withMainActivity(config, (mod) => {
|
||||
mod.modResults.contents = configureDisplayMetricsActivity(mod.modResults.contents);
|
||||
return mod;
|
||||
});
|
||||
module.exports.configureDisplayMetricsActivity = configureDisplayMetricsActivity;
|
||||
@@ -0,0 +1,29 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
const { configureDisplayMetricsActivity } = require("./app.plugin");
|
||||
|
||||
const SYNC = "sh.paseo.displaymetrics.PaseoDisplayMetrics.syncWithWindow(this)";
|
||||
|
||||
describe("Android display metrics", () => {
|
||||
it("restores the window's density after React Native reads the display", () => {
|
||||
const source = "class MainActivity : ReactActivity() {\n}";
|
||||
const result = configureDisplayMetricsActivity(source);
|
||||
expect(result).toContain(`super.onContentChanged()\n ${SYNC}`);
|
||||
expect(result).toContain(`super.onConfigurationChanged(newConfig)\n ${SYNC}`);
|
||||
expect(configureDisplayMetricsActivity(result)).toBe(result);
|
||||
});
|
||||
|
||||
it("fails prebuild when the template no longer has a place for the overrides", () => {
|
||||
expect(() => configureDisplayMetricsActivity("changed template")).toThrow(
|
||||
"Could not keep React Native text at the window's density",
|
||||
);
|
||||
});
|
||||
|
||||
it("fails prebuild rather than replace another plugin's configuration handler", () => {
|
||||
const source =
|
||||
"class MainActivity : ReactActivity() {\n override fun onConfigurationChanged(newConfig: Configuration) {}\n}";
|
||||
expect(() => configureDisplayMetricsActivity(source)).toThrow(
|
||||
"Could not keep React Native text at the window's density",
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"platforms": ["android"],
|
||||
"android": {
|
||||
"modules": []
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"name": "paseo-display-metrics",
|
||||
"version": "0.1.0",
|
||||
"private": true
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@getpaseo/app",
|
||||
"version": "0.16.2",
|
||||
"version": "0.16.1",
|
||||
"private": true,
|
||||
"main": "index.ts",
|
||||
"scripts": {
|
||||
|
||||
@@ -17,6 +17,13 @@ import { isNative } from "@/constants/platform";
|
||||
* On macOS, Electron handles edge resize natively.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Marks a scroll viewport as window content: it and its descendants emit no window
|
||||
* regions, because Electron does not clip app-region rects to scroll viewports.
|
||||
* See the `[data-window-content]` rule in public/index.html.
|
||||
*/
|
||||
export const WINDOW_CONTENT_DATASET = { "window-content": "" };
|
||||
|
||||
export const titlebarDragSurfaceStyle: React.CSSProperties = {
|
||||
cursor: "default",
|
||||
// @ts-expect-error — WebkitAppRegion is not in CSSProperties
|
||||
|
||||
@@ -9,7 +9,16 @@ import {
|
||||
type LucideIcon,
|
||||
} from "lucide-react-native";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { memo, useCallback, useEffect, useMemo, useRef, useState, type RefObject } from "react";
|
||||
import {
|
||||
memo,
|
||||
useCallback,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
type ReactNode,
|
||||
type RefObject,
|
||||
} from "react";
|
||||
import {
|
||||
Pressable,
|
||||
ScrollView,
|
||||
@@ -19,12 +28,19 @@ import {
|
||||
View,
|
||||
type LayoutChangeEvent,
|
||||
} from "react-native";
|
||||
import { Gesture, ScrollView as GHScrollView } from "react-native-gesture-handler";
|
||||
import {
|
||||
Gesture,
|
||||
type GestureType,
|
||||
ScrollView as GHScrollView,
|
||||
} from "react-native-gesture-handler";
|
||||
import Animated, { runOnJS, useAnimatedStyle, useSharedValue } from "react-native-reanimated";
|
||||
import { scheduleOnRN } from "react-native-worklets";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
import { StyleSheet, useUnistyles } from "react-native-unistyles";
|
||||
import { TitlebarDragRegion } from "@/components/desktop/titlebar-drag-region";
|
||||
import {
|
||||
TitlebarDragRegion,
|
||||
WINDOW_CONTENT_DATASET,
|
||||
} from "@/components/desktop/titlebar-drag-region";
|
||||
import { SidebarCloseButton } from "@/components/headers/sidebar-close-button";
|
||||
import {
|
||||
resolveDesktopSidebarInsetLeft,
|
||||
@@ -39,7 +55,7 @@ import { HostPicker } from "@/components/hosts/host-picker";
|
||||
import { SidebarDisplayPreferencesMenu } from "@/components/sidebar/display-preferences/menu";
|
||||
import { SidebarSeparator } from "@/components/sidebar/sidebar-separator";
|
||||
import { SidebarToastRegion } from "@/components/sidebar/sidebar-toast-region";
|
||||
import { SidebarNavRows } from "@/components/sidebar/sidebar-nav-rows";
|
||||
import { SidebarNavRows, useVisibleSidebarNavItems } from "@/components/sidebar/sidebar-nav-rows";
|
||||
import { SidebarFooterIconHighlight } from "@/components/sidebar/sidebar-footer-icon-highlight";
|
||||
import { SidebarHelpMenu } from "@/components/sidebar/sidebar-help-menu";
|
||||
import { SidebarFooterOverflowMenu } from "@/components/sidebar/sidebar-footer-overflow-menu";
|
||||
@@ -622,29 +638,7 @@ function MobileSidebar({
|
||||
>
|
||||
<View style={styles.sidebarContent} pointerEvents="auto">
|
||||
<WindowChromeSafeArea placement="below" />
|
||||
{platformIsNative ? (
|
||||
<GHScrollView
|
||||
// Same contract as the workspace list: vertical drags scroll the nav
|
||||
// block, a clear horizontal intent still activates the close pan.
|
||||
simultaneousHandlers={closeGestureRef}
|
||||
style={styles.mobileNavScroll}
|
||||
showsVerticalScrollIndicator={false}
|
||||
alwaysBounceVertical={false}
|
||||
testID="sidebar-nav-scroll"
|
||||
>
|
||||
{navRows}
|
||||
</GHScrollView>
|
||||
) : (
|
||||
<ScrollView
|
||||
style={styles.mobileNavScroll}
|
||||
showsVerticalScrollIndicator={false}
|
||||
alwaysBounceVertical={false}
|
||||
testID="sidebar-nav-scroll"
|
||||
>
|
||||
{navRows}
|
||||
</ScrollView>
|
||||
)}
|
||||
<SidebarSeparator />
|
||||
<SidebarNavScroll closeGestureRef={closeGestureRef}>{navRows}</SidebarNavScroll>
|
||||
|
||||
<SidebarViewSlot dismiss={handleWorkspacePress}>
|
||||
<SidebarToastRegion active={active}>
|
||||
@@ -689,6 +683,47 @@ function MobileSidebar({
|
||||
);
|
||||
}
|
||||
|
||||
interface SidebarNavScrollProps {
|
||||
closeGestureRef: RefObject<GestureType | undefined>;
|
||||
/** Web only: the viewport emits no window regions (see WINDOW_CONTENT_DATASET). */
|
||||
windowContent?: boolean;
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
// The capped, scrolling nav block shared by the mobile and desktop sidebars, with the
|
||||
// divider below it. The divider is a sibling because Unistyles does not patch the
|
||||
// gesture-handler ScrollView.
|
||||
function SidebarNavScroll({ closeGestureRef, windowContent, children }: SidebarNavScrollProps) {
|
||||
return (
|
||||
<>
|
||||
{platformIsNative ? (
|
||||
<GHScrollView
|
||||
// Same contract as the workspace list: vertical drags scroll the nav
|
||||
// block, a clear horizontal intent still activates the close pan.
|
||||
simultaneousHandlers={closeGestureRef}
|
||||
style={styles.navScroll}
|
||||
showsVerticalScrollIndicator={false}
|
||||
alwaysBounceVertical={false}
|
||||
testID="sidebar-nav-scroll"
|
||||
>
|
||||
{children}
|
||||
</GHScrollView>
|
||||
) : (
|
||||
<ScrollView
|
||||
dataSet={windowContent ? WINDOW_CONTENT_DATASET : undefined}
|
||||
style={styles.navScroll}
|
||||
showsVerticalScrollIndicator={false}
|
||||
alwaysBounceVertical={false}
|
||||
testID="sidebar-nav-scroll"
|
||||
>
|
||||
{children}
|
||||
</ScrollView>
|
||||
)}
|
||||
<SidebarSeparator testID="sidebar-nav-separator" />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function DesktopSidebar({
|
||||
theme,
|
||||
workspaceGroups,
|
||||
@@ -809,12 +844,14 @@ function DesktopSidebar({
|
||||
],
|
||||
[insetsTop, insets.bottom, insets.left, overlay, divisionLayout],
|
||||
);
|
||||
// Below the window controls' row, or in the top band's place, the first row starts flush.
|
||||
const inTopBand = useTopBand() !== null;
|
||||
const sidebarHeaderGroupStyle = useMemo(
|
||||
() => [styles.sidebarHeaderGroup, (ownsTopLeft || inTopBand) && styles.sidebarHeaderGroupFlush],
|
||||
[ownsTopLeft, inTopBand],
|
||||
);
|
||||
// Windows and Linux draw their window controls top-right, so the sidebar has no chrome
|
||||
// row there. The strip above the scrolling rows is then its window drag surface.
|
||||
const showsChromeRow = ownsTopLeft || Boolean(DEV_BUILD_LABEL);
|
||||
// With every top item hidden the sidebar starts at the Workspaces section, as before the
|
||||
// nav scroller existed: no strip above it and no divider below it.
|
||||
const hasNavRows = useVisibleSidebarNavItems().length > 0;
|
||||
const showsDragStrip = hasNavRows && !showsChromeRow && !inTopBand;
|
||||
return (
|
||||
<MobilePanelOverlay
|
||||
panel="agent-list"
|
||||
@@ -825,7 +862,7 @@ function DesktopSidebar({
|
||||
<Animated.View style={desktopSidebarStyle}>
|
||||
<View style={desktopSidebarBorderStyle}>
|
||||
<View style={styles.sidebarDragArea}>
|
||||
{ownsTopLeft || DEV_BUILD_LABEL ? (
|
||||
{showsChromeRow ? (
|
||||
<View style={styles.desktopChromeRow}>
|
||||
<TitlebarDragRegion />
|
||||
{DEV_BUILD_LABEL ? (
|
||||
@@ -842,11 +879,21 @@ function DesktopSidebar({
|
||||
</View>
|
||||
) : null}
|
||||
</View>
|
||||
) : (
|
||||
<TitlebarDragRegion />
|
||||
)}
|
||||
<SidebarNavRows style={sidebarHeaderGroupStyle} onBeforeNavigate={closeSidebar} />
|
||||
) : null}
|
||||
{showsDragStrip ? (
|
||||
<View style={styles.desktopDragStrip} testID="sidebar-nav-drag-strip">
|
||||
<TitlebarDragRegion />
|
||||
</View>
|
||||
) : null}
|
||||
</View>
|
||||
{/* The drag overlay stays above this viewport: Electron does not clip
|
||||
app-region rects to scroll viewports, so a scrolled-out row would
|
||||
still claim its no-drag rect. */}
|
||||
{hasNavRows ? (
|
||||
<SidebarNavScroll closeGestureRef={closeGestureRef} windowContent>
|
||||
<SidebarNavRows style={styles.sidebarHeaderGroup} onBeforeNavigate={closeSidebar} />
|
||||
</SidebarNavScroll>
|
||||
) : null}
|
||||
|
||||
<SidebarViewSlot dismiss={closeSidebar}>
|
||||
<SidebarToastRegion active={active}>
|
||||
@@ -935,19 +982,18 @@ const staticStyles = RNStyleSheet.create({
|
||||
});
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
// The rows start flush: the chrome row, drag strip, or top band above them gives the inset.
|
||||
sidebarHeaderGroup: {
|
||||
paddingTop: theme.spacing[2],
|
||||
gap: 2,
|
||||
paddingBottom: theme.spacing[1.5],
|
||||
borderBottomWidth: 1,
|
||||
borderBottomColor: theme.colors.border,
|
||||
},
|
||||
sidebarHeaderGroupFlush: {
|
||||
paddingTop: 0,
|
||||
desktopDragStrip: {
|
||||
position: "relative",
|
||||
height: theme.spacing[2],
|
||||
},
|
||||
// The nav block caps at half the sidebar; a long item list scrolls inside the
|
||||
// cap instead of crowding the workspace list off a short screen.
|
||||
mobileNavScroll: {
|
||||
navScroll: {
|
||||
flexGrow: 0,
|
||||
flexShrink: 1,
|
||||
maxHeight: "50%",
|
||||
|
||||
@@ -35,14 +35,19 @@ interface SidebarNavRowsProps extends SidebarNavRowProps {
|
||||
firstRowTrailing?: ReactNode;
|
||||
}
|
||||
|
||||
/** The top-level items the user keeps visible, in display order. */
|
||||
export function useVisibleSidebarNavItems() {
|
||||
const { items } = useSidebarNavItems("header");
|
||||
return useMemo(() => items.filter((item) => item.visible), [items]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Top-level sidebar navigation, ordered and filtered by the user's
|
||||
* `sidebarNavItems` preference. Renders nothing — not even the bordered group
|
||||
* wrapper — when every item is hidden and there is no `firstRowTrailing`.
|
||||
*/
|
||||
export function SidebarNavRows({ style, onBeforeNavigate, firstRowTrailing }: SidebarNavRowsProps) {
|
||||
const { items } = useSidebarNavItems("header");
|
||||
const visibleItems = useMemo(() => items.filter((item) => item.visible), [items]);
|
||||
const visibleItems = useVisibleSidebarNavItems();
|
||||
const groupRef = useRef<View | null>(null);
|
||||
|
||||
if (visibleItems.length === 0 && !firstRowTrailing) return null;
|
||||
|
||||
@@ -1,7 +1,4 @@
|
||||
import { PluginClientStateProvider } from "@getpaseo/plugin/client/host";
|
||||
import type { PluginFilePanelProps } from "@getpaseo/plugin/client";
|
||||
import { useMemo } from "react";
|
||||
import { createPluginClientStateSource } from "@/plugins/client-state/source";
|
||||
import { PluginInstallationProvider } from "@/plugins/installation-provider";
|
||||
import { SurfaceErrorBoundary } from "@/plugins/surface-error-boundary";
|
||||
import type { PluginFilePanel } from "./panels";
|
||||
@@ -11,17 +8,11 @@ export function PluginFilePanelHost({
|
||||
...props
|
||||
}: PluginFilePanelProps & { panel: PluginFilePanel }) {
|
||||
const { plugin, contribution } = panel;
|
||||
const stateSource = useMemo(
|
||||
() => createPluginClientStateSource(plugin.serverId),
|
||||
[plugin.serverId],
|
||||
);
|
||||
const Component = contribution.Component;
|
||||
return (
|
||||
<SurfaceErrorBoundary installation={plugin} Surface={Component} key={panel.id}>
|
||||
<PluginInstallationProvider plugin={plugin}>
|
||||
<PluginClientStateProvider source={stateSource}>
|
||||
<Component {...props} />
|
||||
</PluginClientStateProvider>
|
||||
<Component {...props} />
|
||||
</PluginInstallationProvider>
|
||||
</SurfaceErrorBoundary>
|
||||
);
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { PluginTranslationRuntime } from "@getpaseo/plugin/client/host";
|
||||
import { usePaseo, useRpc } from "@getpaseo/plugin/client";
|
||||
import { usePaseo, useRpc, useWorkspace, useWorkspaces } from "@getpaseo/plugin/client";
|
||||
import { defineRpc } from "@getpaseo/plugin";
|
||||
import { createPaseoApi, type PaseoApi } from "@getpaseo/client";
|
||||
import { DaemonClient } from "@getpaseo/client/internal/daemon-client";
|
||||
@@ -8,7 +8,11 @@ import React from "react";
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
import { expect, it } from "vitest";
|
||||
import { z } from "zod";
|
||||
import type { PluginWorkspaceSnapshot } from "@getpaseo/plugin";
|
||||
import type { PluginClientStateSource } from "@getpaseo/plugin/client/host";
|
||||
import type { ToastApi } from "@/components/toast-host";
|
||||
import { PluginInstallationProvider } from "./installation-provider";
|
||||
import { PluginEnvironmentProvider } from "./popover";
|
||||
import type { InstalledPlugin } from "./types";
|
||||
|
||||
const status = defineRpc({
|
||||
@@ -89,3 +93,53 @@ it("gives every surface the installation's client and RPCs on its first frame",
|
||||
plugin.lifetime.abort();
|
||||
await plugin.paseo.dispose();
|
||||
});
|
||||
|
||||
it("lets every surface read state through the plugin state hooks", async () => {
|
||||
const plugin = installation([]);
|
||||
function Surface() {
|
||||
return <span>{useWorkspaces().length} workspaces</span>;
|
||||
}
|
||||
|
||||
const markup = renderToStaticMarkup(
|
||||
<PluginInstallationProvider plugin={plugin}>
|
||||
<Surface />
|
||||
</PluginInstallationProvider>,
|
||||
);
|
||||
|
||||
expect(markup).toBe("<span>0 workspaces</span>");
|
||||
plugin.lifetime.abort();
|
||||
await plugin.paseo.dispose();
|
||||
});
|
||||
|
||||
function pluginEnvironment(plugin: InstalledPlugin, state: PluginClientStateSource) {
|
||||
return { installation: plugin, state, toast: {} as ToastApi };
|
||||
}
|
||||
|
||||
it("lets a surface read the state source its host passes", async () => {
|
||||
const plugin = installation([]);
|
||||
// A sidebar view spans every connected host, so its source is not the installation's host.
|
||||
const workspace = { id: "ws-on-another-host" } as PluginWorkspaceSnapshot;
|
||||
const state: PluginClientStateSource = {
|
||||
subscribe: () => () => undefined,
|
||||
getWorkspace: () => workspace,
|
||||
getAgent: () => null,
|
||||
getProject: () => null,
|
||||
getTerminal: () => null,
|
||||
getSnapshot: () => ({ workspaces: [], agents: [], projects: [], terminals: [] }),
|
||||
};
|
||||
function Surface() {
|
||||
return <span>{useWorkspace("ws-on-another-host")?.id}</span>;
|
||||
}
|
||||
|
||||
const environment = pluginEnvironment(plugin, state);
|
||||
|
||||
const markup = renderToStaticMarkup(
|
||||
<PluginEnvironmentProvider environment={environment}>
|
||||
<Surface />
|
||||
</PluginEnvironmentProvider>,
|
||||
);
|
||||
|
||||
expect(markup).toBe("<span>ws-on-another-host</span>");
|
||||
plugin.lifetime.abort();
|
||||
await plugin.paseo.dispose();
|
||||
});
|
||||
|
||||
@@ -2,29 +2,42 @@ import { getPluginClientApi } from "./client-state/api";
|
||||
import { QueryClientProvider } from "@tanstack/react-query";
|
||||
import {
|
||||
PaseoApiProvider,
|
||||
PluginClientStateProvider,
|
||||
PluginComposersProvider,
|
||||
PluginRpcProvider,
|
||||
PluginTranslationProvider,
|
||||
type PluginClientStateSource,
|
||||
} from "@getpaseo/plugin/client/host";
|
||||
import React, { type ReactNode } from "react";
|
||||
import React, { useMemo, type ReactNode } from "react";
|
||||
import { createPluginClientStateSource } from "./client-state/source";
|
||||
import { pluginComposersSource } from "./composer-items/source";
|
||||
import type { InstalledPlugin } from "./types";
|
||||
|
||||
/** Every plugin surface renders under its installation: one query cache, one Paseo client, RPCs. */
|
||||
/**
|
||||
* Every plugin surface renders under its installation: one query cache, one Paseo client, RPCs,
|
||||
* and the state the plugin state hooks read. That state is scoped to the installation's host
|
||||
* unless the surface passes its own, as a sidebar view does to span every connected host.
|
||||
*/
|
||||
export function PluginInstallationProvider({
|
||||
plugin,
|
||||
state: surfaceState,
|
||||
children,
|
||||
}: {
|
||||
plugin: InstalledPlugin;
|
||||
state?: PluginClientStateSource;
|
||||
children: ReactNode;
|
||||
}) {
|
||||
const state = useMemo(
|
||||
() => surfaceState ?? createPluginClientStateSource(plugin.serverId),
|
||||
[plugin.serverId, surfaceState],
|
||||
);
|
||||
return (
|
||||
<QueryClientProvider client={plugin.queryClient}>
|
||||
<PaseoApiProvider paseo={getPluginClientApi(plugin).paseo}>
|
||||
<PluginRpcProvider invoke={plugin.invoke} subscribe={plugin.subscribe}>
|
||||
<PluginTranslationProvider runtime={plugin.i18n}>
|
||||
<PluginComposersProvider source={pluginComposersSource(plugin)}>
|
||||
{children}
|
||||
<PluginClientStateProvider source={state}>{children}</PluginClientStateProvider>
|
||||
</PluginComposersProvider>
|
||||
</PluginTranslationProvider>
|
||||
</PluginRpcProvider>
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { PluginClientStateProvider } from "@getpaseo/plugin/client/host";
|
||||
import type { ReactNode } from "react";
|
||||
import { View } from "react-native";
|
||||
import { StyleSheet } from "react-native-unistyles";
|
||||
@@ -30,8 +29,8 @@ export function PluginEnvironmentProvider({
|
||||
}: PluginEnvironmentProviderProps) {
|
||||
return (
|
||||
<ToastApiProvider api={environment.toast}>
|
||||
<PluginInstallationProvider plugin={environment.installation}>
|
||||
<PluginClientStateProvider source={environment.state}>{children}</PluginClientStateProvider>
|
||||
<PluginInstallationProvider plugin={environment.installation} state={environment.state}>
|
||||
{children}
|
||||
</PluginInstallationProvider>
|
||||
</ToastApiProvider>
|
||||
);
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { PluginClientStateProvider } from "@getpaseo/plugin/client/host";
|
||||
import type { PluginTimelineItemProps } from "@getpaseo/plugin/client";
|
||||
import type { PluginTheme } from "@getpaseo/plugin";
|
||||
import React, { type ComponentType, useMemo } from "react";
|
||||
@@ -8,7 +7,6 @@ import { useIsCompactFormFactor } from "@/constants/layout";
|
||||
import { useHostRuntimeClient, useHosts } from "@/runtime/host-runtime";
|
||||
import type { Theme } from "@/styles/theme";
|
||||
import type { PluginTimelineStreamItem } from "@/types/stream";
|
||||
import { createPluginClientStateSource } from "../client-state/source";
|
||||
import { useInstalledPlugin } from "../registry";
|
||||
import { PluginInstallationProvider } from "../installation-provider";
|
||||
import { SurfaceErrorBoundary } from "../surface-error-boundary";
|
||||
@@ -59,7 +57,6 @@ function PluginTimelineItemBody({
|
||||
const hostLabel = hosts.find((host) => host.serverId === serverId)?.label ?? serverId;
|
||||
const host = useMemo(() => ({ id: serverId, label: hostLabel }), [hostLabel, serverId]);
|
||||
const layout = useMemo(() => ({ compact, platform: resolvePluginPlatform() }), [compact]);
|
||||
const stateSource = useMemo(() => createPluginClientStateSource(serverId), [serverId]);
|
||||
|
||||
if (!plugin || !renderer || !parsed || !client) {
|
||||
return <TimelineItemUnavailable />;
|
||||
@@ -82,9 +79,7 @@ function PluginTimelineItemBody({
|
||||
return (
|
||||
<SurfaceErrorBoundary installation={plugin} resetKey={item.data} Surface={Component}>
|
||||
<PluginInstallationProvider plugin={plugin}>
|
||||
<PluginClientStateProvider source={stateSource}>
|
||||
<Component {...props} />
|
||||
</PluginClientStateProvider>
|
||||
<Component {...props} />
|
||||
</PluginInstallationProvider>
|
||||
</SurfaceErrorBoundary>
|
||||
);
|
||||
|
||||
@@ -5,7 +5,6 @@ import type {
|
||||
PluginTab,
|
||||
} from "@getpaseo/plugin/client";
|
||||
import type { PluginTheme } from "@getpaseo/plugin";
|
||||
import { PluginClientStateProvider } from "@getpaseo/plugin/client/host";
|
||||
import { CircleAlert } from "lucide-react-native";
|
||||
import { useMemo, useState } from "react";
|
||||
import { Text, View } from "react-native";
|
||||
@@ -20,7 +19,6 @@ import { useWorkspaceExists } from "@/stores/session-store-hooks";
|
||||
import type { Theme } from "@/styles/theme";
|
||||
import { normalizeWorkspaceOpaqueId } from "@/utils/workspace-identity";
|
||||
import { usePluginHostNavigation } from "../host-navigation";
|
||||
import { createPluginClientStateSource } from "../client-state/source";
|
||||
import { toPluginTheme } from "../theme";
|
||||
import { pluginIconComponent } from "../icons";
|
||||
import { useInstalledPlugin } from "../registry";
|
||||
@@ -67,7 +65,6 @@ function PluginPanelBody({ theme }: { theme: PluginTheme }) {
|
||||
const hostLabel = hosts.find((host) => host.serverId === serverId)?.label ?? serverId;
|
||||
const host = useMemo(() => ({ id: serverId, label: hostLabel }), [hostLabel, serverId]);
|
||||
const layout = useMemo(() => ({ compact, platform: resolvePluginPlatform() }), [compact]);
|
||||
const stateSource = useMemo(() => createPluginClientStateSource(serverId), [serverId]);
|
||||
const navigation = usePluginHostNavigation(serverId);
|
||||
|
||||
if (!plugin || !contribution || !workspaceExists) {
|
||||
@@ -123,9 +120,7 @@ function PluginPanelBody({ theme }: { theme: PluginTheme }) {
|
||||
Surface={Surface}
|
||||
key={`${serverId}/${target.pluginId}/${target.panelId}/${target.context}`}
|
||||
>
|
||||
<PluginInstallationProvider plugin={plugin}>
|
||||
<PluginClientStateProvider source={stateSource}>{panel}</PluginClientStateProvider>
|
||||
</PluginInstallationProvider>
|
||||
<PluginInstallationProvider plugin={plugin}>{panel}</PluginInstallationProvider>
|
||||
</SurfaceErrorBoundary>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -2739,6 +2739,52 @@ describe("HostRuntimeStore", () => {
|
||||
session.clearSession(host.serverId);
|
||||
});
|
||||
|
||||
it("loads the directory for a consumer that sees a restored host before the registry finishes loading", async () => {
|
||||
const host = makeHost({
|
||||
connections: [{ id: "direct:lan:6767", type: "directTcp", endpoint: "lan:6767" }],
|
||||
});
|
||||
const fakeClient = new FakeDaemonClient();
|
||||
fakeClient.setConnectionState({ status: "connected" });
|
||||
const store = new HostRuntimeStore({
|
||||
storage: createMemoryHostRuntimeStorage({
|
||||
[REGISTRY_KEY]: JSON.stringify([host]),
|
||||
"@paseo:e2e": "1",
|
||||
}),
|
||||
deps: {
|
||||
createClient: () => fakeClient as unknown as DaemonClient,
|
||||
connectToDaemon: async ({ host: hostProfile }) => ({
|
||||
client: fakeClient as unknown as DaemonClient,
|
||||
serverId: hostProfile.serverId,
|
||||
hostname: hostProfile.label ?? null,
|
||||
}),
|
||||
getClientId: async () => "cid_test_runtime",
|
||||
},
|
||||
});
|
||||
|
||||
// A component renders on every tick while the registry loads, and acquires directory
|
||||
// demand for each host it reads, as the sidebar does on its first render.
|
||||
const registry = { loading: true };
|
||||
const boot = store.boot().finally(() => {
|
||||
registry.loading = false;
|
||||
});
|
||||
let releaseDemand: (() => void) | null = null;
|
||||
while (registry.loading && !releaseDemand) {
|
||||
if (store.getHosts().some((candidate) => candidate.serverId === host.serverId)) {
|
||||
releaseDemand = store.acquireDirectoryDemand(host.serverId);
|
||||
}
|
||||
await Promise.resolve();
|
||||
}
|
||||
await boot;
|
||||
expect(releaseDemand).not.toBeNull();
|
||||
|
||||
await waitForHostOnline(store, host.serverId);
|
||||
await vi.waitFor(() => expect(fakeClient.fetchAgentsCalls).toHaveLength(1));
|
||||
|
||||
releaseDemand?.();
|
||||
store.syncHosts([]);
|
||||
useSessionStore.getState().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));
|
||||
|
||||
@@ -2863,7 +2909,8 @@ describe("HostRuntimeStore", () => {
|
||||
await registryLoaded;
|
||||
|
||||
expect(store.isHostRegistryLoaded()).toBe(true);
|
||||
expect(hostListNotifications).toBe(2);
|
||||
// Publishing the restored hosts, the registry turning ready, and the registry loading.
|
||||
expect(hostListNotifications).toBe(3);
|
||||
} finally {
|
||||
if (previousOverride === undefined) {
|
||||
delete process.env.EXPO_PUBLIC_LOCAL_DAEMON;
|
||||
|
||||
@@ -1816,11 +1816,9 @@ export class HostRuntimeStore {
|
||||
shouldPersistHosts = true;
|
||||
}
|
||||
}
|
||||
this.hosts = profiles;
|
||||
this.replicaCache.setHosts(profiles.map((profile) => profile.serverId));
|
||||
projectIconCache.setHosts(profiles.map((profile) => profile.serverId));
|
||||
await projectIconCache.restore();
|
||||
this.syncHosts(profiles);
|
||||
this.setHostsAndSync(profiles);
|
||||
for (const profile of profiles) {
|
||||
void this.directorySyncByServer
|
||||
.get(profile.serverId)
|
||||
|
||||
@@ -578,6 +578,30 @@ describe("ReplicaCache", () => {
|
||||
expect(restored.agents.get("visible")?.background).toBe(false);
|
||||
});
|
||||
|
||||
it("keeps an agent's background work and running provider subagents across cache reopen", async () => {
|
||||
const storage = new MemoryStorage();
|
||||
const writer = createCache(storage);
|
||||
const parent = {
|
||||
...agent("parent"),
|
||||
backgroundWork: { count: 2 },
|
||||
runningProviderSubagents: { count: 1 },
|
||||
};
|
||||
const quiet = agent("quiet");
|
||||
writer.commitDirectoryMutations(SERVER_ID, [
|
||||
{ kind: "agent", type: "upsert", id: parent.id, value: parent },
|
||||
{ kind: "agent", type: "upsert", id: quiet.id, value: quiet },
|
||||
]);
|
||||
await writer.flush();
|
||||
|
||||
const restored = await createCache(storage).readDirectory(SERVER_ID);
|
||||
|
||||
expect(restored.agents.get("parent")).toMatchObject({
|
||||
backgroundWork: { count: 2 },
|
||||
runningProviderSubagents: { count: 1 },
|
||||
});
|
||||
expect(restored.agents.get("quiet")?.runningProviderSubagents).toBeUndefined();
|
||||
});
|
||||
|
||||
it("round-trips identified and anonymous open turns without changing protocol status", async () => {
|
||||
const storage = new MemoryStorage();
|
||||
const writer = createCache(storage);
|
||||
|
||||
@@ -237,6 +237,7 @@ const StoredAgentSnapshotSchema = z.strictObject({
|
||||
lastUserMessageAt: IsoDateSchema.nullable(),
|
||||
status: AgentStatusSchema,
|
||||
backgroundWork: z.object({ count: z.number().int().nonnegative() }).optional(),
|
||||
runningProviderSubagents: z.object({ count: z.number().int().nonnegative() }).optional(),
|
||||
activeTurn: z
|
||||
.strictObject({
|
||||
turnId: z.string(),
|
||||
@@ -693,6 +694,7 @@ function serializeAgent(agent: Agent): StoredAgent {
|
||||
...(agent.background ? { background: true } : {}),
|
||||
requiresAttention: agent.requiresAttention ?? false,
|
||||
backgroundWork: agent.backgroundWork,
|
||||
runningProviderSubagents: agent.runningProviderSubagents,
|
||||
attentionReason: agent.attentionReason ?? null,
|
||||
attentionTimestamp: agent.attentionTimestamp?.toISOString() ?? null,
|
||||
archivedAt: agent.archivedAt?.toISOString() ?? null,
|
||||
|
||||
@@ -21,8 +21,7 @@ import {
|
||||
import { useLocalDaemonServerId } from "@/hooks/use-is-local-daemon";
|
||||
import { PairDeviceModal } from "@/desktop/components/pair-device-modal";
|
||||
import { buildSettingsHostSectionRoute } from "@/utils/host-routes";
|
||||
|
||||
const WINDOW_CONTENT_DATASET = { "window-content": "" };
|
||||
import { WINDOW_CONTENT_DATASET } from "@/components/desktop/titlebar-drag-region";
|
||||
|
||||
export function OpenProjectScreen() {
|
||||
const { t } = useTranslation();
|
||||
|
||||
@@ -106,6 +106,79 @@ describe("workspace-pane-state", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("does not locate a file by an id retained from a previous target", () => {
|
||||
const layout: WorkspaceLayout = {
|
||||
root: {
|
||||
kind: "pane",
|
||||
pane: {
|
||||
id: "main",
|
||||
tabIds: ["file_/repo/a.ts", "agent_agent-a"],
|
||||
focusedTabId: "agent_agent-a",
|
||||
},
|
||||
},
|
||||
focusedPaneId: "main",
|
||||
};
|
||||
const tabs = [
|
||||
createTab("file_/repo/a.ts", { kind: "file", path: "/repo/b.ts" }),
|
||||
createTab("agent_agent-a", { kind: "agent", agentId: "agent-a" }),
|
||||
];
|
||||
const target: WorkspaceTab["target"] = { kind: "file", path: "/repo/a.ts" };
|
||||
|
||||
expect(resolveSideFileOpenPlacement({ layout, sourcePaneId: "main", tabs, target })).toEqual({
|
||||
kind: "split-side-pane",
|
||||
paneId: "main",
|
||||
});
|
||||
expect(deriveWorkspacePaneState({ layout, tabs, preferredTarget: target }).activeTabId).toBe(
|
||||
"agent_agent-a",
|
||||
);
|
||||
});
|
||||
|
||||
it("matches a retained file instance when only the requested line range differs", () => {
|
||||
const pane = {
|
||||
id: "main",
|
||||
tabIds: ["retained-file", "agent_agent-a"],
|
||||
focusedTabId: "agent_agent-a",
|
||||
};
|
||||
const layout: WorkspaceLayout = { root: { kind: "pane", pane }, focusedPaneId: "main" };
|
||||
const tabs = [
|
||||
createTab("retained-file", { kind: "file", path: "/repo/a.ts", lineStart: 2 }),
|
||||
createTab("agent_agent-a", { kind: "agent", agentId: "agent-a" }),
|
||||
];
|
||||
const target: WorkspaceTab["target"] = {
|
||||
kind: "file",
|
||||
path: "/repo/a.ts",
|
||||
lineStart: 12,
|
||||
lineEnd: 20,
|
||||
};
|
||||
|
||||
expect(resolveSideFileOpenPlacement({ layout, sourcePaneId: "main", tabs, target })).toEqual({
|
||||
kind: "open-in-source",
|
||||
});
|
||||
expect(deriveWorkspacePaneState({ layout, tabs, preferredTarget: target }).activeTabId).toBe(
|
||||
"retained-file",
|
||||
);
|
||||
});
|
||||
|
||||
it("prefers an exact file navigation target over another instance of the same resource", () => {
|
||||
const pane = {
|
||||
id: "main",
|
||||
tabIds: ["first", "second"],
|
||||
focusedTabId: "first",
|
||||
};
|
||||
const tabs = [
|
||||
createTab("first", { kind: "file", path: "/repo/a.ts", lineStart: 2 }),
|
||||
createTab("second", { kind: "file", path: "/repo/a.ts", lineStart: 12 }),
|
||||
];
|
||||
|
||||
expect(
|
||||
deriveWorkspacePaneState({
|
||||
pane,
|
||||
tabs,
|
||||
preferredTarget: { kind: "file", path: "/repo/a.ts", lineStart: 12 },
|
||||
}).activeTabId,
|
||||
).toBe("second");
|
||||
});
|
||||
|
||||
it("resolves side file opens to an existing file tab", () => {
|
||||
const layout: WorkspaceLayout = {
|
||||
root: {
|
||||
|
||||
@@ -5,12 +5,9 @@ import {
|
||||
} from "@/stores/workspace-layout-store";
|
||||
import type { WorkspaceTab, WorkspaceTabTarget } from "@/workspace-tabs/model";
|
||||
import type { WorkspaceTabDescriptor } from "@/screens/workspace/workspace-tabs-types";
|
||||
import {
|
||||
buildDeterministicWorkspaceTabId,
|
||||
normalizeWorkspaceTabTarget,
|
||||
workspaceTabTargetsEqual,
|
||||
} from "@/workspace-tabs/identity";
|
||||
import { normalizeWorkspaceTabTarget, workspaceTabTargetsEqual } from "@/workspace-tabs/identity";
|
||||
import { findAdjacentPane } from "@/utils/split-navigation";
|
||||
import { panelResourceKey } from "@/panels/panel-manifest";
|
||||
|
||||
export interface WorkspaceDerivedTab {
|
||||
descriptor: WorkspaceTabDescriptor;
|
||||
@@ -124,8 +121,10 @@ function getActiveTabId(input: {
|
||||
}
|
||||
const matchingTab =
|
||||
input.tabs.find((tab) => workspaceTabTargetsEqual(tab.descriptor.target, preferredTarget)) ??
|
||||
null;
|
||||
return matchingTab?.descriptor.tabId ?? buildDeterministicWorkspaceTabId(preferredTarget);
|
||||
input.tabs.find(
|
||||
(tab) => panelResourceKey(tab.descriptor.target) === panelResourceKey(preferredTarget),
|
||||
);
|
||||
return matchingTab?.descriptor.tabId ?? null;
|
||||
})();
|
||||
|
||||
if (preferredTabId && input.openTabIds.has(preferredTabId)) {
|
||||
@@ -211,10 +210,8 @@ export function resolveSideFileOpenPlacement(input: {
|
||||
tabs: WorkspaceTab[];
|
||||
target: WorkspaceTabTarget;
|
||||
}): WorkspaceSideFileOpenPlacement {
|
||||
const targetTabId = buildDeterministicWorkspaceTabId(input.target);
|
||||
const existingTab = input.tabs.find(
|
||||
(tab) => tab.tabId === targetTabId || workspaceTabTargetsEqual(tab.target, input.target),
|
||||
);
|
||||
const targetKey = panelResourceKey(input.target);
|
||||
const existingTab = input.tabs.find((tab) => panelResourceKey(tab.target) === targetKey);
|
||||
if (existingTab) {
|
||||
return { kind: "open-in-source" };
|
||||
}
|
||||
|
||||
@@ -2003,9 +2003,8 @@ function WorkspaceScreenContent({
|
||||
const agent =
|
||||
useSessionStore.getState().sessions[normalizedServerId]?.agents?.get(agentId) ?? null;
|
||||
let closePolicy = resolveCloseAgentTabPolicy(agent);
|
||||
const isRunning = agent?.status === "running";
|
||||
|
||||
if (isRunning && closePolicy.kind === "archive-on-close") {
|
||||
if (closePolicy.kind === "archive-on-close" && closePolicy.confirmArchive) {
|
||||
const confirmed = await confirmDialog({
|
||||
title: t("workspace.tabs.confirmations.archiveRunningAgentTitle"),
|
||||
message: t("workspace.tabs.confirmations.archiveRunningAgentMessage"),
|
||||
|
||||
@@ -79,6 +79,7 @@ export interface Agent {
|
||||
provider: AgentProvider;
|
||||
status: AgentLifecycleStatus;
|
||||
backgroundWork?: { count: number };
|
||||
runningProviderSubagents?: { count: number };
|
||||
turn: TurnLiveness;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
|
||||
@@ -3,7 +3,7 @@ import type { JsonValue } from "@getpaseo/protocol/agent-types";
|
||||
import type { WorkspaceTab, WorkspaceTabTarget } from "@/workspace-tabs/model";
|
||||
import { MIN_SPLIT_SIZE } from "@/stores/workspace-layout-constants";
|
||||
import { panelResourceKey, panelSupportsHost } from "@/panels/panel-manifest";
|
||||
import { defaultWorkspaceLayoutIds } from "@/stores/workspace-layout-ids";
|
||||
import { allocateWorkspaceTabId, defaultWorkspaceLayoutIds } from "@/stores/workspace-layout-ids";
|
||||
import type { WorkspaceLayoutNodeIdPrefix } from "@/stores/workspace-layout-ids";
|
||||
import {
|
||||
buildDeterministicWorkspaceTabId,
|
||||
@@ -137,6 +137,8 @@ interface OpenTabInLayoutInput {
|
||||
placement: WorkspaceTabPlacement;
|
||||
/** Required so a new caller cannot silently opt out of Explorer placement rules. */
|
||||
explorerSidebarPaneId: string | null;
|
||||
/** Live sheets share the workspace's panel-instance namespace with its tabs. */
|
||||
reservedTabIds?: ReadonlySet<string>;
|
||||
}
|
||||
|
||||
interface CreateTabInLayoutInput extends OpenTabInLayoutInput {
|
||||
@@ -261,6 +263,7 @@ interface ReorderPaneTabsInLayoutInput {
|
||||
|
||||
export interface WorkspaceTabReconcileState {
|
||||
layout: WorkspaceLayout;
|
||||
reservedTabIds?: ReadonlySet<string>;
|
||||
pinnedAgentIds?: ReadonlySet<string> | null;
|
||||
hiddenAgentIds?: ReadonlySet<string> | null;
|
||||
explorerSidebarPaneId: string | null;
|
||||
@@ -398,15 +401,11 @@ function normalizeWorkspaceTabs(input: unknown): WorkspaceTab[] {
|
||||
if (!Array.isArray(input)) {
|
||||
return [];
|
||||
}
|
||||
// Preserve colliding entries until the whole layout can assign each an identity.
|
||||
const next: WorkspaceTab[] = [];
|
||||
const seen = new Set<string>();
|
||||
for (const value of input) {
|
||||
const tab = normalizeWorkspaceTab(value);
|
||||
if (!tab || seen.has(tab.tabId)) {
|
||||
continue;
|
||||
}
|
||||
seen.add(tab.tabId);
|
||||
next.push(tab);
|
||||
if (tab) next.push(tab);
|
||||
}
|
||||
return next;
|
||||
}
|
||||
@@ -1022,13 +1021,65 @@ function insertSplitInternal(input: InsertSplitInternalInput): InsertSplitIntern
|
||||
};
|
||||
}
|
||||
|
||||
function repairDuplicateTabIds(root: SplitNodeInternal): {
|
||||
root: SplitNodeInternal;
|
||||
ambiguousIds: ReadonlySet<string>;
|
||||
} {
|
||||
const keepers = new Map<string, WorkspaceTab>();
|
||||
const ambiguousIds = new Set<string>();
|
||||
for (const tab of collectAllTabs(root)) {
|
||||
const keeper = keepers.get(tab.tabId);
|
||||
if (!keeper) {
|
||||
keepers.set(tab.tabId, tab);
|
||||
continue;
|
||||
}
|
||||
ambiguousIds.add(tab.tabId);
|
||||
if (
|
||||
buildDeterministicWorkspaceTabId(tab.target) === tab.tabId &&
|
||||
buildDeterministicWorkspaceTabId(keeper.target) !== keeper.tabId
|
||||
) {
|
||||
keepers.set(tab.tabId, tab);
|
||||
}
|
||||
}
|
||||
if (ambiguousIds.size === 0) return { root, ambiguousIds };
|
||||
|
||||
// Reserve every original id before assigning replacements, including hidden panes.
|
||||
const occupiedIds = new Set(keepers.keys());
|
||||
function repair(node: SplitNodeInternal): SplitNodeInternal {
|
||||
if (node.kind === "group") {
|
||||
return { ...node, group: { ...node.group, children: node.group.children.map(repair) } };
|
||||
}
|
||||
const focusedCandidates = node.pane.tabs.filter((tab) => tab.tabId === node.pane.focusedTabId);
|
||||
const focusedTab =
|
||||
focusedCandidates.find((tab) => keepers.get(tab.tabId) === tab) ?? focusedCandidates[0];
|
||||
let focusedTabId = node.pane.focusedTabId;
|
||||
const tabs = node.pane.tabs.map((tab) => {
|
||||
if (keepers.get(tab.tabId) === tab) return tab;
|
||||
const tabId = allocateWorkspaceTabId(
|
||||
buildDeterministicWorkspaceTabId(tab.target),
|
||||
occupiedIds,
|
||||
);
|
||||
occupiedIds.add(tabId);
|
||||
if (tab === focusedTab) focusedTabId = tabId;
|
||||
return { ...tab, tabId };
|
||||
});
|
||||
return {
|
||||
...node,
|
||||
pane: { ...node.pane, tabs, tabIds: tabs.map((tab) => tab.tabId), focusedTabId },
|
||||
};
|
||||
}
|
||||
return { root: repair(root), ambiguousIds };
|
||||
}
|
||||
|
||||
export function normalizeLayout(layout: unknown): WorkspaceLayout {
|
||||
if (!layout || typeof layout !== "object") {
|
||||
return createDefaultLayout();
|
||||
}
|
||||
|
||||
const rawLayout = layout as WorkspaceLayout;
|
||||
const root = normalizeNode(rawLayout.root) ?? asInternalNode(createDefaultLayout().root);
|
||||
const { root, ambiguousIds } = repairDuplicateTabIds(
|
||||
normalizeNode(rawLayout.root) ?? asInternalNode(createDefaultLayout().root),
|
||||
);
|
||||
const focusedPaneId =
|
||||
rawLayout.focusedPaneId === null ? null : trimNonEmpty(rawLayout.focusedPaneId);
|
||||
const resolvedFocusedPaneId =
|
||||
@@ -1047,7 +1098,16 @@ export function normalizeLayout(layout: unknown): WorkspaceLayout {
|
||||
openTabIds: new Set(collectAllTabs(root).map((tab) => tab.tabId)),
|
||||
});
|
||||
|
||||
return parentTabIdByTabId ? { ...normalizedLayout, parentTabIdByTabId } : normalizedLayout;
|
||||
if (parentTabIdByTabId) {
|
||||
// A duplicated id cannot identify either end of a parent relationship unambiguously.
|
||||
for (const [childId, parentId] of Object.entries(parentTabIdByTabId)) {
|
||||
if (ambiguousIds.has(childId) || ambiguousIds.has(parentId))
|
||||
delete parentTabIdByTabId[childId];
|
||||
}
|
||||
if (Object.keys(parentTabIdByTabId).length > 0)
|
||||
return { ...normalizedLayout, parentTabIdByTabId };
|
||||
}
|
||||
return normalizedLayout;
|
||||
}
|
||||
|
||||
export function findPaneById(root: SplitNode, paneId: string | null | undefined): SplitPane | null {
|
||||
@@ -1364,7 +1424,9 @@ function insertNewTabIntoPane(
|
||||
return null;
|
||||
}
|
||||
|
||||
const tabId = input.createTabId();
|
||||
const occupiedIds = new Set(input.reservedTabIds);
|
||||
for (const tab of collectAllTabs(layout.root)) occupiedIds.add(tab.tabId);
|
||||
const tabId = allocateWorkspaceTabId(input.createTabId(), occupiedIds);
|
||||
const nextTab: WorkspaceTab = {
|
||||
tabId,
|
||||
target: input.target,
|
||||
@@ -2284,6 +2346,7 @@ function openEntityTabWithoutFocusing(input: {
|
||||
layout: WorkspaceLayout;
|
||||
target: WorkspaceTabTarget;
|
||||
explorerSidebarPaneId: string | null;
|
||||
reservedTabIds: ReadonlySet<string> | undefined;
|
||||
}): WorkspaceLayout {
|
||||
return (
|
||||
insertNewTabIntoPane({
|
||||
@@ -2292,6 +2355,7 @@ function openEntityTabWithoutFocusing(input: {
|
||||
now: Date.now(),
|
||||
placement: AMBIENT_PLACEMENT,
|
||||
explorerSidebarPaneId: input.explorerSidebarPaneId,
|
||||
reservedTabIds: input.reservedTabIds,
|
||||
createTabId: () => buildDeterministicWorkspaceTabId(input.target),
|
||||
focus: false,
|
||||
})?.layout ?? input.layout
|
||||
@@ -2382,6 +2446,7 @@ function addMissingEntityTabs(input: {
|
||||
hasActivePendingTerminalCreate: boolean;
|
||||
hasActivePendingDraftCreate: boolean;
|
||||
explorerSidebarPaneId: string | null;
|
||||
reservedTabIds: ReadonlySet<string> | undefined;
|
||||
}): WorkspaceLayout {
|
||||
const {
|
||||
autoOpenAgentIds,
|
||||
@@ -2412,6 +2477,7 @@ function addMissingEntityTabs(input: {
|
||||
layout: nextLayout,
|
||||
target: { kind: "agent", agentId },
|
||||
explorerSidebarPaneId,
|
||||
reservedTabIds: input.reservedTabIds,
|
||||
});
|
||||
currentAgentIds.add(agentId);
|
||||
}
|
||||
@@ -2426,6 +2492,7 @@ function addMissingEntityTabs(input: {
|
||||
layout: nextLayout,
|
||||
target: { kind: "terminal", terminalId },
|
||||
explorerSidebarPaneId,
|
||||
reservedTabIds: input.reservedTabIds,
|
||||
});
|
||||
currentTerminalIds.add(terminalId);
|
||||
}
|
||||
@@ -2525,6 +2592,7 @@ export function reconcileWorkspaceTabs(
|
||||
hasActivePendingTerminalCreate: snapshot.hasActivePendingTerminalCreate ?? false,
|
||||
hasActivePendingDraftCreate: snapshot.hasActivePendingDraftCreate ?? false,
|
||||
explorerSidebarPaneId: state.explorerSidebarPaneId,
|
||||
reservedTabIds: state.reservedTabIds,
|
||||
});
|
||||
|
||||
if (reconciledFocusedTabId) {
|
||||
|
||||
@@ -11,6 +11,22 @@ function createRandomIdValue(): string {
|
||||
: `${Date.now()}-${Math.random().toString(16).slice(2)}`;
|
||||
}
|
||||
|
||||
export function createWorkspaceTabInstanceId(): string {
|
||||
return `tab_${createRandomIdValue()}`;
|
||||
}
|
||||
|
||||
/** A resource-derived id may still belong to a preview slot showing another target. */
|
||||
export function allocateWorkspaceTabId(
|
||||
preferredId: string,
|
||||
occupiedIds: ReadonlySet<string>,
|
||||
): string {
|
||||
let tabId = preferredId;
|
||||
for (let suffix = 2; occupiedIds.has(tabId); suffix += 1) {
|
||||
tabId = `${preferredId}:${suffix}`;
|
||||
}
|
||||
return tabId;
|
||||
}
|
||||
|
||||
export const defaultWorkspaceLayoutIds: WorkspaceLayoutIdSource = {
|
||||
createNodeId: (prefix) => `${prefix}_${createRandomIdValue()}`,
|
||||
createFocusRestorationToken: () => `workspace-focus-${createRandomIdValue()}`,
|
||||
|
||||
@@ -59,6 +59,84 @@ it("skips unchanged reconciliations and immediately saves real layout changes",
|
||||
);
|
||||
});
|
||||
|
||||
it("hydrates a saved preview collision and persists the repaired identities", async () => {
|
||||
const workspaceKey = "server:workspace";
|
||||
const duplicateId = "file_a.ts";
|
||||
const values = new Map([
|
||||
[
|
||||
"workspace-layout-state",
|
||||
JSON.stringify({
|
||||
version: 2,
|
||||
state: {
|
||||
layoutByWorkspace: {
|
||||
[workspaceKey]: {
|
||||
root: {
|
||||
kind: "group",
|
||||
group: {
|
||||
id: "split",
|
||||
direction: "horizontal",
|
||||
sizes: [0.5, 0.5],
|
||||
children: [
|
||||
{ id: "main", path: "b.ts" },
|
||||
{ id: "right", path: "a.ts" },
|
||||
].map(({ id, path }) => ({
|
||||
kind: "pane",
|
||||
pane: {
|
||||
id,
|
||||
tabIds: [duplicateId],
|
||||
focusedTabId: duplicateId,
|
||||
tabs: [{ tabId: duplicateId, target: { kind: "file", path }, createdAt: 1 }],
|
||||
},
|
||||
})),
|
||||
},
|
||||
},
|
||||
focusedPaneId: "right",
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
],
|
||||
]);
|
||||
const storage: StateStorage = {
|
||||
getItem: (name) => values.get(name) ?? null,
|
||||
setItem: (name, value) => {
|
||||
values.set(name, value);
|
||||
},
|
||||
removeItem: (name) => {
|
||||
values.delete(name);
|
||||
},
|
||||
};
|
||||
const store = createWorkspaceLayoutStore(undefined, storage);
|
||||
await store.persist.rehydrate();
|
||||
const layout = store.getState().layoutByWorkspace[workspaceKey];
|
||||
const tabs = collectAllTabs(layout.root);
|
||||
|
||||
expect(tabs.filter((tab) => tab.target.kind === "file").map((tab) => tab.tabId)).toEqual([
|
||||
"file_b.ts",
|
||||
"file_a.ts",
|
||||
]);
|
||||
expect(
|
||||
deriveWorkspacePaneState({ layout, tabs, paneId: "main" }).activeTab?.descriptor.target,
|
||||
).toEqual({
|
||||
kind: "file",
|
||||
path: "b.ts",
|
||||
});
|
||||
expect(
|
||||
deriveWorkspacePaneState({ layout, tabs, paneId: "right" }).activeTab?.descriptor.target,
|
||||
).toEqual({
|
||||
kind: "file",
|
||||
path: "a.ts",
|
||||
});
|
||||
store.getState().focusTab(workspaceKey, "file_b.ts");
|
||||
expect(store.getState().layoutByWorkspace[workspaceKey].focusedPaneId).toBe("main");
|
||||
|
||||
const reloaded = createWorkspaceLayoutStore(undefined, storage);
|
||||
await reloaded.persist.rehydrate();
|
||||
expect(reloaded.getState().layoutByWorkspace[workspaceKey]).toEqual(
|
||||
store.getState().layoutByWorkspace[workspaceKey],
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps the saved layout when the shell publishes its layout mode before hydration", async () => {
|
||||
const values = new Map<string, string>();
|
||||
const storage: StateStorage = {
|
||||
|
||||
@@ -906,6 +906,91 @@ describe("workspace-layout-store actions", () => {
|
||||
).toEqual(override);
|
||||
});
|
||||
|
||||
it("keeps reused file tabs unique and focuses the matching split pane", () => {
|
||||
const workspaceKey = createWorkspaceKey();
|
||||
const store = workspaceLayoutStore.getState();
|
||||
const firstTabId = store.openTab({
|
||||
workspaceKey,
|
||||
target: { kind: "file", path: "src/a.ts" },
|
||||
intent: "reveal",
|
||||
})!;
|
||||
store.replaceTab(workspaceKey, firstTabId, { kind: "file", path: "src/b.ts" });
|
||||
const rightPaneId = store.splitPaneEmpty(workspaceKey, {
|
||||
targetPaneId: "main",
|
||||
position: "right",
|
||||
});
|
||||
if (!rightPaneId) throw new Error("Expected a right split pane");
|
||||
const rightTabId = store.openTab({
|
||||
workspaceKey,
|
||||
target: { kind: "file", path: "src/a.ts" },
|
||||
intent: "reveal",
|
||||
placement: { mode: "pane", paneId: rightPaneId },
|
||||
})!;
|
||||
|
||||
store.openTab({
|
||||
workspaceKey,
|
||||
target: { kind: "file", path: "src/b.ts" },
|
||||
intent: "reveal",
|
||||
});
|
||||
store.focusTab(workspaceKey, rightTabId);
|
||||
|
||||
const layout = workspaceLayoutStore.getState().layoutByWorkspace[workspaceKey];
|
||||
const fileTabs = collectAllTabs(layout.root).filter((tab) => tab.target.kind === "file");
|
||||
expect({
|
||||
fileTabCount: fileTabs.length,
|
||||
uniqueFileTabCount: new Set(fileTabs.map((tab) => tab.tabId)).size,
|
||||
fileTargets: fileTabs.map((tab) => tab.target),
|
||||
focusedPaneId: layout.focusedPaneId,
|
||||
}).toEqual({
|
||||
fileTabCount: 2,
|
||||
uniqueFileTabCount: 2,
|
||||
fileTargets: [
|
||||
{ kind: "file", path: "src/b.ts" },
|
||||
{ kind: "file", path: "src/a.ts" },
|
||||
],
|
||||
focusedPaneId: rightPaneId,
|
||||
});
|
||||
});
|
||||
|
||||
it("allocates distinct ids across retained tabs, sheets, and background opens", () => {
|
||||
const workspaceKey = createWorkspaceKey();
|
||||
const layoutStore = createWorkspaceLayoutStore(workspaceLayoutIds);
|
||||
const store = layoutStore.getState();
|
||||
const fileTabId = store.openTab({
|
||||
workspaceKey,
|
||||
target: { kind: "file", path: "src/a.ts" },
|
||||
intent: "reveal",
|
||||
})!;
|
||||
store.replaceTab(workspaceKey, fileTabId, { kind: "file", path: "src/b.ts" });
|
||||
layoutStore.setState({ layoutMode: "compact" });
|
||||
const sheetTabId = store.openTab({
|
||||
workspaceKey,
|
||||
target: { kind: "file", path: "src/a.ts" },
|
||||
intent: "reveal",
|
||||
})!;
|
||||
const selectedSheet = selectSheetTab(layoutStore.getState(), {
|
||||
workspaceKey,
|
||||
target: { kind: "file", path: "src/a.ts" },
|
||||
});
|
||||
expect(selectedSheet?.tab.tabId).toBe(sheetTabId);
|
||||
const backgroundTabId = store.openTab({
|
||||
workspaceKey,
|
||||
target: { kind: "file", path: "src/a.ts" },
|
||||
intent: "background",
|
||||
})!;
|
||||
|
||||
expect(new Set([fileTabId, sheetTabId, backgroundTabId]).size).toBe(3);
|
||||
expect(layoutStore.getState().sheetsByWorkspace[workspaceKey]).toHaveLength(1);
|
||||
expect(
|
||||
collectAllTabs(layoutStore.getState().layoutByWorkspace[workspaceKey].root)
|
||||
.filter((tab) => tab.target.kind === "file")
|
||||
.map((tab) => tab.target),
|
||||
).toEqual([
|
||||
{ kind: "file", path: "src/b.ts" },
|
||||
{ kind: "file", path: "src/a.ts" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps the tab instance when a panel receives a same-kind replacement", () => {
|
||||
const workspaceKey = createWorkspaceKey();
|
||||
const store = workspaceLayoutStore.getState();
|
||||
@@ -3200,6 +3285,75 @@ describe("workspace-layout-store actions", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it("repairs persisted duplicate ids without losing tabs, pane focus, or unambiguous parents", () => {
|
||||
const file = (tabId: string, path: string) => ({
|
||||
tabId,
|
||||
target: { kind: "file", path },
|
||||
createdAt: 1,
|
||||
state: { treeVisible: true, treeWidth: 280 },
|
||||
});
|
||||
const leftTabs = [file("file_a.ts", "b.ts"), file("file_a.ts", "c.ts")];
|
||||
const rightTabs = [
|
||||
file("file_a.ts", "a.ts"),
|
||||
file("file_b.ts", "b.ts"),
|
||||
file("file_b.ts:2", "b.ts"),
|
||||
file("child", "child.ts"),
|
||||
file("parent", "parent.ts"),
|
||||
];
|
||||
const layout = normalizeLayout({
|
||||
root: {
|
||||
kind: "group",
|
||||
group: {
|
||||
id: "root",
|
||||
direction: "horizontal",
|
||||
sizes: [0.4, 0.6],
|
||||
children: [
|
||||
{
|
||||
kind: "pane",
|
||||
pane: {
|
||||
id: "main",
|
||||
tabs: leftTabs,
|
||||
tabIds: leftTabs.map((tab) => tab.tabId),
|
||||
focusedTabId: "file_a.ts",
|
||||
},
|
||||
},
|
||||
{
|
||||
kind: "pane",
|
||||
pane: {
|
||||
id: "right",
|
||||
tabs: rightTabs,
|
||||
tabIds: rightTabs.map((tab) => tab.tabId),
|
||||
focusedTabId: "file_a.ts",
|
||||
hidden: true,
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
focusedPaneId: "main",
|
||||
parentTabIdByTabId: {
|
||||
"file_a.ts": "parent",
|
||||
"file_b.ts": "file_a.ts",
|
||||
child: "parent",
|
||||
},
|
||||
});
|
||||
const tabs = collectAllTabs(layout.root);
|
||||
|
||||
expect(tabs).toHaveLength(7);
|
||||
expect(new Set(tabs.map((tab) => tab.tabId)).size).toBe(7);
|
||||
expect(tabs[0]).toEqual({ ...leftTabs[0], tabId: "file_b.ts:3" });
|
||||
expect(tabs[1]).toEqual({ ...leftTabs[1], tabId: "file_c.ts" });
|
||||
expect(tabs.slice(2)).toEqual(rightTabs);
|
||||
expect(findPaneById(layout.root, "main")?.tabIds).toEqual(["file_b.ts:3", "file_c.ts"]);
|
||||
expect(findPaneById(layout.root, "main")?.focusedTabId).toBe("file_b.ts:3");
|
||||
expect(findPaneById(layout.root, "right")).toMatchObject({
|
||||
hidden: true,
|
||||
focusedTabId: "file_a.ts",
|
||||
});
|
||||
expect(layout.parentTabIdByTabId).toEqual({ child: "parent" });
|
||||
expect(normalizeLayout(layout)).toEqual(layout);
|
||||
});
|
||||
|
||||
it("hydrates duplicate Changes and Pull request instances without collapsing their ids or state", () => {
|
||||
const tabs = [
|
||||
{
|
||||
@@ -5110,6 +5264,50 @@ describe("compact workspace sheet", () => {
|
||||
expect(sheetTargets(store)).toEqual([fileTarget, nextTarget]);
|
||||
});
|
||||
|
||||
it("reserves a retargeted sheet's id when reconciling a new root agent tab", () => {
|
||||
seedAgents([
|
||||
{ id: "root", parentAgentId: null, workspaceId: "sheet-ws" },
|
||||
{ id: "child-a", parentAgentId: "root", workspaceId: "sheet-ws" },
|
||||
{ id: "child-b", parentAgentId: "root", workspaceId: "sheet-ws" },
|
||||
]);
|
||||
const store = createCompactStore();
|
||||
store.getState().openTab({
|
||||
workspaceKey,
|
||||
target: { kind: "agent", agentId: "child-a" },
|
||||
intent: "reveal",
|
||||
});
|
||||
const sheetId = requireTopSheet(store).tab.tabId;
|
||||
store.getState().replaceTab(workspaceKey, sheetId, { kind: "agent", agentId: "child-b" });
|
||||
seedAgents([
|
||||
{ id: "root", parentAgentId: null, workspaceId: "sheet-ws" },
|
||||
{ id: "child-a", parentAgentId: null, workspaceId: "sheet-ws" },
|
||||
{ id: "child-b", parentAgentId: "root", workspaceId: "sheet-ws" },
|
||||
]);
|
||||
|
||||
store.getState().reconcileTabs(workspaceKey, {
|
||||
agentsHydrated: true,
|
||||
terminalsHydrated: true,
|
||||
activeAgentIds: ["root", "child-a", "child-b"],
|
||||
autoOpenAgentIds: ["child-a"],
|
||||
knownTerminalIds: ["term-1"],
|
||||
standaloneTerminalIds: ["term-1"],
|
||||
});
|
||||
const tab = collectAllTabs(store.getState().layoutByWorkspace[workspaceKey].root).find(
|
||||
(candidate) => candidate.target.kind === "agent" && candidate.target.agentId === "child-a",
|
||||
);
|
||||
if (!tab) throw new Error("Expected the root agent's tab");
|
||||
expect(tab.tabId).not.toBe(sheetId);
|
||||
|
||||
store.getState().closeTab(workspaceKey, tab.tabId);
|
||||
expect(requireTopSheet(store).tab).toMatchObject({
|
||||
tabId: sheetId,
|
||||
target: { kind: "agent", agentId: "child-b" },
|
||||
});
|
||||
expect(
|
||||
collectAllTabs(store.getState().layoutByWorkspace[workspaceKey].root),
|
||||
).not.toContainEqual(tab);
|
||||
});
|
||||
|
||||
it("closes the sheet when its agent stops being a subagent, leaving one tab for it", () => {
|
||||
seedAgents([
|
||||
{ id: "root", parentAgentId: null, workspaceId: "sheet-ws" },
|
||||
|
||||
@@ -7,6 +7,8 @@ import { WorkspaceLayoutPersistedStateSchema } from "./workspace-layout-storage"
|
||||
import type { JsonValue } from "@getpaseo/protocol/agent-types";
|
||||
import type { WorkspaceTab, WorkspaceTabTarget } from "@/workspace-tabs/model";
|
||||
import {
|
||||
allocateWorkspaceTabId,
|
||||
createWorkspaceTabInstanceId,
|
||||
defaultWorkspaceLayoutIds,
|
||||
type WorkspaceLayoutIdSource,
|
||||
} from "@/stores/workspace-layout-ids";
|
||||
@@ -431,14 +433,6 @@ function trimNonEmpty(value: string | null | undefined): string | null {
|
||||
return trimmed.length > 0 ? trimmed : null;
|
||||
}
|
||||
|
||||
function createWorkspaceTabInstanceId(): string {
|
||||
const value =
|
||||
typeof globalThis.crypto?.randomUUID === "function"
|
||||
? globalThis.crypto.randomUUID()
|
||||
: `${Date.now()}-${Math.random().toString(16).slice(2)}`;
|
||||
return `tab_${value}`;
|
||||
}
|
||||
|
||||
function addAgentIdToWorkspaceSet(
|
||||
state: Record<string, Set<string>>,
|
||||
workspaceKey: string,
|
||||
@@ -531,7 +525,10 @@ export function selectExplorerSidebarPaneId(
|
||||
*/
|
||||
export function selectSheetTab(
|
||||
state: Pick<WorkspaceLayoutStore, "layoutMode" | "layoutByWorkspace" | "sheetsByWorkspace">,
|
||||
input: Pick<OpenWorkspaceTabInput, "workspaceKey" | "target" | "parentTabId">,
|
||||
input: Pick<OpenWorkspaceTabInput, "workspaceKey" | "target" | "parentTabId"> & {
|
||||
/** A host outside the sheet stack owns its instance identity. */
|
||||
preferredTabId?: string;
|
||||
},
|
||||
): SheetTab | null {
|
||||
const workspaceKey = trimNonEmpty(input.workspaceKey);
|
||||
const target = normalizeWorkspaceTabTarget(input.target);
|
||||
@@ -539,9 +536,14 @@ export function selectSheetTab(
|
||||
const policy = resolveSheetPolicy(state, workspaceKey, target, "reveal");
|
||||
if (!policy) return null;
|
||||
return placeTargetInSheet({
|
||||
kept: undefined,
|
||||
occupiedTabIds: collectWorkspaceTabIds(state, workspaceKey),
|
||||
kept: input.preferredTabId
|
||||
? undefined
|
||||
: getSheets(state, workspaceKey).find(
|
||||
(sheet) => panelResourceKey(sheet.tab.target) === panelResourceKey(target),
|
||||
),
|
||||
target,
|
||||
intent: "reveal",
|
||||
createTabId: () => input.preferredTabId ?? buildDeterministicWorkspaceTabId(target),
|
||||
policy,
|
||||
parentTabId: resolveOpenParentTabId(state, workspaceKey, input.parentTabId),
|
||||
state: undefined,
|
||||
@@ -638,6 +640,7 @@ function getOpenTabPlacement(
|
||||
layout: WorkspaceLayout;
|
||||
placement: WorkspaceTabPlacement;
|
||||
explorerSidebarPaneId: string | null;
|
||||
reservedTabIds: Set<string>;
|
||||
} {
|
||||
const layout = getWorkspaceLayout(state.layoutByWorkspace, workspaceKey);
|
||||
const explorerSidebarPaneId = resolveExplorerSidebarPaneId(
|
||||
@@ -670,6 +673,7 @@ function getOpenTabPlacement(
|
||||
layout,
|
||||
placement: resolvedPlacement,
|
||||
explorerSidebarPaneId,
|
||||
reservedTabIds: new Set(getSheets(state, workspaceKey).map((sheet) => sheet.tab.tabId)),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -815,11 +819,23 @@ function resolveOpenParentTabId(
|
||||
return findSheet(state, workspaceKey, parentTabId)?.parentTabId ?? parentTabId;
|
||||
}
|
||||
|
||||
function collectWorkspaceTabIds(
|
||||
state: Pick<WorkspaceLayoutStore, "layoutByWorkspace" | "sheetsByWorkspace">,
|
||||
workspaceKey: string,
|
||||
): Set<string> {
|
||||
const layout = state.layoutByWorkspace[workspaceKey];
|
||||
return new Set([
|
||||
...(layout ? collectAllTabs(layout.root).map((tab) => tab.tabId) : []),
|
||||
...getSheets(state, workspaceKey).map((sheet) => sheet.tab.tabId),
|
||||
]);
|
||||
}
|
||||
|
||||
function placeTargetInSheet(input: {
|
||||
occupiedTabIds: ReadonlySet<string>;
|
||||
/** The sheet whose tab the target keeps, if any. */
|
||||
kept: SheetTab | undefined;
|
||||
target: WorkspaceTabTarget;
|
||||
intent: WorkspaceTabOpenIntent;
|
||||
createTabId: () => string;
|
||||
policy: CompactSheetPolicy;
|
||||
parentTabId: string | null;
|
||||
state: JsonValue | undefined;
|
||||
@@ -829,10 +845,7 @@ function placeTargetInSheet(input: {
|
||||
}
|
||||
return {
|
||||
tab: {
|
||||
tabId:
|
||||
input.intent === "reveal"
|
||||
? buildDeterministicWorkspaceTabId(input.target)
|
||||
: createWorkspaceTabInstanceId(),
|
||||
tabId: allocateWorkspaceTabId(input.createTabId(), input.occupiedTabIds),
|
||||
target: input.target,
|
||||
createdAt: Date.now(),
|
||||
...(input.state !== undefined ? { state: input.state } : {}),
|
||||
@@ -853,6 +866,7 @@ function promoteSheetToTab(
|
||||
): { tabId: string; patch: Partial<WorkspaceLayoutStore> } | null {
|
||||
const { tab } = sheet;
|
||||
const placement = getOpenTabPlacement(state, workspaceKey, tab.target, FOCUSED_PANE_PLACEMENT);
|
||||
placement.reservedTabIds.delete(tab.tabId);
|
||||
const input = {
|
||||
...placement,
|
||||
target: tab.target,
|
||||
@@ -1122,9 +1136,13 @@ export function createWorkspaceLayoutStore(
|
||||
const sheets = getSheets(get(), normalizedWorkspaceKey);
|
||||
const { keptIndex } = sheetPlacement;
|
||||
const sheet = placeTargetInSheet({
|
||||
occupiedTabIds: collectWorkspaceTabIds(get(), normalizedWorkspaceKey),
|
||||
kept: keptIndex === null ? undefined : sheets[keptIndex],
|
||||
target: normalizedTarget,
|
||||
intent: input.intent,
|
||||
createTabId: () =>
|
||||
input.intent === "reveal"
|
||||
? buildDeterministicWorkspaceTabId(normalizedTarget)
|
||||
: createWorkspaceTabInstanceId(),
|
||||
policy: sheetPlacement.policy,
|
||||
parentTabId,
|
||||
state: input.state,
|
||||
@@ -1706,9 +1724,14 @@ export function createWorkspaceLayoutStore(
|
||||
explorerSidebarPaneId,
|
||||
rawLayout.focusedPaneId,
|
||||
);
|
||||
const sheets = getSheets(state, normalizedWorkspaceKey);
|
||||
const fittingSheets = sheets.filter(
|
||||
(sheet) => !sheetAgentNoLongerFits(normalizedWorkspaceKey, sheet, snapshot),
|
||||
);
|
||||
const nextState = reconcileWorkspaceTabs(
|
||||
{
|
||||
layout: currentLayout,
|
||||
reservedTabIds: new Set(fittingSheets.map((sheet) => sheet.tab.tabId)),
|
||||
pinnedAgentIds: state.pinnedAgentIdsByWorkspace[normalizedWorkspaceKey] ?? null,
|
||||
hiddenAgentIds: state.hiddenAgentIdsByWorkspace[normalizedWorkspaceKey] ?? null,
|
||||
explorerSidebarPaneId,
|
||||
@@ -1730,10 +1753,6 @@ export function createWorkspaceLayoutStore(
|
||||
);
|
||||
}
|
||||
}
|
||||
const sheets = getSheets(state, normalizedWorkspaceKey);
|
||||
const fittingSheets = sheets.filter(
|
||||
(sheet) => !sheetAgentNoLongerFits(normalizedWorkspaceKey, sheet, snapshot),
|
||||
);
|
||||
const sheetAgentGone = fittingSheets.length !== sheets.length;
|
||||
if (
|
||||
state.layoutByWorkspace[normalizedWorkspaceKey] &&
|
||||
|
||||
@@ -1,21 +1,48 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { resolveCloseAgentTabPolicy } from "./close-tab-policy";
|
||||
|
||||
function rootAgent(overrides: Partial<Parameters<typeof resolveCloseAgentTabPolicy>[0]> = {}) {
|
||||
return { parentAgentId: null, status: "idle" as const, ...overrides };
|
||||
}
|
||||
|
||||
describe("resolveCloseAgentTabPolicy", () => {
|
||||
it("archives root agents when their tab closes", () => {
|
||||
expect(resolveCloseAgentTabPolicy({ parentAgentId: null })).toEqual({
|
||||
it("archives an idle root agent without asking", () => {
|
||||
expect(resolveCloseAgentTabPolicy(rootAgent())).toEqual({
|
||||
kind: "archive-on-close",
|
||||
confirmArchive: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("asks before archiving a running root agent", () => {
|
||||
expect(resolveCloseAgentTabPolicy(rootAgent({ status: "running" }))).toEqual({
|
||||
kind: "archive-on-close",
|
||||
confirmArchive: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("asks before archiving a root agent whose turn ended while background work still runs", () => {
|
||||
expect(resolveCloseAgentTabPolicy(rootAgent({ backgroundWork: { count: 1 } }))).toEqual({
|
||||
kind: "archive-on-close",
|
||||
confirmArchive: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("asks before archiving a root agent whose turn ended while its background subagent still runs", () => {
|
||||
expect(
|
||||
resolveCloseAgentTabPolicy(rootAgent({ runningProviderSubagents: { count: 1 } })),
|
||||
).toEqual({ kind: "archive-on-close", confirmArchive: true });
|
||||
});
|
||||
|
||||
it("keeps subagent tab close layout-only", () => {
|
||||
expect(resolveCloseAgentTabPolicy({ parentAgentId: "parent-agent" })).toEqual({
|
||||
kind: "layout-only",
|
||||
});
|
||||
expect(
|
||||
resolveCloseAgentTabPolicy(rootAgent({ parentAgentId: "parent-agent", status: "running" })),
|
||||
).toEqual({ kind: "layout-only" });
|
||||
});
|
||||
|
||||
it("preserves the existing archive fallback when the agent is missing", () => {
|
||||
expect(resolveCloseAgentTabPolicy(null)).toEqual({ kind: "archive-on-close" });
|
||||
expect(resolveCloseAgentTabPolicy(undefined)).toEqual({ kind: "archive-on-close" });
|
||||
expect(resolveCloseAgentTabPolicy(null)).toEqual({
|
||||
kind: "archive-on-close",
|
||||
confirmArchive: false,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,13 +1,30 @@
|
||||
import type { Agent } from "@/stores/session-store";
|
||||
|
||||
export type CloseAgentTabPolicy = { kind: "archive-on-close" } | { kind: "layout-only" };
|
||||
export type CloseAgentTabPolicy =
|
||||
| { kind: "archive-on-close"; confirmArchive: boolean }
|
||||
| { kind: "layout-only" };
|
||||
|
||||
type CloseTabAgent = Pick<
|
||||
Agent,
|
||||
"parentAgentId" | "status" | "backgroundWork" | "runningProviderSubagents"
|
||||
>;
|
||||
|
||||
export function resolveCloseAgentTabPolicy(
|
||||
agent: Pick<Agent, "parentAgentId"> | null | undefined,
|
||||
agent: CloseTabAgent | null | undefined,
|
||||
): CloseAgentTabPolicy {
|
||||
if (agent?.parentAgentId) {
|
||||
return { kind: "layout-only" };
|
||||
}
|
||||
|
||||
return { kind: "archive-on-close" };
|
||||
return { kind: "archive-on-close", confirmArchive: agent ? hasRunningWork(agent) : false };
|
||||
}
|
||||
|
||||
// Archiving stops the agent's process, which also stops work it left running after its turn
|
||||
// ended: background subagents and background shells.
|
||||
function hasRunningWork(agent: CloseTabAgent): boolean {
|
||||
return (
|
||||
agent.status === "running" ||
|
||||
(agent.backgroundWork?.count ?? 0) > 0 ||
|
||||
(agent.runningProviderSubagents?.count ?? 0) > 0
|
||||
);
|
||||
}
|
||||
|
||||
@@ -138,6 +138,88 @@ describe("useSubagentSheetTab", () => {
|
||||
expect(result.current?.tab.tabId).toBe(tabId);
|
||||
});
|
||||
|
||||
it("keeps an open menu sheet's id when an unrelated reused tab disappears", () => {
|
||||
const row = seedParentWithChild();
|
||||
const store = useWorkspaceLayoutStore.getState();
|
||||
const reusedId = store.openTab({
|
||||
workspaceKey,
|
||||
target: { kind: "agent", agentId: "child" },
|
||||
intent: "reveal",
|
||||
asTab: true,
|
||||
});
|
||||
if (!reusedId) throw new Error("Expected a child tab");
|
||||
store.replaceTab(workspaceKey, reusedId, { kind: "agent", agentId: "other" });
|
||||
store.setLayoutMode("compact");
|
||||
const { result } = renderHook(() => useSubagentSheetTab(workspaceKey, "parent-tab")(row));
|
||||
const sheetId = result.current?.tab.tabId;
|
||||
expect(result.current?.tab.target).toEqual({ kind: "agent", agentId: "child" });
|
||||
expect(sheetId).not.toBe(reusedId);
|
||||
|
||||
act(() => {
|
||||
store.reconcileTabs(workspaceKey, {
|
||||
agentsHydrated: true,
|
||||
terminalsHydrated: true,
|
||||
activeAgentIds: ["parent", "child"],
|
||||
autoOpenAgentIds: [],
|
||||
knownTerminalIds: [],
|
||||
standaloneTerminalIds: [],
|
||||
});
|
||||
});
|
||||
expect(store.getWorkspaceTabs(workspaceKey).map((tab) => tab.tabId)).not.toContain(reusedId);
|
||||
expect(result.current?.tab.tabId).toBe(sheetId);
|
||||
expect(result.current?.tab.target).toEqual({ kind: "agent", agentId: "child" });
|
||||
});
|
||||
|
||||
it("promotes a menu sheet to the subagent's own tab", () => {
|
||||
const row = seedParentWithChild();
|
||||
const store = useWorkspaceLayoutStore.getState();
|
||||
store.setLayoutMode("compact");
|
||||
const { result } = renderHook(() => useSubagentSheetTab(workspaceKey, "parent-tab")(row));
|
||||
const sheet = result.current;
|
||||
if (!sheet) throw new Error("Expected a menu sheet");
|
||||
|
||||
let promotedId: string | null = null;
|
||||
act(() => {
|
||||
promotedId = store.openTabInFront(workspaceKey, sheet);
|
||||
});
|
||||
expect(promotedId).toBe("agent_child");
|
||||
expect(
|
||||
store.getWorkspaceTabs(workspaceKey).filter((tab) => tab.target.kind === "agent"),
|
||||
).toEqual([
|
||||
expect.objectContaining({
|
||||
tabId: "agent_child",
|
||||
target: { kind: "agent", agentId: "child" },
|
||||
}),
|
||||
]);
|
||||
});
|
||||
|
||||
it("does not reuse a menu id retained by a promoted tab showing another target", () => {
|
||||
const row = seedParentWithChild();
|
||||
const store = useWorkspaceLayoutStore.getState();
|
||||
store.setLayoutMode("compact");
|
||||
const { result } = renderHook(() => useSubagentSheetTab(workspaceKey, "parent-tab")(row));
|
||||
const sheet = result.current;
|
||||
if (!sheet) throw new Error("Expected a menu sheet");
|
||||
act(() => {
|
||||
store.openTabInFront(workspaceKey, sheet);
|
||||
});
|
||||
expect(result.current).toBeNull();
|
||||
|
||||
act(() => {
|
||||
store.replaceTab(workspaceKey, sheet.tab.tabId, { kind: "agent", agentId: "other" });
|
||||
});
|
||||
expect(result.current?.tab.target).toEqual({ kind: "agent", agentId: "child" });
|
||||
expect(result.current?.tab.tabId).not.toBe(sheet.tab.tabId);
|
||||
expect(
|
||||
store.getWorkspaceTabs(workspaceKey).filter((tab) => tab.target.kind === "agent"),
|
||||
).toEqual([
|
||||
expect.objectContaining({
|
||||
tabId: sheet.tab.tabId,
|
||||
target: { kind: "agent", agentId: "other" },
|
||||
}),
|
||||
]);
|
||||
});
|
||||
|
||||
it("hands a re-rendered row the same sheet", () => {
|
||||
const row = seedParentWithChild();
|
||||
useWorkspaceLayoutStore.getState().setLayoutMode("compact");
|
||||
|
||||
@@ -4,6 +4,7 @@ import {
|
||||
useWorkspaceLayoutStore,
|
||||
type SheetTab,
|
||||
} from "@/stores/workspace-layout-store";
|
||||
import { buildDeterministicWorkspaceTabId } from "@/workspace-tabs/identity";
|
||||
import type { WorkspaceTabTarget } from "@/workspace-tabs/model";
|
||||
import type { SubagentRow } from "./select";
|
||||
|
||||
@@ -32,6 +33,9 @@ export function useSubagentSheetTab(
|
||||
const sheets = useWorkspaceLayoutStore((state) =>
|
||||
workspaceKey ? state.sheetsByWorkspace[workspaceKey] : undefined,
|
||||
);
|
||||
// Menu pages never enter the sheet stack. Each starts from the subagent's own tab id, so opening
|
||||
// it as a tab lands on that id, and keeps the id it was given across layout updates.
|
||||
const tabIds = useMemo(() => new Map<string, string>(), []);
|
||||
return useMemo(() => {
|
||||
// One answer per row until the state it reads changes, so a re-render of the list hands an
|
||||
// open sheet the same tab rather than a fresh one.
|
||||
@@ -43,16 +47,19 @@ export function useSubagentSheetTab(
|
||||
layoutByWorkspace: layout ? { [workspaceKey]: layout } : {},
|
||||
sheetsByWorkspace: sheets ? { [workspaceKey]: sheets } : {},
|
||||
};
|
||||
const key = `${row.kind}:${row.id}`;
|
||||
const key = JSON.stringify([workspaceKey, parentTabId, row.kind, row.id]);
|
||||
const known = answers.get(key);
|
||||
if (known !== undefined) return known;
|
||||
const target = subagentRowTarget(row);
|
||||
const sheet = selectSheetTab(state, {
|
||||
workspaceKey,
|
||||
target: subagentRowTarget(row),
|
||||
target,
|
||||
parentTabId,
|
||||
preferredTabId: tabIds.get(key) ?? buildDeterministicWorkspaceTabId(target),
|
||||
});
|
||||
if (sheet) tabIds.set(key, sheet.tab.tabId);
|
||||
answers.set(key, sheet);
|
||||
return sheet;
|
||||
};
|
||||
}, [layout, layoutMode, parentTabId, sheets, workspaceKey]);
|
||||
}, [layout, layoutMode, parentTabId, sheets, tabIds, workspaceKey]);
|
||||
}
|
||||
|
||||
@@ -72,6 +72,7 @@ export function projectAgentSnapshot(agent: Agent): AgentSnapshotPayload {
|
||||
lastUserMessageAt: agent.lastUserMessageAt?.toISOString() ?? null,
|
||||
status: agent.status,
|
||||
backgroundWork: agent.backgroundWork,
|
||||
runningProviderSubagents: agent.runningProviderSubagents,
|
||||
...projectActiveTurn(agent),
|
||||
capabilities: agent.capabilities,
|
||||
currentModeId: agent.currentModeId,
|
||||
@@ -116,6 +117,7 @@ export function normalizeAgentSnapshot(snapshot: AgentSnapshotPayload, serverId:
|
||||
provider: snapshot.provider,
|
||||
status: snapshot.status,
|
||||
backgroundWork: snapshot.backgroundWork,
|
||||
runningProviderSubagents: snapshot.runningProviderSubagents,
|
||||
turn,
|
||||
createdAt,
|
||||
updatedAt,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@getpaseo/cli",
|
||||
"version": "0.16.2",
|
||||
"version": "0.16.1",
|
||||
"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.2",
|
||||
"@getpaseo/protocol": "0.16.2",
|
||||
"@getpaseo/server": "0.16.2",
|
||||
"@getpaseo/client": "0.16.1",
|
||||
"@getpaseo/protocol": "0.16.1",
|
||||
"@getpaseo/server": "0.16.1",
|
||||
"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; otherwise: interrupt)",
|
||||
"Active-turn behavior (agent default: steer waits for turn end; 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"
|
||||
? "Message queued for delivery after two quiet seconds and the current turn ends, unless interrupt was requested"
|
||||
: "Message sent, not waiting for completion",
|
||||
},
|
||||
schema: agentSendSchema,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@getpaseo/client",
|
||||
"version": "0.16.2",
|
||||
"version": "0.16.1",
|
||||
"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.2",
|
||||
"@getpaseo/relay": "0.16.2",
|
||||
"@getpaseo/protocol": "0.16.1",
|
||||
"@getpaseo/relay": "0.16.1",
|
||||
"ws": "^8.20.0",
|
||||
"zod": "^4.4.3"
|
||||
},
|
||||
|
||||
@@ -483,7 +483,7 @@ export interface SendMessageOptions {
|
||||
sourceAgentServerId?: string;
|
||||
sessionMode?: string;
|
||||
messageId?: string;
|
||||
/** What happens when the agent is mid-turn. The daemon interrupts the turn when omitted. */
|
||||
/** Agent sources wait for turn end unless interrupt is explicit. Human sources default to interrupt. */
|
||||
activeTurnBehavior?: ActiveTurnBehavior;
|
||||
images?: Array<{ data: string; mimeType: string }>;
|
||||
attachments?: SendAgentMessageRequest["attachments"];
|
||||
|
||||
@@ -11,6 +11,9 @@ 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,24 +41,16 @@ 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(
|
||||
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);`,
|
||||
),
|
||||
main,
|
||||
`const { app } = require("electron"); app.setPath("userData", ${JSON.stringify(path.join(root, "user-data"))}); app.whenReady().then(() => { global.lifecycle = require(${JSON.stringify(managerPath)}); });`,
|
||||
);
|
||||
let desktop;
|
||||
let captured;
|
||||
async function openDesktop(entry = main) {
|
||||
async function openDesktop() {
|
||||
desktop = await electron.launch({
|
||||
args: ["--no-sandbox", "--ozone-platform=headless", entry],
|
||||
args: ["--no-sandbox", "--ozone-platform=headless", main],
|
||||
env: {
|
||||
...env,
|
||||
PASEO_LISTEN: "127.0.0.1:1",
|
||||
@@ -86,31 +78,27 @@ async function command(name, args) {
|
||||
);
|
||||
}
|
||||
try {
|
||||
// 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.
|
||||
// Simulate a legacy independent launch that carries the old Desktop flag.
|
||||
const launch = await startDaemonInstance({
|
||||
home,
|
||||
command: process.execPath,
|
||||
args: [path.join(repo, "packages/server/dist/scripts/supervisor-entrypoint.js")],
|
||||
env: { ...env, PASEO_DESKTOP_MANAGED: "1" },
|
||||
env,
|
||||
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, false);
|
||||
assert.equal(attached.desktopManaged, true);
|
||||
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(
|
||||
@@ -146,37 +134,18 @@ try {
|
||||
desktop = null;
|
||||
process.kill(captured.pid, 0);
|
||||
await openDesktop();
|
||||
// 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" });
|
||||
assert.equal((await command("start_desktop_daemon")).ownedByDesktop, false);
|
||||
await command("stop_desktop_daemon", { reason: "quit" });
|
||||
process.kill(captured.pid, 0);
|
||||
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");
|
||||
await command("stop_desktop_daemon", {
|
||||
reason: "manual_ipc",
|
||||
pid: captured.pid,
|
||||
startedAt: captured.startedAt,
|
||||
});
|
||||
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;
|
||||
@@ -226,7 +195,7 @@ try {
|
||||
);
|
||||
}
|
||||
console.log(
|
||||
"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.",
|
||||
"PASS: attached legacy daemon survives automatic actions; explicit captured stop, owned launch, managed settings, worker restart, and next-session attachment.",
|
||||
);
|
||||
} finally {
|
||||
await closeDesktop();
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
import type { Page } from "@playwright/test";
|
||||
import { test, expect } from "../../app/e2e/support/fixtures";
|
||||
import { gotoAppShell } from "../../app/e2e/support/helpers/app";
|
||||
|
||||
// Windows and Linux draw their window controls top-right, so the desktop sidebar has no
|
||||
// chrome row of its own. Its window-drag surface is the strip above the navigation rows.
|
||||
const CUSTOM_CHROME_HOSTS = [
|
||||
{ platform: "linux", windowChromeMode: "custom-linux" },
|
||||
{ platform: "win32", windowChromeMode: "custom-windows" },
|
||||
] as const;
|
||||
|
||||
async function installDesktopHost(
|
||||
page: Page,
|
||||
host: (typeof CUSTOM_CHROME_HOSTS)[number],
|
||||
): Promise<void> {
|
||||
await page.addInitScript((desktopHost) => {
|
||||
window.paseoDesktop = {
|
||||
...desktopHost,
|
||||
events: { on: () => () => {} },
|
||||
invoke: async (command: string) => {
|
||||
if (command === "get_desktop_settings") {
|
||||
return {
|
||||
releaseChannel: "stable",
|
||||
daemon: { manageBuiltInDaemon: true, keepRunningAfterQuit: true },
|
||||
};
|
||||
}
|
||||
return null;
|
||||
},
|
||||
};
|
||||
}, host);
|
||||
}
|
||||
|
||||
async function sidebarDragGeometry(page: Page) {
|
||||
const navScroll = page.locator('[data-testid="sidebar-nav-scroll"]:visible').first();
|
||||
await expect(navScroll).toBeVisible();
|
||||
return navScroll.evaluate((node) => {
|
||||
const nav = node.getBoundingClientRect();
|
||||
const dragRegions = [];
|
||||
for (const element of document.querySelectorAll<HTMLElement>("*")) {
|
||||
if (getComputedStyle(element).getPropertyValue("-webkit-app-region") !== "drag") continue;
|
||||
const rect = element.getBoundingClientRect();
|
||||
const overSidebar = rect.left < nav.right && rect.right > nav.left;
|
||||
if (overSidebar && rect.height > 0) dragRegions.push({ top: rect.top, bottom: rect.bottom });
|
||||
}
|
||||
return { navTop: nav.top, navBottom: nav.bottom, dragRegions };
|
||||
});
|
||||
}
|
||||
|
||||
for (const host of CUSTOM_CHROME_HOSTS) {
|
||||
test.describe(`Desktop sidebar on ${host.platform}`, () => {
|
||||
test.use({ viewport: { width: 1280, height: 480 } });
|
||||
|
||||
test("keeps a window drag strip above the scrolling navigation", async ({ page }) => {
|
||||
await installDesktopHost(page, host);
|
||||
await gotoAppShell(page);
|
||||
|
||||
const geometry = await sidebarDragGeometry(page);
|
||||
expect(geometry.dragRegions).not.toEqual([]);
|
||||
for (const region of geometry.dragRegions) {
|
||||
expect(region.bottom).toBeLessThanOrEqual(geometry.navTop + 1);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@getpaseo/desktop",
|
||||
"version": "0.16.2",
|
||||
"version": "0.16.1",
|
||||
"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.desktopManaged) return false;
|
||||
if (!current.ownedByDesktop) return false;
|
||||
const appVersion = normalizeVersion(resolveDesktopAppVersion());
|
||||
const daemonVersion = normalizeVersion(current.version);
|
||||
return Boolean(appVersion && daemonVersion && appVersion !== daemonVersion);
|
||||
@@ -336,13 +336,12 @@ export async function stopDesktopDaemon(
|
||||
): Promise<DesktopDaemonStatus> {
|
||||
const home = getPaseoHome();
|
||||
const instance = await readDaemonInstance(home);
|
||||
const launchedThisSession = Boolean(
|
||||
const owned = Boolean(
|
||||
instance &&
|
||||
ownedLaunch &&
|
||||
ownedLaunch.home === home &&
|
||||
isSameDaemonInstance(instance, ownedLaunch.instance),
|
||||
);
|
||||
const owned = launchedThisSession || (await replacesDesktopDaemon(reason, instance));
|
||||
const explicit =
|
||||
reason === "manual_ipc" &&
|
||||
confirmedInstance &&
|
||||
@@ -362,28 +361,10 @@ export async function stopDesktopDaemon(
|
||||
keepTerminals,
|
||||
});
|
||||
await stopCapturedDaemon({ home, instance, reason, keepTerminals });
|
||||
if (launchedThisSession) ownedLaunch = null;
|
||||
if (owned) 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;
|
||||
@@ -447,7 +428,7 @@ export function keepsTerminalsOnStop(
|
||||
platform: NodeJS.Platform,
|
||||
): boolean {
|
||||
if (platform === "win32") return false;
|
||||
return isReplacement(reason);
|
||||
return reason === "app_update" || reason === "version_mismatch";
|
||||
}
|
||||
|
||||
async function restartDaemon(): Promise<DesktopDaemonStatus> {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@getpaseo/expo-two-way-audio",
|
||||
"version": "0.16.2",
|
||||
"version": "0.16.1",
|
||||
"description": "Native module for two way audio streaming",
|
||||
"keywords": [
|
||||
"ExpoTwoWayAudio",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@getpaseo/highlight",
|
||||
"version": "0.16.2",
|
||||
"version": "0.16.1",
|
||||
"license": "Apache-2.0",
|
||||
"files": [
|
||||
"dist",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@getpaseo/plugin",
|
||||
"version": "0.16.2",
|
||||
"version": "0.16.1",
|
||||
"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.2",
|
||||
"@getpaseo/protocol": "0.16.2",
|
||||
"@getpaseo/client": "0.16.1",
|
||||
"@getpaseo/protocol": "0.16.1",
|
||||
"@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.2",
|
||||
"@getpaseo/protocol": "0.16.2",
|
||||
"@getpaseo/client": "0.16.1",
|
||||
"@getpaseo/protocol": "0.16.1",
|
||||
"react": ">=19.1.0 <20",
|
||||
"react-native": ">=0.81.5",
|
||||
"zod": "^4.4.3"
|
||||
|
||||
@@ -88,6 +88,8 @@ 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.2",
|
||||
"version": "0.16.1",
|
||||
"description": "Paseo shared protocol schemas and wire types",
|
||||
"license": "Apache-2.0",
|
||||
"files": [
|
||||
|
||||
@@ -921,6 +921,8 @@ export const AgentSnapshotPayloadSchema = z.object({
|
||||
lastUserMessageAt: z.string().nullable(),
|
||||
status: AgentStatusSchema,
|
||||
backgroundWork: z.object({ count: z.number().int().nonnegative() }).optional(),
|
||||
/** Provider subagents of this agent still running. Absent when none run or on older daemons. */
|
||||
runningProviderSubagents: z.object({ count: z.number().int().nonnegative() }).optional(),
|
||||
activeTurn: AgentActiveTurnPayloadSchema.nullable().optional(),
|
||||
capabilities: AgentCapabilityFlagsSchema,
|
||||
currentModeId: z.string().nullable(),
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@getpaseo/relay",
|
||||
"version": "0.16.2",
|
||||
"version": "0.16.1",
|
||||
"description": "Paseo relay for bridging daemon and client connections",
|
||||
"license": "Apache-2.0",
|
||||
"files": [
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@getpaseo/server",
|
||||
"version": "0.16.2",
|
||||
"version": "0.16.1",
|
||||
"description": "Paseo backend server",
|
||||
"license": "Apache-2.0",
|
||||
"files": [
|
||||
@@ -109,11 +109,11 @@
|
||||
"@agentclientprotocol/sdk": "^0.17.1",
|
||||
"@anthropic-ai/claude-agent-sdk": "0.3.326",
|
||||
"@anthropic-ai/sdk": "^0.104.2",
|
||||
"@getpaseo/client": "0.16.2",
|
||||
"@getpaseo/highlight": "0.16.2",
|
||||
"@getpaseo/plugin": "0.16.2",
|
||||
"@getpaseo/protocol": "0.16.2",
|
||||
"@getpaseo/relay": "0.16.2",
|
||||
"@getpaseo/client": "0.16.1",
|
||||
"@getpaseo/highlight": "0.16.1",
|
||||
"@getpaseo/plugin": "0.16.1",
|
||||
"@getpaseo/protocol": "0.16.1",
|
||||
"@getpaseo/relay": "0.16.1",
|
||||
"@isaacs/ttlcache": "^2.1.4",
|
||||
"@modelcontextprotocol/sdk": "1.29.0",
|
||||
"@opencode-ai/sdk": "1.14.46",
|
||||
|
||||
@@ -14,18 +14,19 @@ const BASE_RECORD: StoredAgentRecord = {
|
||||
config: null,
|
||||
};
|
||||
|
||||
const ARCHIVE = {
|
||||
archivedAt: "2025-01-03T00:00:00.000Z",
|
||||
updatedAt: "2025-01-03T00:00:00.000Z",
|
||||
};
|
||||
|
||||
test("archives a stored agent without changing terminal statuses", () => {
|
||||
const statuses: Array<StoredAgentRecord["lastStatus"]> = ["idle", "error", "closed"];
|
||||
|
||||
for (const status of statuses) {
|
||||
const archived = buildArchivedAgentRecord(
|
||||
{ ...BASE_RECORD, lastStatus: status },
|
||||
{ archivedAt: "2025-01-03T00:00:00.000Z" },
|
||||
);
|
||||
const archived = buildArchivedAgentRecord({ ...BASE_RECORD, lastStatus: status }, ARCHIVE);
|
||||
|
||||
expect(archived.lastStatus).toBe(status);
|
||||
expect(archived.archivedAt).toBe("2025-01-03T00:00:00.000Z");
|
||||
expect(archived.updatedAt).toBe(BASE_RECORD.updatedAt);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -33,10 +34,7 @@ test("archives busy stored agents as idle", () => {
|
||||
const statuses: Array<StoredAgentRecord["lastStatus"]> = ["initializing", "running"];
|
||||
|
||||
for (const status of statuses) {
|
||||
const archived = buildArchivedAgentRecord(
|
||||
{ ...BASE_RECORD, lastStatus: status },
|
||||
{ archivedAt: "2025-01-03T00:00:00.000Z" },
|
||||
);
|
||||
const archived = buildArchivedAgentRecord({ ...BASE_RECORD, lastStatus: status }, ARCHIVE);
|
||||
|
||||
expect(archived.lastStatus).toBe("idle");
|
||||
}
|
||||
@@ -50,7 +48,7 @@ test("clears persisted attention when archiving", () => {
|
||||
attentionReason: "finished",
|
||||
attentionTimestamp: "2025-01-02T12:00:00.000Z",
|
||||
},
|
||||
{ archivedAt: "2025-01-03T00:00:00.000Z" },
|
||||
ARCHIVE,
|
||||
);
|
||||
|
||||
expect(archived).toMatchObject({
|
||||
@@ -60,11 +58,19 @@ test("clears persisted attention when archiving", () => {
|
||||
});
|
||||
});
|
||||
|
||||
test("can stamp updatedAt to the archive timestamp", () => {
|
||||
const archived = buildArchivedAgentRecord(BASE_RECORD, {
|
||||
archivedAt: "2025-01-03T00:00:00.000Z",
|
||||
updatedAt: "2025-01-03T00:00:00.000Z",
|
||||
});
|
||||
test("moves updatedAt to the archive time", () => {
|
||||
const archived = buildArchivedAgentRecord(BASE_RECORD, ARCHIVE);
|
||||
|
||||
expect(archived.updatedAt).toBe("2025-01-03T00:00:00.000Z");
|
||||
});
|
||||
|
||||
test("keeps a later updatedAt when the archive time is earlier", () => {
|
||||
// Putting an original archive back after a failed unarchive must not move updatedAt backwards.
|
||||
const archived = buildArchivedAgentRecord(
|
||||
{ ...BASE_RECORD, updatedAt: "2025-01-04T00:00:00.000Z" },
|
||||
ARCHIVE,
|
||||
);
|
||||
|
||||
expect(archived.archivedAt).toBe("2025-01-03T00:00:00.000Z");
|
||||
expect(archived.updatedAt).toBe("2025-01-04T00:00:00.000Z");
|
||||
});
|
||||
|
||||
@@ -3,19 +3,19 @@ import type { StoredAgentRecord } from "./agent-storage.js";
|
||||
export type ArchivedStoredAgentRecord = StoredAgentRecord & { archivedAt: string };
|
||||
|
||||
interface BuildArchivedAgentRecordOptions {
|
||||
archivedAt?: string;
|
||||
updatedAt?: string;
|
||||
archivedAt: string;
|
||||
/** When this archive happened. Re-archiving keeps the original archivedAt but still records it. */
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
export function buildArchivedAgentRecord(
|
||||
record: StoredAgentRecord,
|
||||
options?: BuildArchivedAgentRecordOptions,
|
||||
options: BuildArchivedAgentRecordOptions,
|
||||
): ArchivedStoredAgentRecord {
|
||||
const archivedAt = options?.archivedAt ?? new Date().toISOString();
|
||||
return {
|
||||
...record,
|
||||
archivedAt,
|
||||
updatedAt: options?.updatedAt ?? record.updatedAt,
|
||||
archivedAt: options.archivedAt,
|
||||
updatedAt: latestTimestamp(record.updatedAt, options.updatedAt),
|
||||
lastStatus: normalizeArchivedStatus(record.lastStatus),
|
||||
requiresAttention: false,
|
||||
attentionReason: null,
|
||||
@@ -23,6 +23,13 @@ export function buildArchivedAgentRecord(
|
||||
};
|
||||
}
|
||||
|
||||
// Archiving is the agent's latest change. An earlier archive time (an original archive put back
|
||||
// after a failed unarchive) keeps the newer updatedAt, since clients drop an agent update that is
|
||||
// older than the one they hold.
|
||||
function latestTimestamp(current: string, archiveTime: string): string {
|
||||
return Date.parse(archiveTime) > Date.parse(current) ? archiveTime : current;
|
||||
}
|
||||
|
||||
function normalizeArchivedStatus(
|
||||
status: StoredAgentRecord["lastStatus"],
|
||||
): StoredAgentRecord["lastStatus"] {
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -29,6 +29,7 @@ import { z } from "zod";
|
||||
import type { TerminalManager } from "../../terminal/terminal-manager.js";
|
||||
|
||||
import {
|
||||
AgentTurnStartCanceledError,
|
||||
getAgentStreamEventTurnId,
|
||||
type AgentCapabilityFlags,
|
||||
type AgentClient,
|
||||
@@ -92,6 +93,7 @@ import {
|
||||
import { limitAgentTimelineItemContent } from "./agent-timeline-content.js";
|
||||
import {
|
||||
AgentRunState,
|
||||
type ForegroundPromptStart,
|
||||
type ForegroundTurnWaiter,
|
||||
type PendingForegroundRun,
|
||||
} from "./agent-run-state.js";
|
||||
@@ -634,7 +636,12 @@ function normalizePersistenceForConfig(
|
||||
if (!handle) {
|
||||
return null;
|
||||
}
|
||||
const { mcpServers: _launchMcpServers, ...metadata } = handle.metadata ?? {};
|
||||
const {
|
||||
mcpServers: _launchMcpServers,
|
||||
pluginAppendSystemPrompt: _pluginAppendSystemPrompt,
|
||||
daemonAppendSystemPrompt: _daemonAppendSystemPrompt,
|
||||
...metadata
|
||||
} = handle.metadata ?? {};
|
||||
return {
|
||||
...handle,
|
||||
metadata: {
|
||||
@@ -1117,6 +1124,10 @@ 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) {
|
||||
@@ -1445,6 +1456,12 @@ export class AgentManager {
|
||||
return this.backgroundWork.summary(agentId);
|
||||
}
|
||||
|
||||
/** Undefined when none of the agent's provider subagents is running. */
|
||||
getRunningProviderSubagentSummary(agentId: string): { count: number } | undefined {
|
||||
const count = this.providerSubagents.countRunning(agentId);
|
||||
return count > 0 ? { count } : undefined;
|
||||
}
|
||||
|
||||
private clearBackgroundWork(agentId: string): void {
|
||||
const items = this.backgroundWork.clear(agentId);
|
||||
if (items) this.dispatch({ type: "background_work", agentId, items });
|
||||
@@ -1727,7 +1744,10 @@ export class AgentManager {
|
||||
...(record ? { metadata: record.metadata, attention: extractAttention(record) } : {}),
|
||||
workspaceId,
|
||||
launchEnv,
|
||||
persistence: handle,
|
||||
persistence:
|
||||
purpose === "interactive" && session.persistenceUpdatedOnResume
|
||||
? (session.describePersistence() ?? handle)
|
||||
: handle,
|
||||
restoring: true,
|
||||
});
|
||||
}
|
||||
@@ -2118,7 +2138,7 @@ export class AgentManager {
|
||||
!this.foregroundMutationTails.has(agent.id) &&
|
||||
!this.replacementMutationTails.has(agent.id) &&
|
||||
!this.sessionEventTails.has(agent.id) &&
|
||||
!this.providerSubagents.list(agent.id).some((child) => child.status === "running")
|
||||
this.providerSubagents.countRunning(agent.id) === 0
|
||||
);
|
||||
}
|
||||
|
||||
@@ -2338,7 +2358,7 @@ export class AgentManager {
|
||||
|
||||
private async persistArchivedRecord(
|
||||
record: StoredAgentRecord,
|
||||
options: { archivedAt: string; updatedAt?: string },
|
||||
options: { archivedAt: string; updatedAt: string },
|
||||
): Promise<ArchivedStoredAgentRecord> {
|
||||
const archivedRecord = buildArchivedAgentRecord(record, options);
|
||||
await this.requireRegistry().upsert(archivedRecord);
|
||||
@@ -2858,7 +2878,11 @@ export class AgentManager {
|
||||
throw new Error(`Agent not found: ${agentId}`);
|
||||
}
|
||||
|
||||
const nextRecord = await this.persistArchivedRecord(record, { archivedAt });
|
||||
// Archiving is the agent's latest change, as markRecordArchived records it for a loaded agent.
|
||||
const nextRecord = await this.persistArchivedRecord(record, {
|
||||
archivedAt,
|
||||
updatedAt: archivedAt,
|
||||
});
|
||||
|
||||
await this.syncNativeArchiveState(record.provider, record.persistence, "archive");
|
||||
|
||||
@@ -3030,6 +3054,7 @@ 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);
|
||||
@@ -3049,6 +3074,7 @@ export class AgentManager {
|
||||
if (!handler) {
|
||||
return false;
|
||||
}
|
||||
onAccepted?.();
|
||||
this.touchUpdatedAt(agent);
|
||||
if (options?.clientMessageId) {
|
||||
this.recordSubmittedPrompt(agent, prompt, options.clientMessageId, "accepted");
|
||||
@@ -3125,7 +3151,7 @@ export class AgentManager {
|
||||
pendingRun: PendingForegroundRun;
|
||||
prompt: AgentPromptInput;
|
||||
options?: AgentRunOptions;
|
||||
}): Promise<string> {
|
||||
}): Promise<string | null> {
|
||||
const { agent, agentId, pendingRun, prompt, options } = params;
|
||||
try {
|
||||
const result = await agent.session.startTurn(prompt, options);
|
||||
@@ -3134,11 +3160,32 @@ export class AgentManager {
|
||||
}
|
||||
return result.turnId;
|
||||
} catch (error) {
|
||||
if (error instanceof AgentTurnStartCanceledError) {
|
||||
if (!pendingRun.settled) {
|
||||
if (options?.clientMessageId) {
|
||||
this.recordSubmittedPrompt(agent, prompt, options.clientMessageId, "rejected", {
|
||||
messageId: options.clientMessageId,
|
||||
});
|
||||
}
|
||||
await this.handleStreamEvent(agent, {
|
||||
type: "turn_canceled",
|
||||
provider: agent.provider,
|
||||
reason: "interrupted",
|
||||
});
|
||||
this.finalizeForegroundTurn(agent);
|
||||
this.runs.settleForegroundRun(agentId, pendingRun.token);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
if (pendingRun.settled) {
|
||||
throw error;
|
||||
}
|
||||
if (isStaleProviderSessionError(error)) {
|
||||
this.runs.settleForegroundStart(pendingRun, { status: "failed", error: error.message });
|
||||
this.runs.settleForegroundStart(pendingRun, {
|
||||
status: "failed",
|
||||
error: error.message,
|
||||
stale: true,
|
||||
});
|
||||
agent.pendingReplacement = false;
|
||||
if (!agent.activeForegroundTurnId) agent.lifecycle = "idle";
|
||||
this.runs.settleForegroundRun(agentId, pendingRun.token);
|
||||
@@ -3194,15 +3241,17 @@ export class AgentManager {
|
||||
agentId: string,
|
||||
prompt: AgentPromptInput,
|
||||
options?: AgentRunOptions,
|
||||
promptStart?: ForegroundPromptStart,
|
||||
): AsyncGenerator<AgentStreamEvent> {
|
||||
await this.ensureInteractiveSession(agentId);
|
||||
yield* this.streamAgent(agentId, prompt, options);
|
||||
yield* this.streamAgent(agentId, prompt, options, promptStart);
|
||||
}
|
||||
|
||||
private async *streamAfterRuntimeCollection(
|
||||
agentId: string,
|
||||
prompt: AgentPromptInput,
|
||||
options?: AgentRunOptions,
|
||||
promptStart?: ForegroundPromptStart,
|
||||
): AsyncGenerator<AgentStreamEvent> {
|
||||
await this.waitForAgentClose(agentId);
|
||||
await ensureAgentLoaded(agentId, {
|
||||
@@ -3210,19 +3259,20 @@ export class AgentManager {
|
||||
agentStorage: this.requireRegistry(),
|
||||
logger: this.logger,
|
||||
});
|
||||
yield* this.streamAgent(agentId, prompt, options);
|
||||
yield* this.streamAgent(agentId, prompt, options, promptStart);
|
||||
}
|
||||
|
||||
streamAgent(
|
||||
agentId: string,
|
||||
prompt: AgentPromptInput,
|
||||
options?: AgentRunOptions,
|
||||
promptStart?: ForegroundPromptStart,
|
||||
): AsyncGenerator<AgentStreamEvent> {
|
||||
if (this.collectingRuntimes.has(agentId) || (!this.agents.has(agentId) && this.registry))
|
||||
return this.streamAfterRuntimeCollection(agentId, prompt, options);
|
||||
return this.streamAfterRuntimeCollection(agentId, prompt, options, promptStart);
|
||||
const existingAgent = this.requireSessionAgent(agentId);
|
||||
if (this.historySessions.has(existingAgent.session))
|
||||
return this.streamAfterHistoryLoad(agentId, prompt, options);
|
||||
return this.streamAfterHistoryLoad(agentId, prompt, options, promptStart);
|
||||
this.logger.trace(
|
||||
{
|
||||
agentId,
|
||||
@@ -3257,9 +3307,10 @@ export class AgentManager {
|
||||
agent.lastError = undefined;
|
||||
|
||||
const pendingRun = this.runs.createPendingRun(agentId);
|
||||
promptStart?.bind(pendingRun);
|
||||
|
||||
const streamForwarder = async function* streamForwarder(this: AgentManager) {
|
||||
let turnId: string;
|
||||
let turnId: string | null;
|
||||
let turnStream: ReturnType<AgentRunState["createTurnStream"]> | null = null;
|
||||
turnId = await this.startPendingForegroundTurn({
|
||||
agent,
|
||||
@@ -3268,6 +3319,15 @@ export class AgentManager {
|
||||
prompt,
|
||||
options,
|
||||
});
|
||||
if (turnId === null) {
|
||||
const canceledEvent: AgentStreamEvent = {
|
||||
type: "turn_canceled",
|
||||
provider: agent.provider,
|
||||
reason: "interrupted",
|
||||
};
|
||||
yield canceledEvent;
|
||||
return;
|
||||
}
|
||||
|
||||
if (isReplacement) {
|
||||
agent.pendingReplacement = false;
|
||||
@@ -3422,9 +3482,10 @@ export class AgentManager {
|
||||
agentId: string,
|
||||
prompt: AgentPromptInput,
|
||||
options?: AgentRunOptions,
|
||||
promptStart?: ForegroundPromptStart,
|
||||
): Promise<AsyncGenerator<AgentStreamEvent>> {
|
||||
this.requireSessionAgent(agentId);
|
||||
return this.replaceRunInForegroundLane(agentId, prompt, options);
|
||||
return this.replaceRunInForegroundLane(agentId, prompt, options, promptStart);
|
||||
}
|
||||
|
||||
async steerAgentRun(
|
||||
@@ -3465,6 +3526,7 @@ export class AgentManager {
|
||||
agentId: string,
|
||||
prompt: AgentPromptInput,
|
||||
options?: AgentSteerOptions,
|
||||
promptStart?: ForegroundPromptStart,
|
||||
): Promise<ActiveTurnSteerDispatchResult> {
|
||||
// A turn that is still starting has no id to steer yet. Replacing it would drop its
|
||||
// prompt, so wait until it is accepted (or fails) and steer the turn it became.
|
||||
@@ -3512,6 +3574,7 @@ export class AgentManager {
|
||||
expectedTurnId,
|
||||
prompt,
|
||||
stripSteerOptions(options),
|
||||
promptStart,
|
||||
),
|
||||
};
|
||||
}
|
||||
@@ -3577,9 +3640,10 @@ export class AgentManager {
|
||||
expectedTurnId: string,
|
||||
prompt: AgentPromptInput,
|
||||
options?: AgentRunOptions,
|
||||
promptStart?: ForegroundPromptStart,
|
||||
): Promise<AsyncGenerator<AgentStreamEvent>> {
|
||||
this.assertSteerAdmissionOwnsTurn(agent, expectedTurnId);
|
||||
return this.replaceRunInForegroundLane(agent.id, prompt, options, (live) =>
|
||||
return this.replaceRunInForegroundLane(agent.id, prompt, options, promptStart, (live) =>
|
||||
this.assertSteerAdmissionOwnsTurn(live, expectedTurnId),
|
||||
);
|
||||
}
|
||||
@@ -3592,12 +3656,13 @@ export class AgentManager {
|
||||
agentId: string,
|
||||
prompt: AgentPromptInput,
|
||||
options: AgentRunOptions | undefined,
|
||||
promptStart?: ForegroundPromptStart,
|
||||
assertAdmission?: (agent: ActiveManagedAgent) => void,
|
||||
): Promise<AsyncGenerator<AgentStreamEvent>> {
|
||||
// Replacements queue in arrival order; each one holds the foreground lane only while
|
||||
// it cancels and reserves, so Stop is never stuck behind a replacement that is waiting.
|
||||
return this.runQueuedMutation(this.replacementMutationTails, agentId, () =>
|
||||
this.replaceRunWhenAdmitted(agentId, prompt, options, assertAdmission),
|
||||
this.replaceRunWhenAdmitted(agentId, prompt, options, promptStart, assertAdmission),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -3605,6 +3670,7 @@ export class AgentManager {
|
||||
agentId: string,
|
||||
prompt: AgentPromptInput,
|
||||
options: AgentRunOptions | undefined,
|
||||
promptStart?: ForegroundPromptStart,
|
||||
assertAdmission?: (agent: ActiveManagedAgent) => void,
|
||||
): Promise<AsyncGenerator<AgentStreamEvent>> {
|
||||
let stalledStart: PendingForegroundRun | null = null;
|
||||
@@ -3623,7 +3689,7 @@ export class AgentManager {
|
||||
if (!this.hasInFlightRun(agent.id)) {
|
||||
return {
|
||||
status: "reserved" as const,
|
||||
iterator: this.streamAgent(agent.id, prompt, options),
|
||||
iterator: this.streamAgent(agent.id, prompt, options, promptStart),
|
||||
};
|
||||
}
|
||||
agent.pendingReplacement = true;
|
||||
@@ -3637,7 +3703,7 @@ export class AgentManager {
|
||||
}
|
||||
return {
|
||||
status: "reserved" as const,
|
||||
iterator: this.streamAgent(agent.id, prompt, options),
|
||||
iterator: this.streamAgent(agent.id, prompt, options, promptStart),
|
||||
};
|
||||
} catch (error) {
|
||||
agent.pendingReplacement = false;
|
||||
@@ -3828,7 +3894,10 @@ export class AgentManager {
|
||||
}
|
||||
|
||||
async cancelAgentRun(agentId: string): Promise<AgentRunCancellationResult> {
|
||||
return this.runForegroundMutation(agentId, () => this.cancelAgentRunNow(agentId));
|
||||
return this.runForegroundMutation(agentId, () => {
|
||||
this.requireSessionAgent(agentId).pendingReplacement = false;
|
||||
return this.cancelAgentRunNow(agentId);
|
||||
});
|
||||
}
|
||||
|
||||
private async cancelAgentRunNow(agentId: string): Promise<AgentRunCancellationResult> {
|
||||
@@ -5114,6 +5183,9 @@ 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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5383,7 +5455,6 @@ export class AgentManager {
|
||||
!agent.pendingReplacement
|
||||
) {
|
||||
(agent as ActiveManagedAgent).lifecycle = "idle";
|
||||
this.emitState(agent);
|
||||
}
|
||||
void this.refreshRuntimeInfo(agent);
|
||||
}
|
||||
@@ -5424,9 +5495,6 @@ export class AgentManager {
|
||||
options,
|
||||
);
|
||||
this.resolvePendingPermissionsForAgent(agent, event.provider, options, "Turn failed");
|
||||
if (!isForegroundEvent && !agent.activeForegroundTurnId) {
|
||||
this.emitState(agent);
|
||||
}
|
||||
}
|
||||
|
||||
private onStreamTurnCanceled(params: {
|
||||
@@ -5460,9 +5528,6 @@ export class AgentManager {
|
||||
}
|
||||
agent.lastError = undefined;
|
||||
this.resolvePendingPermissionsForAgent(agent, event.provider, options, "Interrupted");
|
||||
if (!isForegroundEvent && !agent.activeForegroundTurnId) {
|
||||
this.emitState(agent);
|
||||
}
|
||||
}
|
||||
|
||||
private onStreamTurnStarted(params: {
|
||||
@@ -6172,6 +6237,7 @@ 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) {
|
||||
@@ -6193,12 +6259,14 @@ 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: {
|
||||
@@ -6245,6 +6313,7 @@ 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
|
||||
? {
|
||||
@@ -6382,3 +6451,9 @@ 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,3 +1,4 @@
|
||||
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";
|
||||
@@ -117,7 +118,6 @@ 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,3 +313,555 @@ 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 type { PromptDispatchDisposition } from "../agent-prompt.js";
|
||||
import { AgentTurnBusyError, 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,6 +21,8 @@ interface Receipt {
|
||||
dispatched: Promise<PromptDispatchDisposition>;
|
||||
}
|
||||
interface Admitted extends Message {
|
||||
sequence: number;
|
||||
outOfBandDeclined: boolean;
|
||||
receipt: Receipt;
|
||||
resolve(disposition: PromptDispatchDisposition): void;
|
||||
reject(error: unknown): void;
|
||||
@@ -30,12 +32,18 @@ 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. */
|
||||
@@ -47,7 +55,7 @@ export interface AgentMessageDelivery {
|
||||
hasPending(recipientId: string): boolean;
|
||||
/** Stop admission, flush pending messages, and await provider dispatch acknowledgments. */
|
||||
close(): Promise<void>;
|
||||
/** Existing completion waits include agent messages admitted before the wait. */
|
||||
/** Completion waits include admitted messages, but return at permission checkpoints. */
|
||||
waitForDispatch(recipientId: string, signal: AbortSignal): Promise<void>;
|
||||
}
|
||||
|
||||
@@ -59,12 +67,14 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
|
||||
const timer = setTimeout(callback, delayMs);
|
||||
return () => clearTimeout(timer);
|
||||
});
|
||||
const pending = new Map<string, { messages: Admitted[]; cancel(): void }>();
|
||||
const pending = new Map<string, { messages: Admitted[]; ready: boolean; 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 dispatch(recipientId: string, messages: Admitted[]): void {
|
||||
function requestFor(recipientId: string, messages: Admitted[]): DispatchRequest {
|
||||
const prompts = messages.map(
|
||||
(message) =>
|
||||
prepareAgentMessage(message.prompt, message.source, message.receipt.messageId).prompt,
|
||||
@@ -74,39 +84,55 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
|
||||
: prompts.flatMap((entry): AgentPromptContentBlock[] =>
|
||||
typeof entry === "string" ? [{ type: "text", text: entry }] : entry,
|
||||
);
|
||||
const request: DispatchRequest = {
|
||||
return {
|
||||
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),
|
||||
onDispatch: (disposition) => {
|
||||
};
|
||||
}
|
||||
|
||||
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 });
|
||||
}
|
||||
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(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;
|
||||
}
|
||||
});
|
||||
const dispatched = previous.catch(() => undefined).then(operation);
|
||||
dispatching.set(recipientId, dispatched);
|
||||
void dispatched
|
||||
.finally(() => {
|
||||
@@ -115,30 +141,121 @@ 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;
|
||||
pending.delete(recipientId);
|
||||
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[][] = [];
|
||||
let group: Admitted[] = [];
|
||||
let mode: string | undefined;
|
||||
for (const message of entry.messages) {
|
||||
for (const message of 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))
|
||||
) {
|
||||
dispatch(recipientId, group);
|
||||
groups.push(group);
|
||||
group = [];
|
||||
mode = undefined;
|
||||
}
|
||||
group.push(message);
|
||||
mode ??= message.sessionMode;
|
||||
}
|
||||
if (group.length) dispatch(recipientId, group);
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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) {
|
||||
@@ -155,17 +272,47 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
|
||||
messageId: message.messageId ?? randomUUID(),
|
||||
dispatched,
|
||||
};
|
||||
const entry = pending.get(message.recipientId) ?? { messages: [], cancel: () => {} };
|
||||
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: () => {},
|
||||
};
|
||||
entry.cancel();
|
||||
entry.messages.push({ ...message, receipt, resolve, reject });
|
||||
entry.ready = false;
|
||||
entry.messages.push({
|
||||
...message,
|
||||
receipt,
|
||||
resolve,
|
||||
reject,
|
||||
sequence: sequence++,
|
||||
outOfBandDeclined: false,
|
||||
});
|
||||
entry.cancel = schedule(2000, () => flush(message.recipientId));
|
||||
pending.set(message.recipientId, entry);
|
||||
return receipt;
|
||||
},
|
||||
async waitForDispatch(recipientId, signal) {
|
||||
signal.throwIfAborted();
|
||||
const admitted =
|
||||
pending.get(recipientId)?.messages.map((message) => message.receipt.dispatched) ?? [];
|
||||
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();
|
||||
});
|
||||
let aborted!: () => void;
|
||||
const cancellation = new Promise<never>((_resolve, reject) => {
|
||||
aborted = () => reject(new DOMException("Wait aborted", "AbortError"));
|
||||
@@ -175,17 +322,22 @@ 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(dispatching.values()).then(() => undefined);
|
||||
closing = Promise.allSettled(
|
||||
[...receipts.values()].flatMap((owned) => [...owned].map((receipt) => receipt.dispatched)),
|
||||
).then(() => undefined);
|
||||
return closing;
|
||||
},
|
||||
};
|
||||
|
||||
@@ -337,6 +337,7 @@ 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: {
|
||||
@@ -387,6 +388,8 @@ describe("toAgentPayload", () => {
|
||||
sessionId: "persist-stored",
|
||||
metadata: {
|
||||
conversationId: "conversation-stored",
|
||||
pluginAppendSystemPrompt: ["plugin instruction"],
|
||||
daemonAppendSystemPrompt: "daemon instruction",
|
||||
mcpServers: {
|
||||
hub: {
|
||||
type: "http",
|
||||
@@ -402,6 +405,8 @@ describe("toAgentPayload", () => {
|
||||
|
||||
expect(record.persistence?.metadata).toEqual({
|
||||
conversationId: "conversation-stored",
|
||||
pluginAppendSystemPrompt: ["plugin instruction"],
|
||||
daemonAppendSystemPrompt: "daemon instruction",
|
||||
mcpServers: {
|
||||
hub: {
|
||||
type: "http",
|
||||
|
||||
@@ -495,6 +495,9 @@ 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;
|
||||
}
|
||||
|
||||
@@ -15,6 +15,7 @@ import { join } from "node:path";
|
||||
import { createTestLogger } from "../../test-utils/test-logger.js";
|
||||
import { AgentManager } from "./agent-manager.js";
|
||||
import { waitForAgentRunStartWithTimeout } from "./agent-prompt.js";
|
||||
import { ForegroundPromptStart } from "./agent-run-state.js";
|
||||
import type {
|
||||
AgentClient,
|
||||
AgentRunResult,
|
||||
@@ -161,7 +162,7 @@ class SlowStartAgentClient implements AgentClient {
|
||||
async function createRunStartScenario(startDelayMs: number | null): Promise<{
|
||||
agentManager: AgentManager;
|
||||
agentId: string;
|
||||
startRun: () => Promise<void>;
|
||||
startRun: () => Promise<{ started: Promise<void> }>;
|
||||
cleanup: () => Promise<void>;
|
||||
}> {
|
||||
const workdir = mkdtempSync(join(tmpdir(), "agent-run-start-budget-"));
|
||||
@@ -178,14 +179,16 @@ async function createRunStartScenario(startDelayMs: number | null): Promise<{
|
||||
return {
|
||||
agentManager,
|
||||
agentId: snapshot.id,
|
||||
// streamAgent registers the pending run synchronously, so the wait always observes it.
|
||||
// Returns the sender's start, bound to the run streamAgent registers.
|
||||
startRun: async () => {
|
||||
const run = agentManager.streamAgent(snapshot.id, "start the run");
|
||||
const start = new ForegroundPromptStart(snapshot.id);
|
||||
const run = agentManager.streamAgent(snapshot.id, "start the run", undefined, start);
|
||||
drained = (async () => {
|
||||
for await (const _event of run) {
|
||||
// Drain whatever the turn produces.
|
||||
}
|
||||
})().catch(() => undefined);
|
||||
return { started: start.started };
|
||||
},
|
||||
cleanup: async () => {
|
||||
// Release any turn still held open, then close. The drain is deliberately not
|
||||
@@ -207,8 +210,8 @@ test("waiting for a run start outlasts the slowest provider startup budget", asy
|
||||
vi.useFakeTimers();
|
||||
|
||||
try {
|
||||
await scenario.startRun();
|
||||
const wait = waitForAgentRunStartWithTimeout(scenario.agentManager, scenario.agentId);
|
||||
const { started } = await scenario.startRun();
|
||||
const wait = waitForAgentRunStartWithTimeout(scenario.agentManager, scenario.agentId, started);
|
||||
let settled = false;
|
||||
const markSettled = () => {
|
||||
settled = true;
|
||||
@@ -233,8 +236,8 @@ test("waiting for a run start still gives up at the run start budget", async ()
|
||||
vi.useFakeTimers();
|
||||
|
||||
try {
|
||||
await scenario.startRun();
|
||||
const wait = waitForAgentRunStartWithTimeout(scenario.agentManager, scenario.agentId);
|
||||
const { started } = await scenario.startRun();
|
||||
const wait = waitForAgentRunStartWithTimeout(scenario.agentManager, scenario.agentId, started);
|
||||
const rejection = expect(wait).rejects.toThrow(
|
||||
"codex run did not start within 60 seconds (phase: run start)",
|
||||
);
|
||||
|
||||
@@ -3,6 +3,7 @@ import type { Logger } from "pino";
|
||||
|
||||
import type { AgentPromptInput, AgentRunOptions } from "./agent-sdk-types.js";
|
||||
import type { AgentManager, ManagedAgent } from "./agent-manager.js";
|
||||
import { ForegroundPromptStart } from "./agent-run-state.js";
|
||||
import type { AgentStorage } from "./agent-storage.js";
|
||||
import { ensureAgentLoaded } from "./agent-loading.js";
|
||||
import { isStaleProviderSessionError } from "./stale-provider-session-error.js";
|
||||
@@ -23,7 +24,10 @@ 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;
|
||||
@@ -35,11 +39,17 @@ export interface StartAgentRunOptions {
|
||||
|
||||
export type PromptDispatchDisposition = "out_of_band" | "steered" | "turn_started";
|
||||
|
||||
/** A dispatched prompt. A started turn carries its sender's start outcome. */
|
||||
export type PromptDispatchResult =
|
||||
| { disposition: "turn_started"; started: Promise<void> }
|
||||
| { disposition: Exclude<PromptDispatchDisposition, "turn_started"> };
|
||||
|
||||
async function steerOrReplaceActiveRun(
|
||||
agentManager: AgentRunController,
|
||||
agentId: string,
|
||||
prompt: AgentPromptInput,
|
||||
options: StartAgentRunOptions | undefined,
|
||||
promptStart: ForegroundPromptStart,
|
||||
): Promise<
|
||||
| { disposition: "steered" }
|
||||
| {
|
||||
@@ -54,7 +64,12 @@ async function steerOrReplaceActiveRun(
|
||||
const steerOptions = options.clearPendingPermissions
|
||||
? { ...options.runOptions, clearPendingPermissions: true }
|
||||
: options.runOptions;
|
||||
const result = await agentManager.steerOrReplaceActiveTurn(agentId, prompt, steerOptions);
|
||||
const result = await agentManager.steerOrReplaceActiveTurn(
|
||||
agentId,
|
||||
prompt,
|
||||
steerOptions,
|
||||
promptStart,
|
||||
);
|
||||
if (result.status === "steered") {
|
||||
return { disposition: "steered" };
|
||||
}
|
||||
@@ -69,14 +84,15 @@ async function startOrReplaceRun(
|
||||
agentId: string,
|
||||
prompt: AgentPromptInput,
|
||||
options: StartAgentRunOptions | undefined,
|
||||
promptStart: ForegroundPromptStart,
|
||||
): Promise<{
|
||||
iterator: AsyncGenerator<import("./agent-sdk-types.js").AgentStreamEvent>;
|
||||
replaced: boolean;
|
||||
}> {
|
||||
const replaced = Boolean(options?.replaceRunning && agentManager.hasInFlightRun(agentId));
|
||||
const iterator = replaced
|
||||
? await agentManager.replaceAgentRun(agentId, prompt, options?.runOptions)
|
||||
: agentManager.streamAgent(agentId, prompt, options?.runOptions);
|
||||
? await agentManager.replaceAgentRun(agentId, prompt, options?.runOptions, promptStart)
|
||||
: agentManager.streamAgent(agentId, prompt, options?.runOptions, promptStart);
|
||||
return { iterator, replaced };
|
||||
}
|
||||
|
||||
@@ -94,7 +110,7 @@ export async function startAgentRun(
|
||||
prompt: AgentPromptInput,
|
||||
logger: Logger,
|
||||
options?: StartAgentRunOptions,
|
||||
): Promise<{ disposition: PromptDispatchDisposition }> {
|
||||
): Promise<PromptDispatchResult> {
|
||||
const snapshot = agentManager.getAgent(agentId);
|
||||
logger.trace(
|
||||
{
|
||||
@@ -115,16 +131,25 @@ export async function startAgentRun(
|
||||
options?.onDispatch?.("out_of_band");
|
||||
return { disposition: "out_of_band" };
|
||||
}
|
||||
const promptStart = new ForegroundPromptStart(agentId);
|
||||
try {
|
||||
await agentManager.reloadStalePluginSession(agentId);
|
||||
return await startAgentRunInner(agentManager, agentId, prompt, logger, options);
|
||||
try {
|
||||
await agentManager.reloadStalePluginSession(agentId);
|
||||
return await startAgentRunInner(agentManager, agentId, prompt, logger, options, promptStart);
|
||||
} catch (error) {
|
||||
if (!isStaleProviderSessionError(error)) throw error;
|
||||
logger.info(
|
||||
{ agentId, err: error },
|
||||
"Provider session went stale; reopening from persistence",
|
||||
);
|
||||
// The live session belongs to a retired plugin runtime. Reload swaps in a
|
||||
// fresh session on the current runtime while preserving history and labels.
|
||||
await agentManager.reloadAgentSession(agentId);
|
||||
return await startAgentRunInner(agentManager, agentId, prompt, logger, options, promptStart);
|
||||
}
|
||||
} catch (error) {
|
||||
if (!isStaleProviderSessionError(error)) throw error;
|
||||
logger.info({ agentId, err: error }, "Provider session went stale; reopening from persistence");
|
||||
// The live session belongs to a retired plugin runtime. Reload swaps in a
|
||||
// fresh session on the current runtime while preserving history and labels.
|
||||
await agentManager.reloadAgentSession(agentId);
|
||||
return await startAgentRunInner(agentManager, agentId, prompt, logger, options);
|
||||
promptStart.end();
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -133,17 +158,23 @@ async function startAgentRunInner(
|
||||
agentId: string,
|
||||
prompt: AgentPromptInput,
|
||||
logger: Logger,
|
||||
options?: StartAgentRunOptions,
|
||||
): Promise<{ disposition: PromptDispatchDisposition }> {
|
||||
options: StartAgentRunOptions | undefined,
|
||||
promptStart: ForegroundPromptStart,
|
||||
): Promise<PromptDispatchResult> {
|
||||
const snapshot = agentManager.getAgent(agentId);
|
||||
const steered = await steerOrReplaceActiveRun(agentManager, agentId, prompt, options);
|
||||
const steered = options?.idleOnly
|
||||
? null
|
||||
: await steerOrReplaceActiveRun(agentManager, agentId, prompt, options, promptStart);
|
||||
if (options?.idleOnly && agentManager.hasInFlightRun(agentId)) {
|
||||
throw new AgentTurnBusyError(`Agent ${agentId} is running`);
|
||||
}
|
||||
if (steered?.disposition === "steered") {
|
||||
options?.onDispatch?.("steered");
|
||||
return steered;
|
||||
}
|
||||
const { iterator, replaced } = steered
|
||||
? { iterator: steered.iterator, replaced: true }
|
||||
: await startOrReplaceRun(agentManager, agentId, prompt, options);
|
||||
: await startOrReplaceRun(agentManager, agentId, prompt, options, promptStart);
|
||||
logger.trace(
|
||||
{
|
||||
agentId,
|
||||
@@ -165,7 +196,7 @@ async function startAgentRunInner(
|
||||
"Provider session went stale; reopening from persistence",
|
||||
);
|
||||
await agentManager.reloadAgentSession(agentId);
|
||||
const retry = await startOrReplaceRun(agentManager, agentId, prompt, options);
|
||||
const retry = await startOrReplaceRun(agentManager, agentId, prompt, options, promptStart);
|
||||
await drainAgentRunIterator(retry.iterator);
|
||||
}
|
||||
logger.trace(
|
||||
@@ -187,9 +218,11 @@ async function startAgentRunInner(
|
||||
"agent.session.iterator.error",
|
||||
);
|
||||
logger.error({ err: error, agentId }, "Agent stream failed");
|
||||
} finally {
|
||||
promptStart.end();
|
||||
}
|
||||
})();
|
||||
return { disposition: "turn_started" };
|
||||
return { disposition: "turn_started", started: promptStart.started };
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -210,6 +243,7 @@ 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"];
|
||||
@@ -261,8 +295,9 @@ export interface StartCreatedAgentInitialPromptParams {
|
||||
const AGENT_RUN_START_TIMEOUT_MS = 60_000;
|
||||
|
||||
export async function waitForAgentRunStartWithTimeout(
|
||||
agentManager: AgentManager,
|
||||
agentManager: Pick<AgentManager, "getAgent">,
|
||||
agentId: string,
|
||||
started: Promise<void>,
|
||||
signal?: AbortSignal,
|
||||
): Promise<void> {
|
||||
const provider = agentManager.getAgent(agentId)?.provider ?? "provider";
|
||||
@@ -277,15 +312,28 @@ export async function waitForAgentRunStartWithTimeout(
|
||||
AGENT_RUN_START_TIMEOUT_MS,
|
||||
);
|
||||
|
||||
const abortSignal = signal ? AbortSignal.any([startAbort.signal, signal]) : startAbort.signal;
|
||||
let onAbort: (() => void) | null = null;
|
||||
const aborted = new Promise<never>((_, reject) => {
|
||||
onAbort = () => reject(createStartAbortError(abortSignal.reason));
|
||||
if (abortSignal.aborted) onAbort();
|
||||
else abortSignal.addEventListener("abort", onAbort, { once: true });
|
||||
});
|
||||
try {
|
||||
await agentManager.waitForAgentRunStart(agentId, {
|
||||
signal: signal ? AbortSignal.any([startAbort.signal, signal]) : startAbort.signal,
|
||||
});
|
||||
await Promise.race([started, aborted]);
|
||||
} finally {
|
||||
clearTimeout(startTimeout);
|
||||
if (onAbort) abortSignal.removeEventListener("abort", onAbort);
|
||||
}
|
||||
}
|
||||
|
||||
function createStartAbortError(reason: unknown): Error {
|
||||
let message = "wait_for_agent_start aborted";
|
||||
if (typeof reason === "string") message = reason;
|
||||
else if (reason instanceof Error) message = reason.message;
|
||||
return Object.assign(new Error(message), { name: "AbortError" });
|
||||
}
|
||||
|
||||
async function resolvePromptSource(
|
||||
source: AgentPromptSource | undefined,
|
||||
manager: Pick<AgentManager, "getAgent">,
|
||||
@@ -311,7 +359,7 @@ async function resolvePromptSource(
|
||||
*/
|
||||
export async function sendPromptToAgent(
|
||||
params: SendPromptToAgentParams,
|
||||
): Promise<{ disposition: PromptDispatchDisposition }> {
|
||||
): Promise<PromptDispatchResult> {
|
||||
const source = await resolvePromptSource(params.source, params.agentManager, params.agentStorage);
|
||||
const delivery = prepareAgentMessage(params.prompt, source, params.messageId);
|
||||
return sendPreparedPromptToAgent({
|
||||
@@ -326,14 +374,14 @@ export async function sendPromptToAgent(
|
||||
/** Dispatch daemon-prepared context without reclassifying it as human input. */
|
||||
export async function sendPreparedPromptToAgent(
|
||||
params: Omit<SendPromptToAgentParams, "source" | "messageId">,
|
||||
): Promise<{ disposition: PromptDispatchDisposition }> {
|
||||
): Promise<PromptDispatchResult> {
|
||||
const unarchive = params.unarchive ?? true;
|
||||
|
||||
const record = await params.agentStorage.get(params.agentId);
|
||||
let archivedAtToRestore: string | null = null;
|
||||
if (record?.archivedAt) {
|
||||
if (!unarchive) {
|
||||
return { disposition: "turn_started" };
|
||||
return { disposition: "turn_started", started: Promise.resolve() };
|
||||
}
|
||||
if (await unarchiveAgentState(params.agentStorage, params.agentManager, params.agentId)) {
|
||||
archivedAtToRestore = record.archivedAt;
|
||||
@@ -355,13 +403,17 @@ 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: true,
|
||||
replaceRunning: !params.idleOnly,
|
||||
idleOnly: params.idleOnly,
|
||||
onDispatch: params.onDispatch,
|
||||
activeTurnBehavior: params.activeTurnBehavior,
|
||||
clearPendingPermissions: params.clearPendingPermissions,
|
||||
@@ -395,7 +447,11 @@ export async function startCreatedAgentInitialPrompt(
|
||||
);
|
||||
|
||||
if (dispatchResult.disposition === "turn_started") {
|
||||
await waitForAgentRunStartWithTimeout(params.agentManager, params.agentId);
|
||||
await waitForAgentRunStartWithTimeout(
|
||||
params.agentManager,
|
||||
params.agentId,
|
||||
dispatchResult.started,
|
||||
);
|
||||
}
|
||||
|
||||
const refreshedSnapshot = params.agentManager.getAgent(params.agentId) ?? params.snapshot ?? null;
|
||||
|
||||
@@ -13,7 +13,7 @@ export interface ForegroundTurnWaiter {
|
||||
type ForegroundRunStart =
|
||||
| { status: "pending" }
|
||||
| { status: "started"; turnId: string }
|
||||
| { status: "failed"; error: string };
|
||||
| { status: "failed"; error: string; stale?: true };
|
||||
|
||||
export interface PendingForegroundRun {
|
||||
token: string;
|
||||
@@ -343,3 +343,59 @@ function settleTrackedRun(run: TrackedAgentRun): void {
|
||||
run.settled = true;
|
||||
run.resolveSettled();
|
||||
}
|
||||
|
||||
/**
|
||||
* Follows one sender's prompt to the foreground run that starts it. Each run created for the
|
||||
* prompt, including a stale-session retry, is bound here, so `started` settles for this
|
||||
* sender's prompt and never for another run the agent tracks.
|
||||
*/
|
||||
export class ForegroundPromptStart {
|
||||
readonly started: Promise<void>;
|
||||
private resolveStarted!: () => void;
|
||||
private rejectStarted!: (error: Error) => void;
|
||||
private run: PendingForegroundRun | null = null;
|
||||
private done = false;
|
||||
|
||||
constructor(private readonly agentId: string) {
|
||||
this.started = new Promise<void>((resolve, reject) => {
|
||||
this.resolveStarted = resolve;
|
||||
this.rejectStarted = reject;
|
||||
});
|
||||
// Steered and fire-and-forget dispatches never wait on the start.
|
||||
this.started.catch(() => undefined);
|
||||
}
|
||||
|
||||
/** A run was created for this prompt. */
|
||||
bind(run: PendingForegroundRun): void {
|
||||
this.run = run;
|
||||
void Promise.race([run.turnStartedPromise, run.settledPromise]).then(() =>
|
||||
this.settle(run, { ended: false }),
|
||||
);
|
||||
}
|
||||
|
||||
/** The prompt's dispatch is over; no further run will be created for it. */
|
||||
end(): void {
|
||||
this.settle(this.run, { ended: true });
|
||||
}
|
||||
|
||||
private settle(run: PendingForegroundRun | null, { ended }: { ended: boolean }): void {
|
||||
if (this.done || run !== this.run) return;
|
||||
if (run?.start.status === "started") {
|
||||
this.done = true;
|
||||
this.resolveStarted();
|
||||
return;
|
||||
}
|
||||
// A stale-session failure is retried with a new run; wait for it unless dispatch ended.
|
||||
if (run?.start.status === "failed" && run.start.stale && !ended) return;
|
||||
this.done = true;
|
||||
this.rejectStarted(new Error(this.describeUnstarted(run)));
|
||||
}
|
||||
|
||||
private describeUnstarted(run: PendingForegroundRun | null): string {
|
||||
if (run?.start.status === "failed") return run.start.error;
|
||||
if (run?.settled) {
|
||||
return `Agent ${this.agentId} run was canceled before its turn started; its prompt was not delivered`;
|
||||
}
|
||||
return `Agent ${this.agentId} run finished before starting`;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -528,6 +528,14 @@ export type AgentPermissionResponse =
|
||||
interrupt?: boolean;
|
||||
};
|
||||
|
||||
/** A requested turn was canceled before the provider accepted it. */
|
||||
export class AgentTurnStartCanceledError extends Error {
|
||||
constructor() {
|
||||
super("Turn was canceled before starting");
|
||||
this.name = "AgentTurnStartCanceledError";
|
||||
}
|
||||
}
|
||||
|
||||
export interface AgentRunResult {
|
||||
sessionId: string;
|
||||
finalText: string;
|
||||
@@ -621,6 +629,8 @@ 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;
|
||||
@@ -636,6 +646,8 @@ 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>;
|
||||
@@ -688,6 +700,8 @@ 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;
|
||||
|
||||
@@ -10,6 +10,7 @@ import { AgentManager } from "../agent-manager.js";
|
||||
import { AgentStorage } from "../agent-storage.js";
|
||||
import type { CreatePaseoWorktreeWorkflowResult } from "../../worktree-session.js";
|
||||
import { createAgentCommand } from "./create.js";
|
||||
import { ForegroundPromptStart } from "../agent-run-state.js";
|
||||
import type { ManagedAgent } from "../agent-manager.js";
|
||||
|
||||
const logger = createTestLogger();
|
||||
@@ -89,9 +90,12 @@ test("session create forwards clientMessageId to the initial prompt run options"
|
||||
firstAgentContext: { attachments: [] },
|
||||
});
|
||||
|
||||
expect(streamAgent).toHaveBeenCalledWith("agent-1", "hello from create", {
|
||||
clientMessageId: "msg-create-1",
|
||||
});
|
||||
expect(streamAgent).toHaveBeenCalledWith(
|
||||
"agent-1",
|
||||
"hello from create",
|
||||
{ clientMessageId: "msg-create-1" },
|
||||
expect.any(ForegroundPromptStart),
|
||||
);
|
||||
});
|
||||
|
||||
test("session create validates the requested mode against the provider's modes", async () => {
|
||||
|
||||
@@ -498,3 +498,26 @@ 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,7 +267,9 @@ export function createFinishSubscriptions(deps: Dependencies): FinishSubscriptio
|
||||
continue;
|
||||
}
|
||||
if (signal.aborted) return;
|
||||
await decisions(group);
|
||||
// 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);
|
||||
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. You will get notified when the prompted agent finishes, errors, or needs permission unless notifyOnFinish is false."
|
||||
? "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."
|
||||
: "Dispatch acknowledged. Observe completion using get_agent_status/get_agent_activity or SDK/RPC subscriptions and wait APIs.",
|
||||
});
|
||||
},
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { AgentRunState, ForegroundPromptStart } from "./agent-run-state.js";
|
||||
import {
|
||||
createFinishSubscriptions,
|
||||
createFinishObservation,
|
||||
@@ -172,11 +173,12 @@ 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 (response.structuredContent.deliveryStatus === "queued") {
|
||||
if (awaitDispatch && response.structuredContent.deliveryStatus === "queued") {
|
||||
await toolDeliveries
|
||||
.get(tool)!
|
||||
.waitForDispatch(input.agentId as string, new AbortController().signal);
|
||||
@@ -275,11 +277,19 @@ 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(() => {}),
|
||||
streamAgent: vi.fn(() => (async function* noop() {})()),
|
||||
waitForAgentRunStart: vi.fn().mockResolvedValue(undefined),
|
||||
streamAgent: vi.fn(
|
||||
(agentId: string, _prompt: unknown, _options: unknown, start?: ForegroundPromptStart) => {
|
||||
const runs = new AgentRunState();
|
||||
const run = runs.createPendingRun(agentId);
|
||||
runs.settleForegroundStart(run, { status: "started", turnId: `${agentId}-turn` });
|
||||
start?.bind(run);
|
||||
return (async function* noop() {})();
|
||||
},
|
||||
),
|
||||
respondToPermission: vi.fn(),
|
||||
cancelAgentRun: vi.fn(),
|
||||
getPendingPermissions: vi.fn(),
|
||||
@@ -624,6 +634,12 @@ class FakeBrowserToolsBroker {
|
||||
}
|
||||
|
||||
class BoundaryAgentManagerFake {
|
||||
subscribe() {
|
||||
return () => {};
|
||||
}
|
||||
hasPendingPermissions() {
|
||||
return false;
|
||||
}
|
||||
public getPluginTools(): [] {
|
||||
return [];
|
||||
}
|
||||
@@ -878,8 +894,9 @@ function createPaseoWorktreeForMcpTest(options: {
|
||||
async function createAgentMcpServer(
|
||||
options: Parameters<typeof createAgentMcpServerWithDependencies>[0],
|
||||
subscriptionStore?: FinishSubscriptionStore,
|
||||
schedule?: (delayMs: number, callback: () => void) => () => void,
|
||||
) {
|
||||
const messages = createTestAgentMessages(options);
|
||||
const messages = createTestAgentMessages({ ...options, schedule });
|
||||
const records = new Map<string, FinishSubscription>();
|
||||
const subscriptions = createFinishSubscriptions({
|
||||
store: subscriptionStore ?? {
|
||||
@@ -3678,15 +3695,15 @@ class HeldTurnAgentClient implements AgentClient {
|
||||
|
||||
describe("send_agent_prompt MCP tool", () => {
|
||||
it.each([
|
||||
{ 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 },
|
||||
{ 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 },
|
||||
] as const)(
|
||||
"dispatches behavior $behavior for agent-scoped=$agentScoped, steering available=$available",
|
||||
async ({ agentScoped, behavior, available, steered }) => {
|
||||
async ({ agentScoped, behavior, available }) => {
|
||||
const workdir = await mkdtemp(join(tmpdir(), "mcp-send-behavior-"));
|
||||
const storage = new AgentStorage(join(workdir, "agents"), logger);
|
||||
const client = new HeldTurnAgentClient("codex", true, {
|
||||
@@ -3718,18 +3735,33 @@ describe("send_agent_prompt MCP tool", () => {
|
||||
notifyOnFinish: false,
|
||||
});
|
||||
const originalTurn = manager.getAgent(child.id)!.activeTurnId;
|
||||
const response = await invokeToolWithParsedInput(tool, {
|
||||
agentId: child.id,
|
||||
prompt: "New message",
|
||||
notifyOnFinish: false,
|
||||
...(behavior ? { activeTurnBehavior: behavior } : {}),
|
||||
});
|
||||
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,
|
||||
);
|
||||
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);
|
||||
@@ -3741,18 +3773,16 @@ describe("send_agent_prompt MCP tool", () => {
|
||||
|
||||
it.each([
|
||||
{ rejected: false, priorNotification: false },
|
||||
{ rejected: true, priorNotification: false },
|
||||
{ rejected: false, priorNotification: true },
|
||||
{ rejected: true, priorNotification: false },
|
||||
{ rejected: true, priorNotification: true },
|
||||
])(
|
||||
"buffers completion until steer acknowledgement (rejected: $rejected, prior notification: $priorNotification)",
|
||||
"keeps completion tied to queued dispatch acknowledgement (rejected: $rejected, prior notification: $priorNotification)",
|
||||
async ({ rejected, priorNotification }) => {
|
||||
const workdir = await mkdtemp(join(tmpdir(), "mcp-send-behavior-"));
|
||||
const workdir = await mkdtemp(join(tmpdir(), "mcp-queued-ack-"));
|
||||
const storage = new AgentStorage(join(workdir, "agents"), logger);
|
||||
const client = new HeldTurnAgentClient("codex", true, {
|
||||
steerResult: "accepted",
|
||||
finishDuringSteer: true,
|
||||
rejectSteer: rejected,
|
||||
});
|
||||
const options: HeldTurnOptions = {};
|
||||
const client = new HeldTurnAgentClient("codex", true, options);
|
||||
const manager = new AgentManager({ clients: { codex: client }, registry: storage, logger });
|
||||
let mcpClient: Client | undefined;
|
||||
try {
|
||||
@@ -3774,104 +3804,47 @@ describe("send_agent_prompt MCP tool", () => {
|
||||
logger,
|
||||
});
|
||||
mcpClient = await connectInMemoryMcpClient(server);
|
||||
const send = (input: Record<string, unknown>) =>
|
||||
sendMcpAndAwaitDispatch(mcpClient!, server, input);
|
||||
await send({
|
||||
await sendMcpAndAwaitDispatch(mcpClient, server, {
|
||||
agentId: child.id,
|
||||
prompt: "Original work",
|
||||
notifyOnFinish: priorNotification,
|
||||
});
|
||||
const sending = send({
|
||||
agentId: child.id,
|
||||
prompt: "New message",
|
||||
notifyOnFinish: true,
|
||||
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 },
|
||||
});
|
||||
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",
|
||||
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" },
|
||||
});
|
||||
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));
|
||||
await serverSubscriptions.get(server)!.close();
|
||||
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);
|
||||
@@ -4013,7 +3986,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(spies.agentManager.subscribe).not.toHaveBeenCalled();
|
||||
expect(serverSubscriptionRecords.get(server)!.size).toBe(1);
|
||||
await serverDeliveries
|
||||
.get(server)!
|
||||
.waitForDispatch("child-agent", new AbortController().signal);
|
||||
@@ -4054,7 +4027,7 @@ describe("send_agent_prompt MCP tool", () => {
|
||||
|
||||
await tool.handler(parsed.data as Record<string, unknown>);
|
||||
|
||||
expect(spies.agentManager.subscribe).not.toHaveBeenCalled();
|
||||
expect(serverSubscriptionRecords.get(server)!.size).toBe(0);
|
||||
expect(spies.agentManager.waitForAgentEvent).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
@@ -4097,7 +4070,7 @@ describe("send_agent_prompt MCP tool", () => {
|
||||
notifyOnFinish: false,
|
||||
});
|
||||
|
||||
expect(spies.agentManager.subscribe).not.toHaveBeenCalled();
|
||||
expect(serverSubscriptionRecords.get(server)!.size).toBe(0);
|
||||
expect(spies.agentManager.waitForAgentEvent).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
@@ -4221,11 +4194,15 @@ 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",
|
||||
});
|
||||
const response = await invokeToolWithParsedInput(
|
||||
tool,
|
||||
{
|
||||
agentId: child.id,
|
||||
prompt: "/side-command",
|
||||
activeTurnBehavior: scenario === "out_of_band_interrupt" ? "interrupt" : "steer",
|
||||
},
|
||||
scenario !== "out_of_band",
|
||||
);
|
||||
expect(response.structuredContent).toMatchObject({
|
||||
success: true,
|
||||
deliveryStatus: "queued",
|
||||
@@ -4237,6 +4214,9 @@ 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.");
|
||||
@@ -4244,7 +4224,11 @@ 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" }),
|
||||
invokeToolWithParsedInput(tool, {
|
||||
agentId: child.id,
|
||||
prompt: "Replacement task",
|
||||
activeTurnBehavior: "interrupt",
|
||||
}),
|
||||
).rejects.toThrow("Requested turn could not start");
|
||||
// A later real turn must not inherit a subscription from the rejected dispatch.
|
||||
await invokeToolWithParsedInput(tool, {
|
||||
@@ -4355,6 +4339,7 @@ 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,
|
||||
@@ -4518,7 +4503,7 @@ describe("send_agent_prompt MCP tool to an OMP child", () => {
|
||||
const logger = createTestLogger();
|
||||
const existingCwd = process.cwd();
|
||||
|
||||
async function setupOmpChild() {
|
||||
async function setupOmpChild(schedule?: (delayMs: number, callback: () => void) => () => void) {
|
||||
const workdir = await mkdtemp(join(tmpdir(), "mcp-omp-child-"));
|
||||
const storage = new AgentStorage(join(workdir, "agents"), logger);
|
||||
const parentClient = new HeldTurnAgentClient("claude", false);
|
||||
@@ -4546,13 +4531,17 @@ 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,
|
||||
});
|
||||
const server = await createAgentMcpServer(
|
||||
{
|
||||
agentManager,
|
||||
agentStorage: storage,
|
||||
callerAgentId: parent.id,
|
||||
providerSnapshotManager: createOpenCodeManager().manager,
|
||||
logger,
|
||||
},
|
||||
undefined,
|
||||
schedule,
|
||||
);
|
||||
return {
|
||||
agentManager,
|
||||
storage,
|
||||
@@ -4582,37 +4571,63 @@ describe("send_agent_prompt MCP tool to an OMP child", () => {
|
||||
{ command: "follow-up", streamingBehavior: "followUp" },
|
||||
{ command: "steer", streamingBehavior: "steer" },
|
||||
] as const)(
|
||||
"delivers /$command into a turn OMP started on its own, without aborting it",
|
||||
"delivers /$command to a running OMP child while ordinary messages in the same quiet window wait",
|
||||
async ({ command, streamingBehavior }) => {
|
||||
const { agentManager, storage, workdir, parentClient, ompSession, childId, tool } =
|
||||
await setupOmpChild();
|
||||
let flush!: () => void;
|
||||
const { agentManager, storage, workdir, ompSession, childId, tool } = await setupOmpChild(
|
||||
(_delay, callback) => {
|
||||
flush = callback;
|
||||
return () => {};
|
||||
},
|
||||
);
|
||||
try {
|
||||
ompSession.beginTurn();
|
||||
ompSession.streamAssistantText("background job finished, working on it");
|
||||
await vi.waitFor(() => {
|
||||
expect(agentManager.getAgent(childId)?.activeTurnId).toMatch(/^autonomous-/);
|
||||
});
|
||||
|
||||
const response = await invokeToolWithParsedInput(tool, {
|
||||
agentId: childId,
|
||||
prompt: `/${command} then summarize the logs`,
|
||||
});
|
||||
|
||||
expect(response.structuredContent).toMatchObject({
|
||||
success: true,
|
||||
deliveryStatus: "queued",
|
||||
status: "running",
|
||||
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`,
|
||||
},
|
||||
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",
|
||||
});
|
||||
expect(ompSession.abortRequested).toBe(false);
|
||||
expect(agentManager.getAgent(childId)?.lifecycle).toBe("running");
|
||||
|
||||
ompSession.finishTurn();
|
||||
await expectOneFinishNotification(agentManager, parentClient, childId);
|
||||
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();
|
||||
} finally {
|
||||
await removeAgentStateDir(agentManager, storage, workdir);
|
||||
}
|
||||
|
||||
@@ -1949,7 +1949,11 @@ function mapSessionConfig(
|
||||
return {
|
||||
cwd: config.cwd,
|
||||
env: createProviderEnv({ baseEnv: {}, overlays: [launchContext?.env] }),
|
||||
systemPrompt: combineSystemPrompts(config.systemPrompt, config.daemonAppendSystemPrompt),
|
||||
systemPrompt: combineSystemPrompts(
|
||||
config.systemPrompt,
|
||||
config.daemonAppendSystemPrompt,
|
||||
...(config.pluginAppendSystemPrompt ?? []),
|
||||
),
|
||||
mcpServers: { ...config.mcpServers },
|
||||
toolPolicy: config.toolPolicy
|
||||
? { preapproved: config.toolPolicy.preapproved.map((grant) => ({ ...grant })) }
|
||||
@@ -1968,8 +1972,9 @@ function mapSessionConfig(
|
||||
function combineSystemPrompts(
|
||||
systemPrompt: string | undefined,
|
||||
daemonPrompt: string | undefined,
|
||||
...pluginPrompts: string[]
|
||||
): string | undefined {
|
||||
const parts = [systemPrompt, daemonPrompt].filter(
|
||||
const parts = [systemPrompt, daemonPrompt, ...pluginPrompts].filter(
|
||||
(value): value is string => typeof value === "string" && value.trim().length > 0,
|
||||
);
|
||||
return parts.length > 0 ? parts.join("\n\n") : undefined;
|
||||
|
||||
@@ -448,6 +448,9 @@ export function wrapSessionProvider(provider: AgentProvider, inner: AgentSession
|
||||
get initialTimeline() {
|
||||
return inner.initialTimeline;
|
||||
},
|
||||
get persistenceUpdatedOnResume() {
|
||||
return inner.persistenceUpdatedOnResume;
|
||||
},
|
||||
get controls() {
|
||||
return inner.controls;
|
||||
},
|
||||
|
||||
@@ -54,12 +54,61 @@ describe("ProviderSubagentStore", () => {
|
||||
]);
|
||||
expect(subagents.list("parent-b")[0]).toMatchObject({ provider: "claude", title: "Review" });
|
||||
expect(subagents.deleteParent("parent-a")).toEqual([
|
||||
{ type: "remove", parentAgentId: "parent-a", subagentId: "child-1" },
|
||||
{
|
||||
type: "remove",
|
||||
parentAgentId: "parent-a",
|
||||
subagentId: "child-1",
|
||||
runningCountChanged: false,
|
||||
},
|
||||
]);
|
||||
expect(subagents.list("parent-a")).toEqual([]);
|
||||
expect(subagents.list("parent-b")).toHaveLength(1);
|
||||
});
|
||||
|
||||
test("marks the changes that start or stop one of the parent's running children", () => {
|
||||
const subagents = new ProviderSubagentStore();
|
||||
const runningCountChanged = (event: ReturnType<ProviderSubagentStore["apply"]>) =>
|
||||
event.type === "timeline" ? null : event.runningCountChanged;
|
||||
|
||||
const started = subagents.apply("parent-a", "claude", {
|
||||
type: "upsert",
|
||||
id: "child-1",
|
||||
status: "running",
|
||||
});
|
||||
const progressed = subagents.apply("parent-a", "claude", {
|
||||
type: "upsert",
|
||||
id: "child-1",
|
||||
subtitle: "Reading files",
|
||||
});
|
||||
const finished = subagents.apply("parent-a", "claude", {
|
||||
type: "upsert",
|
||||
id: "child-1",
|
||||
status: "completed",
|
||||
});
|
||||
const finishedRemoved = subagents.apply("parent-a", "claude", {
|
||||
type: "remove",
|
||||
id: "child-1",
|
||||
});
|
||||
subagents.apply("parent-a", "claude", { type: "upsert", id: "child-2", status: "running" });
|
||||
const runningRemoved = subagents.apply("parent-a", "claude", { type: "remove", id: "child-2" });
|
||||
const recorded = subagents.apply("parent-a", "claude", {
|
||||
type: "upsert",
|
||||
id: "child-3",
|
||||
status: "completed",
|
||||
});
|
||||
subagents.apply("parent-a", "claude", { type: "upsert", id: "child-4", status: "running" });
|
||||
|
||||
expect(
|
||||
[started, progressed, finished, finishedRemoved, runningRemoved, recorded].map(
|
||||
runningCountChanged,
|
||||
),
|
||||
).toEqual([true, false, true, false, true, false]);
|
||||
expect(subagents.deleteParent("parent-a")).toEqual([
|
||||
expect.objectContaining({ subagentId: "child-3", runningCountChanged: false }),
|
||||
expect.objectContaining({ subagentId: "child-4", runningCountChanged: true }),
|
||||
]);
|
||||
});
|
||||
|
||||
test("limits oversized provider child tool output before storage", () => {
|
||||
const subagents = new ProviderSubagentStore();
|
||||
const output = "x".repeat(70 * 1024);
|
||||
|
||||
@@ -50,8 +50,12 @@ export type ProviderSubagentInputEvent =
|
||||
}
|
||||
| { type: "remove"; id: string };
|
||||
|
||||
/**
|
||||
* `runningCountChanged` says whether the change started or stopped one of the parent's running
|
||||
* children, which is what the parent agent's snapshot reports.
|
||||
*/
|
||||
export type ProviderSubagentStoreEvent =
|
||||
| { type: "upsert"; subagent: ProviderSubagentDescriptor }
|
||||
| { type: "upsert"; subagent: ProviderSubagentDescriptor; runningCountChanged: boolean }
|
||||
| {
|
||||
type: "timeline";
|
||||
parentAgentId: string;
|
||||
@@ -60,7 +64,7 @@ export type ProviderSubagentStoreEvent =
|
||||
row: AgentTimelineRow;
|
||||
epoch: string;
|
||||
}
|
||||
| { type: "remove"; parentAgentId: string; subagentId: string };
|
||||
| { type: "remove"; parentAgentId: string; subagentId: string; runningCountChanged: boolean };
|
||||
|
||||
function storeKey(parentAgentId: string, subagentId: string): string {
|
||||
return `${parentAgentId}\0${subagentId}`;
|
||||
@@ -86,9 +90,15 @@ export class ProviderSubagentStore {
|
||||
): ProviderSubagentStoreEvent {
|
||||
const key = storeKey(parentAgentId, event.id);
|
||||
if (event.type === "remove") {
|
||||
const removed = this.descriptors.get(key);
|
||||
this.descriptors.delete(key);
|
||||
this.timelines.delete(key);
|
||||
return { type: "remove", parentAgentId, subagentId: event.id };
|
||||
return {
|
||||
type: "remove",
|
||||
parentAgentId,
|
||||
subagentId: event.id,
|
||||
runningCountChanged: removed?.status === "running",
|
||||
};
|
||||
}
|
||||
|
||||
if (event.type === "timeline") {
|
||||
@@ -128,7 +138,11 @@ export class ProviderSubagentStore {
|
||||
parentSubagentId: stickyField(event.parentSubagentId, previous?.parentSubagentId),
|
||||
};
|
||||
this.descriptors.set(key, subagent);
|
||||
return { type: "upsert", subagent };
|
||||
return {
|
||||
type: "upsert",
|
||||
subagent,
|
||||
runningCountChanged: (previous?.status === "running") !== (subagent.status === "running"),
|
||||
};
|
||||
}
|
||||
|
||||
list(parentAgentId: string): ProviderSubagentDescriptor[] {
|
||||
@@ -137,6 +151,14 @@ export class ProviderSubagentStore {
|
||||
.sort((left, right) => left.createdAt.localeCompare(right.createdAt));
|
||||
}
|
||||
|
||||
countRunning(parentAgentId: string): number {
|
||||
let count = 0;
|
||||
for (const subagent of this.descriptors.values()) {
|
||||
if (subagent.parentAgentId === parentAgentId && subagent.status === "running") count += 1;
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
listAll(): ProviderSubagentDescriptor[] {
|
||||
return [...this.descriptors.values()];
|
||||
}
|
||||
@@ -159,7 +181,12 @@ export class ProviderSubagentStore {
|
||||
const key = storeKey(parentAgentId, subagent.id);
|
||||
this.descriptors.delete(key);
|
||||
this.timelines.delete(key);
|
||||
events.push({ type: "remove", parentAgentId, subagentId: subagent.id });
|
||||
events.push({
|
||||
type: "remove",
|
||||
parentAgentId,
|
||||
subagentId: subagent.id,
|
||||
runningCountChanged: subagent.status === "running",
|
||||
});
|
||||
}
|
||||
return events;
|
||||
}
|
||||
|
||||
@@ -153,6 +153,56 @@ describe("Claude SDK env", () => {
|
||||
}
|
||||
});
|
||||
|
||||
test("resume uses current plugin instructions and excludes them from persistence", async () => {
|
||||
const prompts: unknown[] = [];
|
||||
const queryFactory = ({ options }: ClaudeQueryInput) => {
|
||||
prompts.push(options.systemPrompt);
|
||||
return createQueryMock([
|
||||
{
|
||||
type: "system",
|
||||
subtype: "init",
|
||||
session_id: "persisted-session",
|
||||
permissionMode: "default",
|
||||
model: "opus",
|
||||
},
|
||||
{ type: "assistant", message: { content: "done" } },
|
||||
{
|
||||
type: "result",
|
||||
subtype: "success",
|
||||
usage: { input_tokens: 1, cache_read_input_tokens: 0, output_tokens: 1 },
|
||||
total_cost_usd: 0,
|
||||
},
|
||||
]);
|
||||
};
|
||||
const client = new ClaudeAgentClient({
|
||||
logger: createTestLogger(),
|
||||
queryFactory,
|
||||
resolveBinary: async () => "/test/claude/bin",
|
||||
});
|
||||
const first = await client.createSession({
|
||||
provider: "claude",
|
||||
cwd: process.cwd(),
|
||||
pluginAppendSystemPrompt: ["Plugin instructions"],
|
||||
});
|
||||
await first.run("first");
|
||||
const handle = first.describePersistence()!;
|
||||
expect(handle.metadata).not.toHaveProperty("pluginAppendSystemPrompt");
|
||||
await first.close();
|
||||
const resumed = await client.resumeSession(handle, {
|
||||
cwd: process.cwd(),
|
||||
pluginAppendSystemPrompt: undefined,
|
||||
});
|
||||
try {
|
||||
await resumed.run("after disable");
|
||||
expect(prompts).toEqual([
|
||||
{ type: "preset", preset: "claude_code", append: "Plugin instructions" },
|
||||
{ type: "preset", preset: "claude_code", append: "" },
|
||||
]);
|
||||
} finally {
|
||||
await resumed.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("forwards launch-context env through Claude resume env", async () => {
|
||||
let capturedEnv: Record<string, string | undefined> | undefined;
|
||||
const launchContext: AgentLaunchContext = {
|
||||
|
||||
@@ -123,7 +123,8 @@ test.each(["mode", "model", "commands"] as const)(
|
||||
try {
|
||||
await session.startTurn("Run the foreground command");
|
||||
await running.promise;
|
||||
expect(await session.setThinkingOption?.("medium")).toMatchObject({
|
||||
// Ultracode is launched with the query, so the change waits for a restart.
|
||||
expect(await session.setThinkingOption?.("ultracode")).toMatchObject({
|
||||
message: "Thinking level applies next turn",
|
||||
});
|
||||
if (control === "mode") await session.setMode("acceptEdits");
|
||||
@@ -149,7 +150,7 @@ test.each(["mode", "model", "commands"] as const)(
|
||||
await session.startTurn("Run another command with the new thinking level");
|
||||
queries[1].work.resolve();
|
||||
expect(await terminal.promise).toBe("turn_completed");
|
||||
expect(efforts).toEqual(["low", "medium"]);
|
||||
expect(efforts).toEqual(["low", "xhigh"]);
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
|
||||
@@ -2070,212 +2070,3 @@ test("does not use stream_event uuid as assistant message identity when message_
|
||||
|
||||
await session.close();
|
||||
});
|
||||
|
||||
// A background command's notification starts a turn. When Claude responds, the notification and
|
||||
// the response are one turn. When Claude does not respond, the notification is a turn in itself.
|
||||
// The frame sequences below are the ones Claude Code 2.1.321 sent on the wire.
|
||||
|
||||
function backgroundCommandNotification(taskId: string, status: "completed" | "stopped") {
|
||||
return {
|
||||
type: "system",
|
||||
subtype: "task_notification",
|
||||
task_id: taskId,
|
||||
tool_use_id: `toolu_${taskId}`,
|
||||
status,
|
||||
summary: `Background command ${status}`,
|
||||
output_file: `/tmp/${taskId}.output`,
|
||||
uuid: `uuid-${taskId}-${status}`,
|
||||
session_id: "sess-1",
|
||||
};
|
||||
}
|
||||
|
||||
const backgroundTasksChanged = {
|
||||
type: "system",
|
||||
subtype: "background_tasks_changed",
|
||||
tasks: [],
|
||||
uuid: "uuid-background-tasks-changed",
|
||||
session_id: "sess-1",
|
||||
};
|
||||
|
||||
function notificationRowTurnIds(events: AgentStreamEvent[]): (string | undefined)[] {
|
||||
return events
|
||||
.filter(
|
||||
(event): event is Extract<AgentStreamEvent, { type: "timeline" }> =>
|
||||
event.type === "timeline" &&
|
||||
event.item.type === "tool_call" &&
|
||||
event.item.name === "task_notification",
|
||||
)
|
||||
.map((event) => event.turnId);
|
||||
}
|
||||
|
||||
function startedTurnIds(events: AgentStreamEvent[]): (string | undefined)[] {
|
||||
return events
|
||||
.filter((event) => event.type === "turn_started")
|
||||
.map((event) => (event.type === "turn_started" ? event.turnId : undefined));
|
||||
}
|
||||
|
||||
async function createObservedSession() {
|
||||
sdkQueryFactory.mockImplementation(() => createPendingQueryMock());
|
||||
const session = await createSession();
|
||||
const internal: SessionStateInternals = asInternals(session);
|
||||
const queryMock = createPendingQueryMock();
|
||||
const events: AgentStreamEvent[] = [];
|
||||
session.subscribe((event) => events.push(event));
|
||||
async function route(...frames: Record<string, unknown>[]) {
|
||||
for (const frame of frames) await internal.routeSdkMessageFromPump(frame, queryMock);
|
||||
}
|
||||
return { session, internal, events, route };
|
||||
}
|
||||
|
||||
test("a completed command's notification and Claude's response to it are one turn", async () => {
|
||||
const { session, internal, events, route } = await createObservedSession();
|
||||
|
||||
await route(backgroundCommandNotification("sleep-40", "completed"), backgroundTasksChanged);
|
||||
const [notificationTurnId] = notificationRowTurnIds(events);
|
||||
expect(notificationTurnId).toEqual(expect.any(String));
|
||||
expect(startedTurnIds(events)).toEqual([]);
|
||||
expect(internal.turnState).toBe("idle");
|
||||
|
||||
await route(sessionState("running"), claudeTurnInit(), unboundTextDelta("SECOND REPLY"));
|
||||
expect(startedTurnIds(events)).toEqual([notificationTurnId]);
|
||||
expect(internal.turnState).toBe("autonomous");
|
||||
|
||||
await route(successResult(), sessionState("idle"));
|
||||
expect(internal.turnState).toBe("idle");
|
||||
|
||||
await session.close();
|
||||
});
|
||||
|
||||
test("a stopped command Claude does not respond to is a turn in itself, and the next notification starts the next turn", async () => {
|
||||
const { session, internal, events, route } = await createObservedSession();
|
||||
|
||||
await route(backgroundCommandNotification("sleep-300", "stopped"), backgroundTasksChanged);
|
||||
const [stoppedTurnId] = notificationRowTurnIds(events);
|
||||
expect(stoppedTurnId).toEqual(expect.any(String));
|
||||
expect(startedTurnIds(events)).toEqual([]);
|
||||
expect(internal.turnState).toBe("idle");
|
||||
|
||||
await route(backgroundCommandNotification("sleep-60", "completed"), backgroundTasksChanged);
|
||||
const [, completedTurnId] = notificationRowTurnIds(events);
|
||||
expect(completedTurnId).toEqual(expect.any(String));
|
||||
expect(completedTurnId).not.toBe(stoppedTurnId);
|
||||
|
||||
await route(sessionState("running"), claudeTurnInit(), successResult(), sessionState("idle"));
|
||||
expect(startedTurnIds(events)).toEqual([completedTurnId]);
|
||||
|
||||
await session.close();
|
||||
});
|
||||
|
||||
test("a run Claude announces as a queued command does not belong to the notification before it", async () => {
|
||||
const { session, events, route } = await createObservedSession();
|
||||
|
||||
await route(backgroundCommandNotification("sleep-300", "stopped"), backgroundTasksChanged);
|
||||
const [stoppedTurnId] = notificationRowTurnIds(events);
|
||||
|
||||
// A scheduled wake-up: Claude announces the queued command it starts before the run's init.
|
||||
await route(
|
||||
sessionState("running"),
|
||||
commandLifecycle("cron-prompt", "started"),
|
||||
claudeTurnInit(),
|
||||
);
|
||||
const [runTurnId] = startedTurnIds(events);
|
||||
expect(runTurnId).toEqual(expect.any(String));
|
||||
expect(runTurnId).not.toBe(stoppedTurnId);
|
||||
|
||||
await session.close();
|
||||
});
|
||||
|
||||
test("a run Claude starts for a finished background subagent does not belong to the notification before it", async () => {
|
||||
const { session, events, route } = await createObservedSession();
|
||||
|
||||
await route(helperTaskStarted);
|
||||
await route(backgroundCommandNotification("sleep-300", "stopped"), backgroundTasksChanged);
|
||||
const [stoppedTurnId] = notificationRowTurnIds(events);
|
||||
|
||||
await route(helperCompleted, claudeTurnInit());
|
||||
const [runTurnId] = startedTurnIds(events);
|
||||
expect(runTurnId).toEqual(expect.any(String));
|
||||
expect(runTurnId).not.toBe(stoppedTurnId);
|
||||
|
||||
await session.close();
|
||||
});
|
||||
|
||||
test("the user's next message starts its own turn after a notification Claude did not respond to", async () => {
|
||||
const { session, internal, events, route } = await createObservedSession();
|
||||
|
||||
await route(backgroundCommandNotification("sleep-300", "stopped"), backgroundTasksChanged);
|
||||
const [stoppedTurnId] = notificationRowTurnIds(events);
|
||||
|
||||
const { turnId } = await session.startTurn("PING");
|
||||
expect(turnId).not.toBe(stoppedTurnId);
|
||||
await route(claudeTurnInit(), successResult());
|
||||
expect(internal.activeForegroundTurnId).toBeNull();
|
||||
|
||||
// A run Claude starts later, with nothing announced, is not the stopped command's turn either.
|
||||
await route(claudeTurnInit());
|
||||
expect(startedTurnIds(events).at(-1)).not.toBe(stoppedTurnId);
|
||||
|
||||
await session.close();
|
||||
});
|
||||
|
||||
test("a run Claude starts without announcing anything belongs to the last notification", async () => {
|
||||
const { session, events, route } = await createObservedSession();
|
||||
|
||||
// Claude sends no frame for a Monitor event, so its wake-up reads as the response to the stop.
|
||||
await route(backgroundCommandNotification("sleep-300", "stopped"), backgroundTasksChanged);
|
||||
const [stoppedTurnId] = notificationRowTurnIds(events);
|
||||
|
||||
await route(sessionState("running"), claudeTurnInit());
|
||||
expect(startedTurnIds(events)).toEqual([stoppedTurnId]);
|
||||
|
||||
await session.close();
|
||||
});
|
||||
|
||||
test("a notification during a turn belongs to that turn", async () => {
|
||||
const { session, events, route } = await createObservedSession();
|
||||
|
||||
await route(claudeTurnInit());
|
||||
const [runTurnId] = startedTurnIds(events);
|
||||
await route(backgroundCommandNotification("sleep-40", "completed"));
|
||||
expect(notificationRowTurnIds(events)).toEqual([runTurnId]);
|
||||
await route(successResult(), claudeTurnInit());
|
||||
expect(startedTurnIds(events)).toHaveLength(2);
|
||||
expect(startedTurnIds(events)[1]).not.toBe(runTurnId);
|
||||
|
||||
await session.close();
|
||||
});
|
||||
|
||||
test("a background subagent's own job notification does not start a main-session turn", async () => {
|
||||
const { session, events, route } = await createObservedSession();
|
||||
|
||||
// The helper runs a background Bash of its own; its notification reports to the helper.
|
||||
await route(helperTaskStarted, {
|
||||
type: "assistant",
|
||||
parent_tool_use_id: "toolu_helper",
|
||||
session_id: "sess-1",
|
||||
message: {
|
||||
id: "msg-helper-bash",
|
||||
role: "assistant",
|
||||
model: "opus",
|
||||
content: [{ type: "tool_use", id: "toolu_subagent_bash", name: "Bash", input: {} }],
|
||||
},
|
||||
});
|
||||
|
||||
await route(backgroundCommandNotification("sleep-40", "completed"), backgroundTasksChanged);
|
||||
const [notificationTurnId] = notificationRowTurnIds(events);
|
||||
await route(subagentOwnedTaskNotification);
|
||||
expect(
|
||||
events.some(
|
||||
(event) =>
|
||||
event.type === "provider_subagent" &&
|
||||
event.event.type === "timeline" &&
|
||||
event.event.item.type === "tool_call" &&
|
||||
event.event.item.name === "task_notification",
|
||||
),
|
||||
).toBe(true);
|
||||
|
||||
await route(claudeTurnInit());
|
||||
expect(startedTurnIds(events)).toEqual([notificationTurnId]);
|
||||
|
||||
await session.close();
|
||||
});
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user