mirror of
https://github.com/getpaseo/paseo.git
synced 2026-12-03 13:46:00 +00:00
Compare commits
18
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
83aead6d08 | ||
|
|
d3918b95a5 | ||
|
|
8ebe37558d | ||
|
|
dcd10a6029 | ||
|
|
5e16d70aaa | ||
|
|
b89eae1eff | ||
|
|
32496c489e | ||
|
|
da51ac3d64 | ||
|
|
0ec89b5623 | ||
|
|
12d28ddbc8 | ||
|
|
f621e31f3e | ||
|
|
c9ba30194c | ||
|
|
fa185cb063 | ||
|
|
723df269d2 | ||
|
|
f86c58b42b | ||
|
|
1cfadda498 | ||
|
|
776210b72b | ||
|
|
80bcbdc931 |
@@ -89,8 +89,9 @@ relay:
|
||||
- "packages/relay/**"
|
||||
|
||||
# cli-tests is also a daemon end-to-end suite: it drives a real daemon, built-in
|
||||
# plugins included, so daemon changes run it too.
|
||||
# plugins and the plugin runtime included, so their changes run it too.
|
||||
cli:
|
||||
- "packages/cli/**"
|
||||
- "packages/server/**"
|
||||
- "packages/plugin/**"
|
||||
- "plugins/**"
|
||||
|
||||
+21
-21
@@ -20,6 +20,15 @@
|
||||
- Paseo CLI and daemon now require Node.js 22.16.0 or later ([#11410](https://github.com/getpaseo/paseo/pull/11410))
|
||||
- Relay connections now require [protected end-to-end encryption](https://paseo.sh/docs/security) by default, so apps older than 0.13.0 cannot connect through the relay ([#11864](https://github.com/getpaseo/paseo/pull/11864))
|
||||
|
||||
### Security
|
||||
|
||||
- Denied camera, microphone, location, notification and device access to pages in the desktop browser by default ([#11837](https://github.com/getpaseo/paseo/pull/11837))
|
||||
- Blocked client file access to the daemon's own state in the Paseo home directory, and warned when a saved host's daemon key changes ([#11452](https://github.com/getpaseo/paseo/pull/11452))
|
||||
- Restricted loopback origin matching to `localhost`, `127.0.0.1` and `::1` for daemon WebSocket and HTTP requests ([#11686](https://github.com/getpaseo/paseo/pull/11686))
|
||||
- Stopped images in pull request comments and reviews from loading files from the host ([#11699](https://github.com/getpaseo/paseo/pull/11699))
|
||||
- Stopped `.worktreeinclude` from copying local files into worktrees from fork pull requests ([#11709](https://github.com/getpaseo/paseo/pull/11709))
|
||||
- Rejected schedule IDs that point outside the schedules directory ([#11727](https://github.com/getpaseo/paseo/pull/11727))
|
||||
|
||||
### Added
|
||||
|
||||
- Added Antigravity quota to Usage, refreshed only when you select Refresh ([#11585](https://github.com/getpaseo/paseo/pull/11585))
|
||||
@@ -53,6 +62,18 @@
|
||||
- Changed Cmd/Ctrl+click on a sidebar workspace to open it instead of entering select mode ([#11472](https://github.com/getpaseo/paseo/pull/11472))
|
||||
- Changed agents that already reported to their caller with `send_agent_prompt` to skip the extra finished notice ([#11583](https://github.com/getpaseo/paseo/pull/11583))
|
||||
|
||||
### Plugins
|
||||
|
||||
- Added a workspace layout API so plugins can open, move and close panes and tabs ([#11328](https://github.com/getpaseo/paseo/pull/11328))
|
||||
- Added `ProviderIcon` so plugins can show Paseo's provider icons ([#4664](https://github.com/getpaseo/paseo/pull/4664) by [@omercnet](https://github.com/omercnet))
|
||||
- Added `requirements.app` to set a separate minimum app version from the daemon's ([#11494](https://github.com/getpaseo/paseo/pull/11494) by [@mcowger](https://github.com/mcowger))
|
||||
- Fixed a plugin error in a press handler or timer closing the iOS and Android app ([#11412](https://github.com/getpaseo/paseo/pull/11412))
|
||||
- Fixed plugin popovers on web and desktop loading their content twice on each open ([#11748](https://github.com/getpaseo/paseo/pull/11748) by [@tomgrin10](https://github.com/tomgrin10))
|
||||
- Fixed the desktop app keeping every replaced plugin version in memory after plugin reloads ([#11800](https://github.com/getpaseo/paseo/pull/11800))
|
||||
- Fixed plugin operations deleting plugin entries added to `config.json` by hand ([#11501](https://github.com/getpaseo/paseo/pull/11501) by [@matchy233](https://github.com/matchy233))
|
||||
- Fixed registry plugin installs failing with Missing npm artifact when npm leaves registry URLs out of lockfiles ([#11656](https://github.com/getpaseo/paseo/pull/11656) by [@Brandon168](https://github.com/Brandon168))
|
||||
- Fixed local plugin reloads taking 12 to 21 seconds when the daemon runs under a large directory ([#11653](https://github.com/getpaseo/paseo/pull/11653))
|
||||
|
||||
### Fixed
|
||||
|
||||
- Fixed thinking level, mode and model changes on a running agent snapping back to the old value ([#11850](https://github.com/getpaseo/paseo/pull/11850))
|
||||
@@ -151,27 +172,6 @@
|
||||
- Fixed `paseo daemon status` leaving out unconfirmed terminal cleanup ([#11658](https://github.com/getpaseo/paseo/pull/11658) by [@chirag127](https://github.com/chirag127))
|
||||
- Fixed CLI archive, detach and reload scanning all agent history for a full agent ID ([#11617](https://github.com/getpaseo/paseo/pull/11617) by [@maci0](https://github.com/maci0))
|
||||
|
||||
### Security
|
||||
|
||||
- Denied camera, microphone, location, notification and device access to pages in the desktop browser by default ([#11837](https://github.com/getpaseo/paseo/pull/11837))
|
||||
- Blocked client file access to the daemon's own state in the Paseo home directory, and warned when a saved host's daemon key changes ([#11452](https://github.com/getpaseo/paseo/pull/11452))
|
||||
- Restricted loopback origin matching to `localhost`, `127.0.0.1` and `::1` for daemon WebSocket and HTTP requests ([#11686](https://github.com/getpaseo/paseo/pull/11686))
|
||||
- Stopped images in pull request comments and reviews from loading files from the host ([#11699](https://github.com/getpaseo/paseo/pull/11699))
|
||||
- Stopped `.worktreeinclude` from copying local files into worktrees from fork pull requests ([#11709](https://github.com/getpaseo/paseo/pull/11709))
|
||||
- Rejected schedule IDs that point outside the schedules directory ([#11727](https://github.com/getpaseo/paseo/pull/11727))
|
||||
|
||||
### Plugins
|
||||
|
||||
- Added a workspace layout API so plugins can open, move and close panes and tabs ([#11328](https://github.com/getpaseo/paseo/pull/11328))
|
||||
- Added `ProviderIcon` so plugins can show Paseo's provider icons ([#4664](https://github.com/getpaseo/paseo/pull/4664) by [@omercnet](https://github.com/omercnet))
|
||||
- Added `requirements.app` to set a separate minimum app version from the daemon's ([#11494](https://github.com/getpaseo/paseo/pull/11494) by [@mcowger](https://github.com/mcowger))
|
||||
- Fixed a plugin error in a press handler or timer closing the iOS and Android app ([#11412](https://github.com/getpaseo/paseo/pull/11412))
|
||||
- Fixed plugin popovers on web and desktop loading their content twice on each open ([#11748](https://github.com/getpaseo/paseo/pull/11748) by [@tomgrin10](https://github.com/tomgrin10))
|
||||
- Fixed the desktop app keeping every replaced plugin version in memory after plugin reloads ([#11800](https://github.com/getpaseo/paseo/pull/11800))
|
||||
- Fixed plugin operations deleting plugin entries added to `config.json` by hand ([#11501](https://github.com/getpaseo/paseo/pull/11501) by [@matchy233](https://github.com/matchy233))
|
||||
- Fixed registry plugin installs failing with Missing npm artifact when npm leaves registry URLs out of lockfiles ([#11656](https://github.com/getpaseo/paseo/pull/11656) by [@Brandon168](https://github.com/Brandon168))
|
||||
- Fixed local plugin reloads taking 12 to 21 seconds when the daemon runs under a large directory ([#11653](https://github.com/getpaseo/paseo/pull/11653))
|
||||
|
||||
## 0.18.2 - 2026-11-30
|
||||
|
||||
- **Redesigned model picker:** Pick models from a two-pane desktop view with cross-provider search, an in-place phone drawer with a thinking slider, and per-provider model lists in settings. ([#11186](https://github.com/getpaseo/paseo/pull/11186), [#11280](https://github.com/getpaseo/paseo/pull/11280), [#11295](https://github.com/getpaseo/paseo/pull/11295), [#11371](https://github.com/getpaseo/paseo/pull/11371), [#11313](https://github.com/getpaseo/paseo/pull/11313))
|
||||
|
||||
+21
-21
@@ -20,6 +20,15 @@
|
||||
- Paseo CLI 和 daemon 现在需要 Node.js 22.16.0 或更高版本 ([#11410](https://github.com/getpaseo/paseo/pull/11410))
|
||||
- 中继连接现在默认要求[受保护的端到端加密](https://paseo.sh/zh-CN/docs/security),因此 0.13.0 之前的应用无法再通过中继连接 ([#11864](https://github.com/getpaseo/paseo/pull/11864))
|
||||
|
||||
### 安全
|
||||
|
||||
- 桌面端浏览器中的网页默认禁止访问摄像头、麦克风、位置、通知和设备 ([#11837](https://github.com/getpaseo/paseo/pull/11837))
|
||||
- 阻止客户端访问 Paseo 主目录中 daemon 自身的状态文件,并在已保存主机的 daemon 密钥变化时发出警告 ([#11452](https://github.com/getpaseo/paseo/pull/11452))
|
||||
- 将 daemon WebSocket 和 HTTP 请求的回环来源匹配限制为 `localhost`、`127.0.0.1` 和 `::1` ([#11686](https://github.com/getpaseo/paseo/pull/11686))
|
||||
- 禁止 PR 评论和审查中的图片读取主机上的文件 ([#11699](https://github.com/getpaseo/paseo/pull/11699))
|
||||
- 禁止 `.worktreeinclude` 将本地文件复制到来自 fork PR 的 worktree 中 ([#11709](https://github.com/getpaseo/paseo/pull/11709))
|
||||
- 拒绝指向定时任务目录之外的定时任务 ID ([#11727](https://github.com/getpaseo/paseo/pull/11727))
|
||||
|
||||
### 新增
|
||||
|
||||
- 在用量中新增 Antigravity 配额,仅在选择 **刷新** 时更新 ([#11585](https://github.com/getpaseo/paseo/pull/11585))
|
||||
@@ -53,6 +62,18 @@
|
||||
- 在侧边栏中 Cmd/Ctrl+点击工作区改为打开该工作区,而不再进入选择模式 ([#11472](https://github.com/getpaseo/paseo/pull/11472))
|
||||
- 已通过 `send_agent_prompt` 向调用方汇报的 Agent 不再额外发送完成通知 ([#11583](https://github.com/getpaseo/paseo/pull/11583))
|
||||
|
||||
### 插件
|
||||
|
||||
- 新增工作区布局 API,插件可以打开、移动和关闭面板与标签页 ([#11328](https://github.com/getpaseo/paseo/pull/11328))
|
||||
- 新增 `ProviderIcon`,插件可以显示 Paseo 的 Provider 图标 ([#4664](https://github.com/getpaseo/paseo/pull/4664),贡献者:[@omercnet](https://github.com/omercnet))
|
||||
- 新增 `requirements.app`,可单独设置与 daemon 不同的最低应用版本 ([#11494](https://github.com/getpaseo/paseo/pull/11494),贡献者:[@mcowger](https://github.com/mcowger))
|
||||
- 修复插件在按下处理函数或定时器中出错导致 iOS 和 Android 应用关闭的问题 ([#11412](https://github.com/getpaseo/paseo/pull/11412))
|
||||
- 修复网页端和桌面端插件弹出框每次打开都加载两次内容的问题 ([#11748](https://github.com/getpaseo/paseo/pull/11748),贡献者:[@tomgrin10](https://github.com/tomgrin10))
|
||||
- 修复桌面应用在插件重新加载后仍在内存中保留每个被替换插件版本的问题 ([#11800](https://github.com/getpaseo/paseo/pull/11800))
|
||||
- 修复插件操作删除手动添加到 `config.json` 中插件条目的问题 ([#11501](https://github.com/getpaseo/paseo/pull/11501),贡献者:[@matchy233](https://github.com/matchy233))
|
||||
- 修复 npm 在锁文件中省略 registry 地址时,注册表插件安装报 Missing npm artifact 错误的问题 ([#11656](https://github.com/getpaseo/paseo/pull/11656),贡献者:[@Brandon168](https://github.com/Brandon168))
|
||||
- 修复 daemon 运行在大型目录下时,本地插件重新加载耗时 12 至 21 秒的问题 ([#11653](https://github.com/getpaseo/paseo/pull/11653))
|
||||
|
||||
### 修复
|
||||
|
||||
- 修复更改运行中 Agent 的思考强度、模式和模型后又跳回旧值的问题 ([#11850](https://github.com/getpaseo/paseo/pull/11850))
|
||||
@@ -151,27 +172,6 @@
|
||||
- 修复 `paseo daemon status` 遗漏未确认的终端清理的问题 ([#11658](https://github.com/getpaseo/paseo/pull/11658),贡献者:[@chirag127](https://github.com/chirag127))
|
||||
- 修复 CLI 归档、分离和重新加载时为匹配完整 Agent ID 而扫描全部 Agent 历史记录的问题 ([#11617](https://github.com/getpaseo/paseo/pull/11617),贡献者:[@maci0](https://github.com/maci0))
|
||||
|
||||
### 安全
|
||||
|
||||
- 桌面端浏览器中的网页默认禁止访问摄像头、麦克风、位置、通知和设备 ([#11837](https://github.com/getpaseo/paseo/pull/11837))
|
||||
- 阻止客户端访问 Paseo 主目录中 daemon 自身的状态文件,并在已保存主机的 daemon 密钥变化时发出警告 ([#11452](https://github.com/getpaseo/paseo/pull/11452))
|
||||
- 将 daemon WebSocket 和 HTTP 请求的回环来源匹配限制为 `localhost`、`127.0.0.1` 和 `::1` ([#11686](https://github.com/getpaseo/paseo/pull/11686))
|
||||
- 禁止 PR 评论和审查中的图片读取主机上的文件 ([#11699](https://github.com/getpaseo/paseo/pull/11699))
|
||||
- 禁止 `.worktreeinclude` 将本地文件复制到来自 fork PR 的 worktree 中 ([#11709](https://github.com/getpaseo/paseo/pull/11709))
|
||||
- 拒绝指向定时任务目录之外的定时任务 ID ([#11727](https://github.com/getpaseo/paseo/pull/11727))
|
||||
|
||||
### 插件
|
||||
|
||||
- 新增工作区布局 API,插件可以打开、移动和关闭面板与标签页 ([#11328](https://github.com/getpaseo/paseo/pull/11328))
|
||||
- 新增 `ProviderIcon`,插件可以显示 Paseo 的 Provider 图标 ([#4664](https://github.com/getpaseo/paseo/pull/4664),贡献者:[@omercnet](https://github.com/omercnet))
|
||||
- 新增 `requirements.app`,可单独设置与 daemon 不同的最低应用版本 ([#11494](https://github.com/getpaseo/paseo/pull/11494),贡献者:[@mcowger](https://github.com/mcowger))
|
||||
- 修复插件在按下处理函数或定时器中出错导致 iOS 和 Android 应用关闭的问题 ([#11412](https://github.com/getpaseo/paseo/pull/11412))
|
||||
- 修复网页端和桌面端插件弹出框每次打开都加载两次内容的问题 ([#11748](https://github.com/getpaseo/paseo/pull/11748),贡献者:[@tomgrin10](https://github.com/tomgrin10))
|
||||
- 修复桌面应用在插件重新加载后仍在内存中保留每个被替换插件版本的问题 ([#11800](https://github.com/getpaseo/paseo/pull/11800))
|
||||
- 修复插件操作删除手动添加到 `config.json` 中插件条目的问题 ([#11501](https://github.com/getpaseo/paseo/pull/11501),贡献者:[@matchy233](https://github.com/matchy233))
|
||||
- 修复 npm 在锁文件中省略 registry 地址时,注册表插件安装报 Missing npm artifact 错误的问题 ([#11656](https://github.com/getpaseo/paseo/pull/11656),贡献者:[@Brandon168](https://github.com/Brandon168))
|
||||
- 修复 daemon 运行在大型目录下时,本地插件重新加载耗时 12 至 21 秒的问题 ([#11653](https://github.com/getpaseo/paseo/pull/11653))
|
||||
|
||||
## 0.18.2 - 2026-11-30
|
||||
|
||||
- **重新设计的模型选择器**:桌面端采用支持跨 Provider 搜索的双栏视图,手机端合并为带思考强度滑块的单层抽屉,并支持在设置中按 Provider 筛选常用模型。([#11186](https://github.com/getpaseo/paseo/pull/11186), [#11280](https://github.com/getpaseo/paseo/pull/11280), [#11295](https://github.com/getpaseo/paseo/pull/11295), [#11371](https://github.com/getpaseo/paseo/pull/11371), [#11313](https://github.com/getpaseo/paseo/pull/11313))
|
||||
|
||||
+15
-15
@@ -154,15 +154,15 @@ Users can also detach an existing subagent from the subagents track. Detach is d
|
||||
|
||||
Agent-originated messages and automatic notifications share a recipient-daemon delivery module. The daemon saves a queued message, then acknowledges it with a receipt, before provider dispatch. The module keeps one ordered queue per recipient, and the recipient reads its prompts in the order the daemon admitted them. Nothing overtakes an older queued message. A prompt takes its place when the daemon admits it, even while the provider is still starting an earlier turn, and a message stays in the queue until the turn that carries it starts. The turn has started when the agent manager acknowledges the run start; a turn that fails after that point is not delivered again.
|
||||
|
||||
Any sender picks `queue`, `steer`, or `interrupt` with `activeTurnBehavior`. Agent senders default to `queue`; non-agent senders (app, CLI, plugins, Hub, top-level MCP) default to `interrupt`. Each kind of prompt is released this way:
|
||||
Any sender picks `queue`, `steer`, or `interrupt` with `activeTurnBehavior`. Agent senders and finish notifications default to `steer` (falling back to `queue` on providers without `steerActiveTurn`); non-agent senders (app, CLI, plugins, Hub, top-level MCP) default to `interrupt` (or `steer` in composer settings). Each kind of prompt is released this way:
|
||||
|
||||
- **`queue`** waits for any running or starting turn (including compaction) to end on its own or fail, then delivers the queued prompts together. The daemon releases it when it observes the recipient settle; a two-second timer also retries. On an idle recipient, agent messages wait two quiet seconds (steady arrivals cannot hold that window open past ten seconds); a non-agent queued message skips that quiet window and starts a turn at once. A non-agent queued message is sent unwrapped when dispatched alone, and in a `kind="user-message"` envelope when it shares a prompt with other messages. Finish notifications and change-request updates always queue.
|
||||
- **`steer`** waits for neither the quiet window nor the turn. It is dispatched at admission as one prompt that enters the running turn: the messages queued before it, then the steer. A provider that cannot steer, or that refuses this steer, gets the prompt as a replacing turn instead, the same as a person's steer.
|
||||
- **`interrupt`** is dispatched at admission the same way, as one prompt that replaces the running turn. An older queued message cannot start a turn after the newer `interrupt` that countermands it.
|
||||
- **A person's direct prompt** (`steer` or `interrupt` from app, CLI, plugins, Hub, or top-level MCP) is dispatched directly and takes the queue along the same way: the messages admitted before it first, then the person's text, in one provider prompt. Messages admitted after it follow it. The person's text keeps its own transcript row. When the turn does not start, the messages return to the queue in their place. That covers a start the provider rejects and a start that is not acknowledged within 60 seconds; a provider that starts the turn after those 60 seconds receives the messages twice.
|
||||
- **Stop** (the stop button, Escape, `cancel_agent`, a Hub interrupt) starts nothing. Messages admitted before the Stop are held, not dropped, including an interrupt whose turn had not started yet. They go ahead of the recipient's next prompt, in that prompt's turn: a person's prompt, or an agent message or notification admitted after the Stop. A held steer or interrupt no longer enters the turn; it waits like a queued message. A queue step or dispatch decided before the Stop is void, and the queue is held again when the message that reopened it is withdrawn. A replacing prompt, a reload, and a rewind are not a Stop. Neither is `cancel_agent` on a recipient with no running or starting turn: it stops nothing, reports that it canceled no run, and a queued message keeps its quiet window.
|
||||
- **`queue`** waits for any running or starting turn (including compaction) to end on its own or fail, then delivers the queued prompts together. The daemon releases it when it observes the recipient settle; a two-second timer also retries. On an idle recipient, agent messages wait two quiet seconds (steady arrivals cannot hold that window open past ten seconds); a non-agent queued message skips that quiet window and starts a turn at once. A non-agent queued message is sent unwrapped when dispatched alone, and in a `kind="user-message"` envelope when it shares a prompt with other messages.
|
||||
- **`steer`** from an agent sender enters the running turn without cutting it, carrying earlier agent-queued messages ahead of it while leaving human-queued items untouched in the queue. Finish notifications batch across the two-second quiet window before steering so parallel completions arrive together. If the provider cannot steer (`canSteer` is false, e.g., ACP agents) or rejects steering mid-turn without ending the turn, the daemon keeps the message queued until the turn ends rather than interrupting it.
|
||||
- **`interrupt`** is dispatched at admission the same way, replacing the running turn and carrying earlier non-human-queued messages ahead of it.
|
||||
- **A person's direct prompt** (`steer` or `interrupt` from app, CLI, plugins, Hub, or top-level MCP) runs immediately by itself and does **not** sweep queued messages. Queued messages stay intact in the queue track and dispatch once the turn settles, unless the queue is behind a staged provider switch (where the switch queues behind items meant for the current provider). When a non-command, non-resume direct human prompt succeeds on a held queue (after Stop or a refused start), it reopens the held queue so remaining queued items resume after the turn ends.
|
||||
- **Stop** (the stop button, Escape, `cancel_agent`, a Hub interrupt) starts nothing. Messages admitted before the Stop are held, not dropped, including an interrupt whose turn had not started yet. Held items wait until reopened by a direct non-command prompt, a newly admitted message, or explicit Send now (`promote`). A queue step or dispatch decided before the Stop is void, and the queue is held again when the message that reopened it is withdrawn. A replacing prompt, a reload, and a rewind are not a Stop. Neither is `cancel_agent` on a recipient with no running or starting turn: it stops nothing, reports that it canceled no run, and a queued message keeps its quiet window.
|
||||
|
||||
The queued receipt carries the applied behavior and guidance text for the sender. The text comes from two facts known at admission: whether the recipient has a running turn, and whether its provider can steer (`AgentManager.canSteer`, which is true when the session offers `steerActiveTurn`). It does not wait for the outcome. Guidance for a message queued behind a running turn tells the sender to send a short `steer` or `interrupt` follow-up instead of resending, because the follow-up carries the queued message ahead of it and a resend would be read twice. The MCP tool, the WebSocket `send_agent_message_response`, the CLI, and the connected-host path all relay this one text.
|
||||
The queued receipt carries the applied behavior and guidance text for the sender. The text comes from two facts known at admission: whether the recipient has a running turn, and whether its provider can steer (`AgentManager.canSteer`, which is true when the session offers `steerActiveTurn`). It does not wait for the outcome. Guidance for a message queued behind a running turn tells the sender to send a short `steer` or `interrupt` follow-up instead of resending, because an agent follow-up carries earlier agent-queued messages ahead of it. On non-steering providers, queued `steer` reports as `queue` and notes that `steer` waits until the turn ends. The MCP tool, the WebSocket `send_agent_message_response`, the CLI, and the connected-host path all relay this one text.
|
||||
|
||||
Older CLIs and connected hosts send an explicit `steer` for every default agent send. The daemon reads an agent sender's `steer` as `queue` unless the client advertises the `agent_active_turn_behaviors` capability. A new client talking to a daemon without `server_info.features.agentActiveTurnBehaviors` sends no behavior for `queue` and refuses a `steer`. A new client talking to a daemon without `server_info.features.nonAgentMessageQueue` refuses a non-agent `queue` before sending.
|
||||
|
||||
@@ -173,8 +173,8 @@ One provider prompt has one session mode. A batch released by a steer, an interr
|
||||
A provider switch can wait in the queue too (`agent.provider.switch.request` with
|
||||
`activeTurnBehavior: "queue"`). The message carries the target provider and settings, shares a prompt
|
||||
with nothing, and divides the queue: what is ahead of it goes to the current provider, and it and
|
||||
what follows go to the target. A direct prompt therefore takes along only the queued rows ahead of
|
||||
the switch. Promoting the switch cuts the running turn once the target is known to be usable. A chat
|
||||
what follows go to the target. A direct provider switch queues right behind any items queued for
|
||||
the current provider so those items dispatch first. Promoting the switch cuts the running turn once the target is known to be usable. A chat
|
||||
already on the target takes the message and its settings as a plain prompt. A switch that fails keeps
|
||||
the message and holds the queue; the reason is in the daemon log.
|
||||
|
||||
@@ -184,10 +184,10 @@ queue holds references. An empty message is refused, and a recipient holds at mo
|
||||
messages.
|
||||
|
||||
A message is marked `dispatching` before the provider can receive it and removed when the provider
|
||||
admits it. A dispatch that is not admitted returns the message to its place. A refused turn start
|
||||
also holds the queue: retrying by itself would be refused again and would add the prompt to the
|
||||
history each time. A message that cannot be sent is removed so that it does not block the ones
|
||||
behind it.
|
||||
admits it. A dispatch that fails transiently (busy/non-steering turn, run-start timeout, mode/RPC
|
||||
error, or rejected start) returns the batch to the queue rather than deleting it; non-busy failures
|
||||
also hold the queue until the next prompt reopens it. Only pre-dispatch unresolvable payloads (such
|
||||
as missing local attachments) or rejected out-of-band commands are discarded so they do not block later messages.
|
||||
|
||||
Shutdown does not send the queue. It waits only for dispatches already in flight, and everything
|
||||
else stays saved, held messages included. Closing an idle runtime keeps the queue. Archiving or
|
||||
@@ -456,8 +456,8 @@ Rows take these commands:
|
||||
already started sending the row, the draft stays as it is.
|
||||
- **Cancel** withdraws the row.
|
||||
|
||||
A message you send directly (`steer` or `interrupt`) takes the queued rows with it, ahead of your
|
||||
text.
|
||||
A message you send directly (`steer` or `interrupt`) runs right away without sweeping the queue track;
|
||||
queued rows stay visible in place and dispatch after the turn ends (unless held by Stop).
|
||||
|
||||
A message sent mid-turn with a staged provider switch is queued whatever the send behavior, and its
|
||||
row names the target.
|
||||
|
||||
+1
-1
@@ -58,7 +58,7 @@ Authoritative terminology. UI label wins. Don't invent synonyms; use what's here
|
||||
- **Agent controls** — Provider, model, mode, thinking, and provider-feature controls for an agent or draft agent. Code: `AgentControls` / `DraftAgentControls` (`packages/app/src/composer/agent-controls/index.tsx`). Forbidden: "Agent status bar".
|
||||
- **Composer footer** — Optional area rendered below the composer input but still inside the keyboard-shifted composer layout. Code: `Composer.footer` (`packages/app/src/composer/index.tsx`).
|
||||
- **Composer track** — A contextual lane at the foot of a pane, by the composer input. Specific tracks use the `<thing> track` form: **Queue track**, **Subagents track**, **Tasks track**. The subagents and tasks tracks are pills floating over the transcript, each opening a panel with its rows; the [queue track](agent-lifecycle.md#the-queue-track) is a lane inside the composer itself. Code: `ComposerQueueTrack` (`packages/app/src/composer/queue/track.tsx`), pill and panel frame in `packages/app/src/composer/tracks.tsx`, `SubagentsTrack` (`packages/app/src/subagents/track.tsx`), `AgentTaskList` (`packages/app/src/composer/task-list/index.tsx`).
|
||||
- **Steer** — A follow-up admitted into an agent's already-running turn instead of interrupting it. Interrupting the turn discards steers the provider has not read yet; there is no take-back short of that, and no provider offers one. The stop button and Escape both interrupt. A steer the provider never read keeps its transcript row, matching Codex. Sending while the agent waits on a permission denies that request first, so the message reaches the same turn instead of stalling behind it. UI: "Send and steer". Code: `steerActiveTurn` (`packages/server/src/server/agent/agent-sdk-types.ts`). Don't confuse with **Queue track**, which lists the messages the host holds until the turn ends. A queued message does not enter the running turn. An agent sender's `activeTurnBehavior: "steer"` (CLI `--behavior steer`) means the same as a person's steer. Agent senders default to `queue` instead: the daemon holds the message until the running turn ends, as it does for a person's queued message. Forbidden: "Delivery", "Queued prompt".
|
||||
- **Steer** — A follow-up admitted into an agent's already-running turn instead of interrupting it. Interrupting the turn discards steers the provider has not read yet; there is no take-back short of that, and no provider offers one. The stop button and Escape both interrupt. A steer the provider never read keeps its transcript row, matching Codex. Sending while the agent waits on a permission denies that request first, so the message reaches the same turn instead of stalling behind it. UI: "Send and steer". Code: `steerActiveTurn` (`packages/server/src/server/agent/agent-sdk-types.ts`). Don't confuse with **Queue track**, which lists the messages the host holds until the turn ends. A queued message does not enter the running turn, and a person's direct steer leaves queued rows in the queue track. Agent senders and finish notifications default to `steer` (falling back to `queue` when the provider cannot steer) and never sweep human-queued items. Forbidden: "Delivery", "Queued prompt".
|
||||
- **Subagent** — User-facing term for an agent session related to a parent agent session. Use **subagents** in UI copy and docs. Internal daemon/provider plumbing may say "child agent" or `child_session`, especially for provider-managed imports; do not surface "child agent" as a product term.
|
||||
- **Attachment tray** — The selected-attachments row inside the composer input, above the text input. Code: `renderAttachmentTray` (`packages/app/src/composer/index.tsx`). Forbidden: "Attachment bar".
|
||||
- **Fork** — Starting a NEW agent session seeded with a copy of another session's curated chat history. The history rides along as a `chat_history` composer attachment on a draft; the fork does **not** resume or branch the provider-side session, and the source session keeps running untouched. Two targets, one surface, one RPC (`agent.fork_context`, gated on the `agentForkContext` host feature). UI: the fork menu lives in the assistant turn footer and offers "Fork in a new tab" / "Fork in a new workspace". On a **completed** turn it sits beside the copy button and pins a boundary to that turn, so the fork stops where the turn ended. On the **in-flight** turn it sits beside the progress loader and elapsed timer, and omits the boundary entirely — `selectForkContextRows` projects the whole timeline when no boundary is given, so the fork captures everything **up to now**, including the response still streaming. That omission is what makes mid-run forking work; pinning a boundary there would silently drop the live response. Forbidden on provider-subagent (read-only) panes. Code: `useForkAgent` (`packages/app/src/hooks/use-fork-agent.ts`), `selectForkContextRows` (`packages/server/src/server/agent/activity-curator.ts`). Don't confuse with: git fork (unrelated; Paseo has no such concept), **Worktree** (filesystem isolation, not history copying).
|
||||
|
||||
@@ -971,6 +971,8 @@ question.
|
||||
you got wrong, rank every highlight again, and then edit the file. Moving only the named item
|
||||
leaves the same mistake in the others.
|
||||
|
||||
Order sections as `Breaking`, `Security`, `Added`, `Improved`, `Changed`, `Plugins`, `Fixed` (omitting empty sections) so `Security` and `Plugins` stay visible above a long `Fixed` list.
|
||||
|
||||
Bullets within each section (Added, Changed, Fixed) follow this order:
|
||||
|
||||
1. **User-facing features and changes first** — things users will notice, want to try, or that change their workflow.
|
||||
|
||||
@@ -97,13 +97,19 @@ Two more reasons the stylesheet route does not work here:
|
||||
- Unistyles owns style conversion on web, so React Native Web's `animationKeyframes` is ignored.
|
||||
- React Native Web's `StyleSheet.create` validation deletes `animationName` in development.
|
||||
|
||||
Indicators that must move together use `phase: "shared"`, which starts the loop at the document
|
||||
timeline's origin instead of at mount. Every ring and every loader is then at the same point of its
|
||||
Indicators that must move together use `phase: "shared"`, which starts the loop at the step
|
||||
grid's origin instead of at mount. Every ring and every loader is then at the same point of its
|
||||
cycle wherever and whenever it mounted. `phase: "own"` starts the loop at the beginning of the
|
||||
current grid step, so its steps still turn over with the shared loops. A stepped animation sets its easing on the keyframes:
|
||||
`step-end` to hold each keyframe until the next, `steps(n)` to cross between two keyframes in `n`
|
||||
even steps. The compositor then draws a frame when a step changes and none in between.
|
||||
|
||||
The grid's origin is 2.5 µs after the document timeline's, not at it. Browsers stamp frames on
|
||||
whole microseconds, and each loop computes a step boundary from its own duration. A boundary that
|
||||
falls exactly on a frame's stamp can then round to before that frame for the ring and after it for
|
||||
the shimmer, so they turn over on consecutive frames. With the origin at 0, every third boundary is
|
||||
a whole millisecond and lands on a stamp. Off by 2.5 µs, no boundary does.
|
||||
|
||||
## Native
|
||||
|
||||
Reanimated commits a cloned shadow tree on the UI thread for every frame a shared value changes.
|
||||
|
||||
+1
-1
@@ -1 +1 @@
|
||||
sha256-oBd6CQ8+BhzMHhrpRIwzojuFPUwqXpgc3ZAPqKPs5QQ=
|
||||
sha256-6NRyu5y01d/Hx79kROAwN6xjlTJ4sYWi0LuTQiJ+Zjw=
|
||||
|
||||
@@ -20,6 +20,9 @@ import {
|
||||
readTerminalProcessIds,
|
||||
} from "../support/helpers/daemon-lifecycle";
|
||||
|
||||
// Page setup takes up to 30 s, then a restart can take DAEMON_RESTART_TIMEOUT_MS to confirm.
|
||||
test.describe.configure({ timeout: 120_000 });
|
||||
|
||||
test("settings restart waits for a replacement worker while retaining the supervisor", async ({
|
||||
page,
|
||||
}, testInfo) => {
|
||||
|
||||
@@ -131,6 +131,11 @@ test.describe("Running indicators", () => {
|
||||
test.setTimeout(180_000);
|
||||
const scene = await openIdleChatBesideRunningAgent(page);
|
||||
try {
|
||||
// Once the chat has settled, nothing but rings is moving, so every frame drawn is a ring's.
|
||||
// A 200 ms border-colour transition in the composer can still be running as the chat opens.
|
||||
await expect
|
||||
.poll(async () => new Set(await readAnimatingTargets(page)))
|
||||
.toEqual(new Set(["status-ring"]));
|
||||
const animating = await readAnimatingTargets(page);
|
||||
const activity = await measureSteadyStateActivity({
|
||||
browser,
|
||||
@@ -143,8 +148,6 @@ test.describe("Running indicators", () => {
|
||||
JSON.stringify({ animating, activity, angles }, null, 2),
|
||||
);
|
||||
|
||||
// Nothing but rings is moving, so every frame drawn is a ring's.
|
||||
expect.soft(new Set(animating)).toEqual(new Set(["status-ring"]));
|
||||
expect
|
||||
.soft(activity.compositorFramesPerSecond)
|
||||
.toBeLessThan(RING_ONLY_FRAMES_PER_SECOND_BUDGET);
|
||||
|
||||
@@ -337,6 +337,20 @@ test("Add host draws its text fields as bordered inputs", async ({ page }) => {
|
||||
});
|
||||
});
|
||||
|
||||
test("Space toggles the focused Use SSL checkbox in the direct host form", async ({ page }) => {
|
||||
await gotoAppShell(page);
|
||||
await openSidebarAddHost(page);
|
||||
await selectHostConnectionType(page, "direct");
|
||||
const checkbox = page.getByRole("checkbox", { name: "Use SSL", exact: true });
|
||||
const initial = await checkbox.isChecked();
|
||||
await checkbox.focus();
|
||||
await checkbox.press("Space");
|
||||
await expect(checkbox).toBeChecked({ checked: !initial });
|
||||
await expect(checkbox).toBeFocused();
|
||||
await checkbox.press("Space");
|
||||
await expect(checkbox).toBeChecked({ checked: initial });
|
||||
});
|
||||
|
||||
test("sidebar Add host completes without navigating", async ({ page }) => {
|
||||
await gotoAppShell(page);
|
||||
await expect(page).toHaveURL(/\/open-project$/);
|
||||
|
||||
@@ -33,16 +33,20 @@ export async function restartDaemonInSettings(
|
||||
await expect(page.getByRole("button", { name: "Restarting...", exact: true })).toBeDisabled();
|
||||
}
|
||||
|
||||
// The app reads the replacement worker only after it reconnects. Reconnect attempts back off
|
||||
// (1.5 s doubling to a 30 s cap), so the result can trail a ready worker by up to 30 s.
|
||||
export const DAEMON_RESTART_TIMEOUT_MS = 75_000;
|
||||
|
||||
export async function expectDaemonRestartFailed(page: Page, text: string) {
|
||||
const error = page.getByTestId("host-page-restart-error");
|
||||
await expect(error).toBeVisible({ timeout: 30_000 });
|
||||
await expect(error).toBeVisible({ timeout: DAEMON_RESTART_TIMEOUT_MS });
|
||||
await expect(error).toContainText(text);
|
||||
await expect(page.getByRole("button", { name: "Restart", exact: true })).toBeEnabled();
|
||||
}
|
||||
|
||||
export async function expectDaemonRestartComplete(page: Page) {
|
||||
await expect(page.getByRole("button", { name: "Restart", exact: true })).toBeEnabled({
|
||||
timeout: 30_000,
|
||||
timeout: DAEMON_RESTART_TIMEOUT_MS,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
import { act } from "react";
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
import { View } from "react-native";
|
||||
import { afterEach, expect, it } from "vitest";
|
||||
import { STATUS_RING_PERIOD_MS, STATUS_RING_STEPS } from "@/components/status-ring/geometry";
|
||||
import { type IndicatorLoop, useIndicatorLoop } from "./loop.web";
|
||||
import { INDICATOR_STEP_MS } from "./steps";
|
||||
|
||||
// A ring and a shimmer: two stepped loops of different lengths on the step grid, one counted from
|
||||
// the timeline's origin and one from the step it started in.
|
||||
const RING: IndicatorLoop = {
|
||||
keyframes: [
|
||||
{ transform: "rotate(0deg)", easing: `steps(${STATUS_RING_STEPS})` },
|
||||
{ transform: "rotate(360deg)" },
|
||||
],
|
||||
durationMs: STATUS_RING_PERIOD_MS,
|
||||
phase: "shared",
|
||||
};
|
||||
const SHIMMER_STEPS = 42;
|
||||
const SHIMMER: IndicatorLoop = {
|
||||
keyframes: [
|
||||
{ transform: "translateX(-100px)", easing: `steps(${SHIMMER_STEPS})` },
|
||||
{ transform: "translateX(300px)" },
|
||||
],
|
||||
durationMs: SHIMMER_STEPS * INDICATOR_STEP_MS,
|
||||
phase: "own",
|
||||
};
|
||||
|
||||
function Indicators() {
|
||||
const ringRef = useIndicatorLoop(RING);
|
||||
const shimmerRef = useIndicatorLoop(SHIMMER);
|
||||
return (
|
||||
<>
|
||||
<View ref={ringRef} testID="ring" />
|
||||
<View ref={shimmerRef} testID="shimmer" />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
let root: Root | null = null;
|
||||
|
||||
afterEach(() => {
|
||||
act(() => root?.unmount());
|
||||
root = null;
|
||||
document.body.innerHTML = "";
|
||||
});
|
||||
|
||||
function mountIndicators(): { ring: Animation; shimmer: Animation } {
|
||||
const container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
root = createRoot(container);
|
||||
act(() => root!.render(<Indicators />));
|
||||
const animationOf = (testId: string) => {
|
||||
const element = container.querySelector(`[data-testid="${testId}"]`);
|
||||
const animation = element?.getAnimations()[0];
|
||||
if (!animation) throw new Error(`${testId} is not animating`);
|
||||
return animation;
|
||||
};
|
||||
return { ring: animationOf("ring"), shimmer: animationOf("shimmer") };
|
||||
}
|
||||
|
||||
/**
|
||||
* Steps through every timeline time, on the microsecond marks a browser stamps frames at, around
|
||||
* each of the grid's next `boundaries` step boundaries. Reports how often each loop turned over and
|
||||
* the times at which one of the two turned over and the other did not.
|
||||
*/
|
||||
function sweepBoundaries(
|
||||
loops: { ring: Animation; shimmer: Animation },
|
||||
boundaries: number,
|
||||
): { ringTurnovers: number; shimmerTurnovers: number; turningOneLoop: number[] } {
|
||||
const elements = {
|
||||
ring: loops.ring.effect as KeyframeEffect,
|
||||
shimmer: loops.shimmer.effect as KeyframeEffect,
|
||||
};
|
||||
const startTimes = {
|
||||
ring: Number(loops.ring.startTime),
|
||||
shimmer: Number(loops.shimmer.startTime),
|
||||
};
|
||||
loops.ring.pause();
|
||||
loops.shimmer.pause();
|
||||
const showAt = (timelineMs: number) => {
|
||||
loops.ring.currentTime = timelineMs - startTimes.ring;
|
||||
loops.shimmer.currentTime = timelineMs - startTimes.shimmer;
|
||||
return {
|
||||
ring: getComputedStyle(elements.ring.target!).transform,
|
||||
shimmer: getComputedStyle(elements.shimmer.target!).transform,
|
||||
};
|
||||
};
|
||||
|
||||
const firstStep = Math.ceil(startTimes.shimmer / INDICATOR_STEP_MS) + 1;
|
||||
const turnovers = { ringTurnovers: 0, shimmerTurnovers: 0, turningOneLoop: [] as number[] };
|
||||
for (let step = firstStep; step < firstStep + boundaries; step += 1) {
|
||||
const boundaryUs = Math.round(step * INDICATOR_STEP_MS * 1000);
|
||||
let previous = showAt((boundaryUs - 20) / 1000);
|
||||
for (let frameUs = boundaryUs - 19; frameUs <= boundaryUs + 20; frameUs += 1) {
|
||||
const current = showAt(frameUs / 1000);
|
||||
const ringTurned = current.ring !== previous.ring;
|
||||
const shimmerTurned = current.shimmer !== previous.shimmer;
|
||||
if (ringTurned) turnovers.ringTurnovers += 1;
|
||||
if (shimmerTurned) turnovers.shimmerTurnovers += 1;
|
||||
if (ringTurned !== shimmerTurned) {
|
||||
turnovers.turningOneLoop.push(frameUs / 1000);
|
||||
}
|
||||
previous = current;
|
||||
}
|
||||
}
|
||||
return turnovers;
|
||||
}
|
||||
|
||||
it("turns loops of different lengths over on the same frame, whenever the frame is stamped", () => {
|
||||
const loops = mountIndicators();
|
||||
|
||||
// Each loop turns over once at every boundary, and never on a frame without the other.
|
||||
expect(sweepBoundaries(loops, 300)).toEqual({
|
||||
ringTurnovers: 300,
|
||||
shimmerTurnovers: 300,
|
||||
turningOneLoop: [],
|
||||
});
|
||||
});
|
||||
@@ -2,7 +2,14 @@ import { useLayoutEffect, useRef, type RefObject } from "react";
|
||||
import type { View } from "react-native";
|
||||
import { INDICATOR_STEP_MS } from "./steps";
|
||||
|
||||
const TIMELINE_ORIGIN_MS = 0;
|
||||
// Where the step grid starts on the document timeline. Browsers stamp a frame at a whole number of
|
||||
// microseconds, often coarsened to 5 or 100. Each loop works out a step boundary from its own
|
||||
// duration, so floating-point rounding can put a boundary that falls exactly on a frame's stamp
|
||||
// before that frame for one loop and after it for another: the two then turn over on consecutive
|
||||
// frames, and the window draws one more. Every third boundary of a grid from 0 is a whole number of
|
||||
// milliseconds and so falls on a stamp. Starting the grid 2.5 µs in keeps every boundary at least
|
||||
// a sixth of a microsecond from any stamp, far beyond the rounding.
|
||||
const STEP_GRID_ORIGIN_MS = 0.0025;
|
||||
|
||||
export interface IndicatorLoop {
|
||||
/** One cycle. Keep the array's identity stable: a new array restarts the loop. */
|
||||
@@ -10,7 +17,7 @@ export interface IndicatorLoop {
|
||||
durationMs: number;
|
||||
/**
|
||||
* `shared` puts every instance at the same point of the cycle, wherever and whenever it mounted:
|
||||
* the loop counts from the document timeline's origin instead of from its own start. `own` starts
|
||||
* the loop counts from the step grid's origin instead of from its own start. `own` starts
|
||||
* the cycle at the step of the indicator step grid the loop starts in, so a stepped loop turns
|
||||
* over with every other; see `steps.ts`.
|
||||
*/
|
||||
@@ -19,8 +26,8 @@ export interface IndicatorLoop {
|
||||
|
||||
// The start of the step of the indicator step grid the document timeline is in now.
|
||||
function currentStepStartMs(): number {
|
||||
const now = Number(document.timeline.currentTime ?? 0);
|
||||
return Math.floor(now / INDICATOR_STEP_MS) * INDICATOR_STEP_MS;
|
||||
const sinceOrigin = Number(document.timeline.currentTime ?? 0) - STEP_GRID_ORIGIN_MS;
|
||||
return STEP_GRID_ORIGIN_MS + Math.floor(sinceOrigin / INDICATOR_STEP_MS) * INDICATOR_STEP_MS;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -47,7 +54,7 @@ export function useIndicatorLoop(loop: IndicatorLoop | null): RefObject<View | n
|
||||
iterations: Number.POSITIVE_INFINITY,
|
||||
});
|
||||
// An explicit start also keeps loops that start in the same commit exactly together.
|
||||
animation.startTime = loop.phase === "shared" ? TIMELINE_ORIGIN_MS : currentStepStartMs();
|
||||
animation.startTime = loop.phase === "shared" ? STEP_GRID_ORIGIN_MS : currentStepStartMs();
|
||||
return () => {
|
||||
animation.cancel();
|
||||
};
|
||||
|
||||
@@ -18,6 +18,21 @@ export function Checkbox({ checked }: { checked: boolean }) {
|
||||
);
|
||||
}
|
||||
|
||||
/** React Native Web checkboxes need an explicit Space handler when built on Pressable. */
|
||||
export function useCheckboxSpaceKey(onToggle: () => void, disabled: boolean) {
|
||||
return useMemo(() => {
|
||||
if (!isWeb || disabled) return {};
|
||||
return {
|
||||
onKeyDown: (event: { key?: string; preventDefault?: () => void }) => {
|
||||
if (event.key === " " || event.key === "Spacebar") {
|
||||
event.preventDefault?.();
|
||||
onToggle();
|
||||
}
|
||||
},
|
||||
};
|
||||
}, [disabled, onToggle]);
|
||||
}
|
||||
|
||||
interface HoverState {
|
||||
hovered?: boolean;
|
||||
}
|
||||
@@ -48,18 +63,7 @@ export function CheckboxRow({
|
||||
({ hovered }: HoverState) => [style, hovered && !disabled ? styles.hovered : null],
|
||||
[disabled, style],
|
||||
);
|
||||
const keyProps = useMemo(() => {
|
||||
if (!isWeb || disabled) return {};
|
||||
return {
|
||||
// React Native Web's Pressable activates Space only for role="button", not checkbox.
|
||||
onKeyDown: (event: { key?: string; preventDefault?: () => void }) => {
|
||||
if (event.key === " " || event.key === "Spacebar") {
|
||||
event.preventDefault?.();
|
||||
onToggle();
|
||||
}
|
||||
},
|
||||
};
|
||||
}, [disabled, onToggle]);
|
||||
const keyProps = useCheckboxSpaceKey(onToggle, disabled);
|
||||
|
||||
return (
|
||||
<PressHighlight
|
||||
|
||||
@@ -2,8 +2,9 @@ import { beforeEach, describe, expect, test, vi } from "vitest";
|
||||
import type { SessionInboundMessage, SessionOutboundMessage } from "@getpaseo/protocol/messages";
|
||||
import { createJSONStorage, type StateStorage } from "zustand/middleware";
|
||||
import { mountBrowserAutomationHandler, type BrowserAutomationHandlerOptions } from "./handler";
|
||||
import type { DesktopHostBridge } from "@/desktop/host";
|
||||
import type { DesktopAutomationExecutionContext, DesktopHostBridge } from "@/desktop/host";
|
||||
import { useBrowserStore } from "@/desktop/browser/store";
|
||||
import { useSessionStore } from "@/stores/session-store";
|
||||
import { findPaneById } from "@/stores/workspace-layout-actions";
|
||||
import { useWorkspaceLayoutStore } from "@/stores/workspace-layout-store";
|
||||
import { buildWorkspaceTabPersistenceKey } from "@/workspace-tabs/model";
|
||||
@@ -72,9 +73,11 @@ class FakeDaemonClient {
|
||||
|
||||
class FakeBrowserBridge {
|
||||
public readonly executedRequests: BrowserAutomationExecuteRequest[] = [];
|
||||
public readonly executedContexts: DesktopAutomationExecutionContext[] = [];
|
||||
public readonly unregisteredWorkspaceBrowsers: string[] = [];
|
||||
public readonly activeWorkspaceBrowsers: Array<{
|
||||
browserId: string | null;
|
||||
serverId: string;
|
||||
workspaceId: string;
|
||||
}> = [];
|
||||
public response: BrowserAutomationResponsePayload | null = null;
|
||||
@@ -82,8 +85,10 @@ class FakeBrowserBridge {
|
||||
|
||||
public executeAutomationCommand = async (
|
||||
request: BrowserAutomationExecuteRequest,
|
||||
context: DesktopAutomationExecutionContext,
|
||||
): Promise<BrowserAutomationResponsePayload> => {
|
||||
this.executedRequests.push(request);
|
||||
this.executedContexts.push(context);
|
||||
if (this.thrownError) {
|
||||
throw this.thrownError;
|
||||
}
|
||||
@@ -96,6 +101,7 @@ class FakeBrowserBridge {
|
||||
|
||||
public setWorkspaceActiveBrowser = async (input: {
|
||||
browserId: string | null;
|
||||
serverId: string;
|
||||
workspaceId: string;
|
||||
}): Promise<void> => {
|
||||
this.activeWorkspaceBrowsers.push(input);
|
||||
@@ -105,6 +111,7 @@ class FakeBrowserBridge {
|
||||
class FakeResidentBrowser {
|
||||
public readonly ensuredWebviews: Array<{
|
||||
browserId: string;
|
||||
serverId: string;
|
||||
workspaceId: string;
|
||||
url: string;
|
||||
partition?: string;
|
||||
@@ -112,6 +119,7 @@ class FakeResidentBrowser {
|
||||
|
||||
public ensure = (input: {
|
||||
browserId: string;
|
||||
serverId: string;
|
||||
workspaceId: string;
|
||||
url: string;
|
||||
partition?: string;
|
||||
@@ -131,20 +139,22 @@ class BrowserAutomationHandlerHarness {
|
||||
input: {
|
||||
serverId?: string;
|
||||
host?: DesktopHostBridge | null;
|
||||
readHostBrowserRouting?: BrowserAutomationHandlerOptions["readHostBrowserRouting"];
|
||||
readHostBrowserRouting?: BrowserAutomationHandlerOptions["readHostBrowserRouting"] | null;
|
||||
prepareHostBrowserPartition?: BrowserAutomationHandlerOptions["prepareHostBrowserPartition"];
|
||||
registrationWaitTimeoutMs?: number;
|
||||
registrationPollIntervalMs?: number;
|
||||
} = {},
|
||||
): void {
|
||||
const readHostBrowserRouting =
|
||||
input.readHostBrowserRouting === null
|
||||
? undefined
|
||||
: (input.readHostBrowserRouting ?? (() => ({ kind: "local" as const })));
|
||||
this.unsubscribe = mountBrowserAutomationHandler({
|
||||
client: this.client,
|
||||
...(input.serverId ? { serverId: input.serverId } : {}),
|
||||
getHost: () => (input.host === undefined ? { browser: this.browser } : input.host),
|
||||
ensureResidentBrowserWebview: this.resident.ensure,
|
||||
...(input.readHostBrowserRouting
|
||||
? { readHostBrowserRouting: input.readHostBrowserRouting }
|
||||
: {}),
|
||||
...(readHostBrowserRouting ? { readHostBrowserRouting } : {}),
|
||||
...(input.prepareHostBrowserPartition
|
||||
? { prepareHostBrowserPartition: input.prepareHostBrowserPartition }
|
||||
: {}),
|
||||
@@ -167,10 +177,14 @@ class BrowserAutomationHandlerHarness {
|
||||
}
|
||||
}
|
||||
|
||||
function browserAutomationRequest(): BrowserAutomationExecuteRequest {
|
||||
function browserAutomationRequest(input?: {
|
||||
workspaceId?: string;
|
||||
}): BrowserAutomationExecuteRequest {
|
||||
const workspaceId = input && "workspaceId" in input ? input.workspaceId : "wks_workspace_a";
|
||||
return {
|
||||
type: "browser.automation.execute.request",
|
||||
requestId: "req-1",
|
||||
...(workspaceId ? { workspaceId } : {}),
|
||||
command: { command: "list_tabs", args: {} },
|
||||
};
|
||||
}
|
||||
@@ -294,6 +308,7 @@ describe("mountBrowserAutomationHandler", () => {
|
||||
browserAutomationStorage.clear();
|
||||
useBrowserStore.setState({ browsersById: {} });
|
||||
useWorkspaceLayoutStore.setState({ layoutByWorkspace: {} });
|
||||
useSessionStore.setState({ sessions: {} });
|
||||
});
|
||||
|
||||
test("browser_new_tab creates a workspace browser tab without stealing focus", async () => {
|
||||
@@ -338,6 +353,7 @@ describe("mountBrowserAutomationHandler", () => {
|
||||
expect(browser.resident.ensuredWebviews).toEqual([
|
||||
{
|
||||
browserId: result.browserId,
|
||||
serverId: "server-1",
|
||||
workspaceId: "wks_workspace_a",
|
||||
url: "https://example.com",
|
||||
},
|
||||
@@ -543,13 +559,14 @@ describe("mountBrowserAutomationHandler", () => {
|
||||
ok: true,
|
||||
result: { command: "list_tabs", tabs: [] },
|
||||
};
|
||||
browser.mount();
|
||||
browser.mount({ serverId: "server-1" });
|
||||
const request = browserAutomationRequest();
|
||||
|
||||
browser.receive(request);
|
||||
await flushAsyncWork();
|
||||
|
||||
expect(browser.browser.executedRequests).toEqual([request]);
|
||||
expect(browser.browser.executedContexts).toEqual([{ serverId: "server-1", uploadRoot: null }]);
|
||||
expect(browser.client.sentResponses).toEqual([
|
||||
{
|
||||
type: "browser.automation.execute.response",
|
||||
@@ -564,7 +581,7 @@ describe("mountBrowserAutomationHandler", () => {
|
||||
|
||||
test("missing desktop bridge sends browser_unsupported", async () => {
|
||||
const browser = new BrowserAutomationHandlerHarness();
|
||||
browser.mount({ host: null });
|
||||
browser.mount({ serverId: "server-1", host: null });
|
||||
|
||||
browser.receive(browserAutomationRequest());
|
||||
await flushAsyncWork();
|
||||
@@ -592,7 +609,7 @@ describe("mountBrowserAutomationHandler", () => {
|
||||
message: "Browser tab browser-1 was not found.",
|
||||
retryable: false,
|
||||
};
|
||||
browser.mount();
|
||||
browser.mount({ serverId: "server-1" });
|
||||
|
||||
browser.receive(browserAutomationRequest());
|
||||
await flushAsyncWork();
|
||||
@@ -618,7 +635,7 @@ describe("mountBrowserAutomationHandler", () => {
|
||||
browser.browser.thrownError = new Error(
|
||||
'No handler registered for "paseo:browser:execute-automation-command"',
|
||||
);
|
||||
browser.mount();
|
||||
browser.mount({ serverId: "server-1" });
|
||||
|
||||
browser.receive(browserAutomationRequest());
|
||||
await flushAsyncWork();
|
||||
@@ -641,7 +658,7 @@ describe("mountBrowserAutomationHandler", () => {
|
||||
|
||||
test("unsubscribe stops handling browser automation requests", async () => {
|
||||
const browser = new BrowserAutomationHandlerHarness();
|
||||
browser.mount();
|
||||
browser.mount({ serverId: "server-1" });
|
||||
|
||||
browser.unmount();
|
||||
browser.receive(browserAutomationRequest());
|
||||
@@ -680,6 +697,7 @@ describe("mountBrowserAutomationHandler", () => {
|
||||
expect(browser.resident.ensuredWebviews).toEqual([
|
||||
{
|
||||
browserId: result.browserId,
|
||||
serverId: "remote-1",
|
||||
workspaceId: "wks_workspace_a",
|
||||
url: "http://localhost:5173",
|
||||
partition: "persist:paseo-browser-host-0123456789abcdef",
|
||||
@@ -687,6 +705,165 @@ describe("mountBrowserAutomationHandler", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
test("browser_resize fails closed when workspaceId is omitted", async () => {
|
||||
const browser = new BrowserAutomationHandlerHarness();
|
||||
browser.mount({ serverId: "server-1" });
|
||||
|
||||
browser.receive(browserNewTabRequest());
|
||||
await vi.waitFor(() => expect(browser.client.sentResponses).toHaveLength(1));
|
||||
const result = newTabResultFrom(browser.client.payloadAt(0));
|
||||
|
||||
browser.receive({
|
||||
type: "browser.automation.execute.request",
|
||||
requestId: "req-resize-no-ws",
|
||||
agentId: "agent-1",
|
||||
command: {
|
||||
command: "resize",
|
||||
args: { browserId: result.browserId, width: 800, height: 600 },
|
||||
},
|
||||
});
|
||||
await flushAsyncWork();
|
||||
|
||||
expect(browser.client.payloadAt(1)).toEqual({
|
||||
requestId: "req-resize-no-ws",
|
||||
ok: false,
|
||||
error: {
|
||||
code: "browser_denied",
|
||||
message: expect.stringMatching(/workspace/i),
|
||||
retryable: false,
|
||||
},
|
||||
});
|
||||
expect(useBrowserStore.getState().browsersById[result.browserId]?.viewport).toEqual({
|
||||
mode: "responsive",
|
||||
});
|
||||
});
|
||||
|
||||
test("forwarded commands fail closed when workspaceId is omitted", async () => {
|
||||
const browser = new BrowserAutomationHandlerHarness();
|
||||
browser.mount({ serverId: "server-1" });
|
||||
|
||||
browser.receive(browserAutomationRequest({ workspaceId: "" }));
|
||||
await flushAsyncWork();
|
||||
|
||||
expect(browser.browser.executedRequests).toEqual([]);
|
||||
expect(browser.client.payloadAt(0)).toEqual({
|
||||
requestId: "req-1",
|
||||
ok: false,
|
||||
error: {
|
||||
code: "browser_denied",
|
||||
message: expect.stringMatching(/workspace/i),
|
||||
retryable: false,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
test("passes uploadRoot from session-store for local hosts and null for remote hosts", async () => {
|
||||
const store = useSessionStore.getState();
|
||||
store.initializeSession("local-1", null);
|
||||
store.mergeWorkspaces("local-1", [
|
||||
{
|
||||
id: "wks_workspace_a",
|
||||
projectId: "proj-1",
|
||||
projectDisplayName: "Project",
|
||||
projectRootPath: "/Users/dev/project",
|
||||
workspaceDirectory: "/Users/dev/project",
|
||||
projectKind: "git",
|
||||
workspaceKind: "directory",
|
||||
name: "Project",
|
||||
title: "Project",
|
||||
status: "done",
|
||||
statusEnteredAt: null,
|
||||
createdAt: null,
|
||||
lastUserMessageAt: null,
|
||||
archivingAt: null,
|
||||
diffStat: null,
|
||||
scripts: [],
|
||||
},
|
||||
]);
|
||||
store.initializeSession("remote-1", null);
|
||||
store.mergeWorkspaces("remote-1", [
|
||||
{
|
||||
id: "wks_workspace_a",
|
||||
projectId: "proj-2",
|
||||
projectDisplayName: "Remote Project",
|
||||
projectRootPath: "/home/remote/project",
|
||||
workspaceDirectory: "/home/remote/project",
|
||||
projectKind: "git",
|
||||
workspaceKind: "directory",
|
||||
name: "Remote Project",
|
||||
title: "Remote Project",
|
||||
status: "done",
|
||||
statusEnteredAt: null,
|
||||
createdAt: null,
|
||||
lastUserMessageAt: null,
|
||||
archivingAt: null,
|
||||
diffStat: null,
|
||||
scripts: [],
|
||||
},
|
||||
]);
|
||||
|
||||
const uploadRequest: BrowserAutomationExecuteRequest = {
|
||||
type: "browser.automation.execute.request",
|
||||
requestId: "req-upload",
|
||||
workspaceId: "wks_workspace_a",
|
||||
cwd: "/Users/dev/project",
|
||||
command: {
|
||||
command: "upload",
|
||||
args: {
|
||||
browserId: "11111111-1111-4111-8111-111111111111",
|
||||
ref: "@e1",
|
||||
filePaths: ["a.txt"],
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const localHarness = new BrowserAutomationHandlerHarness();
|
||||
localHarness.mount({
|
||||
serverId: "local-1",
|
||||
readHostBrowserRouting: () => ({ kind: "local" }),
|
||||
});
|
||||
localHarness.receive(uploadRequest);
|
||||
await flushAsyncWork();
|
||||
expect(localHarness.browser.executedContexts).toEqual([
|
||||
{ serverId: "local-1", uploadRoot: "/Users/dev/project" },
|
||||
]);
|
||||
|
||||
const remoteHarness = new BrowserAutomationHandlerHarness();
|
||||
remoteHarness.mount({
|
||||
serverId: "remote-1",
|
||||
readHostBrowserRouting: () => ({
|
||||
kind: "remote",
|
||||
support: "supported",
|
||||
target: "tcp://10.0.0.5:6767",
|
||||
}),
|
||||
});
|
||||
remoteHarness.receive(uploadRequest);
|
||||
await flushAsyncWork();
|
||||
expect(remoteHarness.browser.executedContexts).toEqual([
|
||||
{ serverId: "remote-1", uploadRoot: null },
|
||||
]);
|
||||
});
|
||||
|
||||
test("browser_new_tab on an unhydrated host fails closed without opening a local webview", async () => {
|
||||
const browser = new BrowserAutomationHandlerHarness();
|
||||
browser.mount({
|
||||
serverId: "unhydrated-host-id",
|
||||
readHostBrowserRouting: null,
|
||||
});
|
||||
|
||||
browser.receive(browserNewTabRequest({ url: "http://localhost:5173" }));
|
||||
await flushAsyncWork();
|
||||
|
||||
expect(browser.resident.ensuredWebviews).toEqual([]);
|
||||
expect(browser.client.payloadAt(0)).toMatchObject({
|
||||
requestId: "req-new",
|
||||
ok: false,
|
||||
error: {
|
||||
code: "browser_unsupported",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
test("remote agent browser_new_tab fails closed without creating a webview when host proxy cannot prepare", async () => {
|
||||
const browser = new BrowserAutomationHandlerHarness();
|
||||
browser.mount({
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
import { BROWSER_AUTOMATION_COMMAND_NAMES } from "@getpaseo/protocol/browser-automation/rpc-schemas";
|
||||
import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
|
||||
import type { SessionInboundMessage, SessionOutboundMessage } from "@getpaseo/protocol/messages";
|
||||
import { getDesktopHost, type DesktopHostBridge } from "@/desktop/host";
|
||||
import {
|
||||
getDesktopHost,
|
||||
type DesktopAutomationExecutionContext,
|
||||
type DesktopHostBridge,
|
||||
} from "@/desktop/host";
|
||||
import {
|
||||
ensureResidentBrowserWebview as ensureResidentBrowserWebviewDefault,
|
||||
removeResidentBrowserWebview,
|
||||
@@ -20,6 +24,7 @@ import {
|
||||
useBrowserStore,
|
||||
waitForBrowserHydration,
|
||||
} from "@/desktop/browser/store";
|
||||
import { useSessionStore } from "@/stores/session-store";
|
||||
import { collectAllTabs, useWorkspaceLayoutStore } from "@/stores/workspace-layout-store";
|
||||
import { buildWorkspaceTabPersistenceKey } from "@/workspace-tabs/model";
|
||||
|
||||
@@ -213,17 +218,70 @@ async function handleBrowserAutomationRequest(params: {
|
||||
return;
|
||||
}
|
||||
|
||||
client.sendBrowserAutomationExecuteResponse({
|
||||
type: "browser.automation.execute.response",
|
||||
payload: await forwardAutomationRequest({
|
||||
request,
|
||||
serverId,
|
||||
executeAutomationCommand,
|
||||
readHostBrowserRouting,
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
function resolveWorkspaceUploadRoot(input: {
|
||||
serverId: string;
|
||||
workspaceId: string;
|
||||
readHostBrowserRouting: typeof readHostBrowserRoutingDefault;
|
||||
}): string | null {
|
||||
if (input.readHostBrowserRouting(input.serverId).kind !== "local") {
|
||||
return null;
|
||||
}
|
||||
const directory = useSessionStore
|
||||
.getState()
|
||||
.sessions[input.serverId]?.workspaces.get(input.workspaceId)
|
||||
?.workspaceDirectory?.trim();
|
||||
return directory || null;
|
||||
}
|
||||
|
||||
async function forwardAutomationRequest(params: {
|
||||
request: BrowserAutomationExecuteRequest;
|
||||
serverId?: string;
|
||||
executeAutomationCommand: NonNullable<DesktopHostBridge["browser"]>["executeAutomationCommand"];
|
||||
readHostBrowserRouting: typeof readHostBrowserRoutingDefault;
|
||||
}): Promise<BrowserAutomationResponsePayload> {
|
||||
const { request, serverId, executeAutomationCommand, readHostBrowserRouting } = params;
|
||||
const normalizedServerId = serverId?.trim();
|
||||
const normalizedWorkspaceId = request.workspaceId?.trim();
|
||||
if (!normalizedServerId || !normalizedWorkspaceId) {
|
||||
return browserAutomationFailure({
|
||||
requestId: request.requestId,
|
||||
code: "browser_denied",
|
||||
message: "Browser automation requires a server and workspace context.",
|
||||
});
|
||||
}
|
||||
if (!executeAutomationCommand) {
|
||||
return browserAutomationFailure({
|
||||
requestId: request.requestId,
|
||||
code: "browser_unsupported",
|
||||
message: "Browser automation is not available in this app runtime.",
|
||||
});
|
||||
}
|
||||
|
||||
const uploadRoot = resolveWorkspaceUploadRoot({
|
||||
serverId: normalizedServerId,
|
||||
workspaceId: normalizedWorkspaceId,
|
||||
readHostBrowserRouting,
|
||||
});
|
||||
|
||||
try {
|
||||
const payload = await executeAutomationCommand(request);
|
||||
client.sendBrowserAutomationExecuteResponse({
|
||||
type: "browser.automation.execute.response",
|
||||
payload: normalizeBridgePayload(request.requestId, payload),
|
||||
const payload = await executeAutomationCommand(request, {
|
||||
serverId: normalizedServerId,
|
||||
uploadRoot,
|
||||
});
|
||||
return normalizeBridgePayload(request.requestId, payload);
|
||||
} catch (error) {
|
||||
client.sendBrowserAutomationExecuteResponse({
|
||||
type: "browser.automation.execute.response",
|
||||
payload: normalizeThrownBridgeError(request.requestId, error),
|
||||
});
|
||||
return normalizeThrownBridgeError(request.requestId, error);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -237,16 +295,24 @@ function resizeBrowserTabForRequest(params: {
|
||||
{ command: "resize" }
|
||||
>;
|
||||
const browserId = command.args.browserId;
|
||||
if (!getBrowserRecord(browserId)) {
|
||||
const normalizedServerId = serverId?.trim();
|
||||
const normalizedWorkspaceId = request.workspaceId?.trim();
|
||||
if (!normalizedServerId || !normalizedWorkspaceId) {
|
||||
return browserAutomationFailure({
|
||||
requestId: request.requestId,
|
||||
code: "browser_tab_not_found",
|
||||
message: `No browser tab found for ID: ${browserId}`,
|
||||
code: "browser_denied",
|
||||
message: "Cannot resize a browser tab without a workspace context.",
|
||||
});
|
||||
}
|
||||
|
||||
const workspaceId = request.workspaceId;
|
||||
if (serverId && workspaceId && !findWorkspaceBrowserTab({ serverId, workspaceId, browserId })) {
|
||||
if (
|
||||
!findWorkspaceBrowserTab({
|
||||
serverId: normalizedServerId,
|
||||
workspaceId: normalizedWorkspaceId,
|
||||
browserId,
|
||||
}) ||
|
||||
!getBrowserRecord(browserId)
|
||||
) {
|
||||
return browserAutomationFailure({
|
||||
requestId: request.requestId,
|
||||
code: "browser_tab_not_found",
|
||||
@@ -434,6 +500,7 @@ async function openBrowserTabForRequest(params: {
|
||||
try {
|
||||
ensureResidentBrowserWebview({
|
||||
browserId,
|
||||
serverId,
|
||||
workspaceId,
|
||||
url: normalizedUrl,
|
||||
...(targetPartition ? { partition: targetPartition } : {}),
|
||||
@@ -441,6 +508,7 @@ async function openBrowserTabForRequest(params: {
|
||||
registered = await waitForBrowserRegistration({
|
||||
request,
|
||||
browserId,
|
||||
serverId,
|
||||
workspaceId,
|
||||
executeAutomationCommand: browserHost.executeAutomationCommand,
|
||||
...(registrationWaitTimeoutMs !== undefined
|
||||
@@ -473,23 +541,31 @@ async function openBrowserTabForRequest(params: {
|
||||
async function waitForBrowserRegistration(params: {
|
||||
request: BrowserAutomationExecuteRequest;
|
||||
browserId: string;
|
||||
serverId: string;
|
||||
workspaceId: string;
|
||||
executeAutomationCommand: (
|
||||
request: BrowserAutomationExecuteRequest,
|
||||
context: DesktopAutomationExecutionContext,
|
||||
) => Promise<BrowserAutomationResponsePayload>;
|
||||
timeoutMs?: number;
|
||||
pollIntervalMs?: number;
|
||||
}): Promise<boolean> {
|
||||
const deadline = Date.now() + (params.timeoutMs ?? 5_000);
|
||||
while (Date.now() < deadline) {
|
||||
const payload = await params.executeAutomationCommand({
|
||||
type: "browser.automation.execute.request",
|
||||
requestId: `${params.request.requestId}:list_tabs`,
|
||||
agentId: params.request.agentId,
|
||||
cwd: params.request.cwd,
|
||||
workspaceId: params.workspaceId,
|
||||
command: { command: "list_tabs", args: {} },
|
||||
});
|
||||
const payload = await params.executeAutomationCommand(
|
||||
{
|
||||
type: "browser.automation.execute.request",
|
||||
requestId: `${params.request.requestId}:list_tabs`,
|
||||
agentId: params.request.agentId,
|
||||
cwd: params.request.cwd,
|
||||
workspaceId: params.workspaceId,
|
||||
command: { command: "list_tabs", args: {} },
|
||||
},
|
||||
{
|
||||
serverId: params.serverId,
|
||||
uploadRoot: null,
|
||||
},
|
||||
);
|
||||
if (payload.ok && payload.result.command === "list_tabs") {
|
||||
if (payload.result.tabs.some((tab) => tab.browserId === params.browserId)) {
|
||||
return true;
|
||||
|
||||
@@ -774,6 +774,7 @@ function deviceSizeIdForViewport(viewport: BrowserViewport): DeviceSizeId | null
|
||||
|
||||
function acquirePartitionedWebview(input: {
|
||||
browserId: string;
|
||||
serverId: string;
|
||||
workspaceId: string;
|
||||
partition: string;
|
||||
initialUrl: string;
|
||||
@@ -791,6 +792,7 @@ function acquirePartitionedWebview(input: {
|
||||
const webview = document.createElement("webview") as ElectronWebview;
|
||||
prepareBrowserWebview(webview, {
|
||||
browserId: input.browserId,
|
||||
serverId: input.serverId,
|
||||
workspaceId: input.workspaceId,
|
||||
initialUrl: input.initialUrl,
|
||||
partition: input.partition,
|
||||
@@ -985,6 +987,7 @@ export function BrowserPane({
|
||||
);
|
||||
const webview = acquirePartitionedWebview({
|
||||
browserId,
|
||||
serverId,
|
||||
workspaceId,
|
||||
partition: activePartition,
|
||||
initialUrl: initialUnsafeNavigationMessage ? "about:blank" : currentUrl,
|
||||
|
||||
@@ -173,6 +173,27 @@ describe("classifyHostBrowserRouting", () => {
|
||||
).toEqual({ kind: "remote", support: "host_connecting" });
|
||||
});
|
||||
|
||||
it.each([
|
||||
["idle", "host_connecting"],
|
||||
["connecting", "host_connecting"],
|
||||
["offline", "host_offline"],
|
||||
] as const)(
|
||||
"fails closed when host profile has no saved connections and is %s",
|
||||
(connectionStatus, expectedSupport) => {
|
||||
expect(
|
||||
classifyHostBrowserRouting({
|
||||
serverId: "unhydrated-host",
|
||||
connections: [],
|
||||
activeConnection: null,
|
||||
activeConnectionId: null,
|
||||
connectionStatus,
|
||||
features: null,
|
||||
origin: null,
|
||||
}),
|
||||
).toEqual({ kind: "remote", support: expectedSupport });
|
||||
},
|
||||
);
|
||||
|
||||
it("routes only loopback URLs on supported remote hosts in Electron to a proxied browser tab", () => {
|
||||
const supportedRemote = {
|
||||
kind: "remote" as const,
|
||||
|
||||
@@ -216,9 +216,9 @@ export function classifyHostBrowserRouting(
|
||||
if (originServerId) {
|
||||
return classifyRoutedHost(host, originServerId, origin);
|
||||
}
|
||||
} else if (connections.length === 0 || connections.some(isLocalHostConnection)) {
|
||||
// No active connection yet (connecting/offline). Distinguish local hosts from remote
|
||||
// hosts using saved connection definitions so remote tabs fail closed during startup.
|
||||
} else if (connections.some(isLocalHostConnection)) {
|
||||
// No active connection yet (connecting/offline). Classify as local only when saved
|
||||
// connections positively identify a local host; unhydrated or unknown hosts fail closed.
|
||||
return { kind: "local" };
|
||||
}
|
||||
|
||||
|
||||
@@ -21,7 +21,9 @@ import {
|
||||
const RESIDENT_HOST_ID = "paseo-browser-resident-webviews";
|
||||
const attachedBrowsers: Array<{
|
||||
browserId: string;
|
||||
serverId: string;
|
||||
workspaceId: string;
|
||||
partition: string;
|
||||
webContentsId: number;
|
||||
}> = [];
|
||||
const profileHost: BrowserWebviewProfileHost = {
|
||||
@@ -32,11 +34,13 @@ const profileHost: BrowserWebviewProfileHost = {
|
||||
|
||||
function ensureTestBrowser(input: {
|
||||
browserId: string;
|
||||
serverId?: string;
|
||||
workspaceId: string;
|
||||
url: string;
|
||||
}): HTMLElement | null {
|
||||
return ensureResidentBrowserWebview({
|
||||
partition: "persist:paseo-browser",
|
||||
serverId: "server-a",
|
||||
...input,
|
||||
profileHost,
|
||||
});
|
||||
@@ -44,9 +48,14 @@ function ensureTestBrowser(input: {
|
||||
|
||||
function prepareTestBrowser(
|
||||
webview: HTMLElement,
|
||||
input: { browserId: string; workspaceId: string; initialUrl?: string | null },
|
||||
input: { browserId: string; serverId?: string; workspaceId: string; initialUrl?: string | null },
|
||||
): void {
|
||||
prepareBrowserWebview(webview, { partition: "persist:paseo-browser", ...input, profileHost });
|
||||
prepareBrowserWebview(webview, {
|
||||
partition: "persist:paseo-browser",
|
||||
serverId: "server-a",
|
||||
...input,
|
||||
profileHost,
|
||||
});
|
||||
}
|
||||
|
||||
function residentHost(): HTMLElement {
|
||||
@@ -230,7 +239,13 @@ describe("resident browser webviews", () => {
|
||||
});
|
||||
|
||||
it("reuses a resident browser on the same partition and replaces it when the partition changes", () => {
|
||||
const input = { browserId: "first", workspaceId: "workspace", url: "about:blank", profileHost };
|
||||
const input = {
|
||||
browserId: "first",
|
||||
serverId: "server-a",
|
||||
workspaceId: "workspace",
|
||||
url: "about:blank",
|
||||
profileHost,
|
||||
};
|
||||
const first = ensureTestBrowser(input);
|
||||
expect(ensureResidentBrowserWebview({ ...input, partition: "persist:paseo-browser" })).toBe(
|
||||
first,
|
||||
@@ -275,12 +290,14 @@ describe("resident browser webviews", () => {
|
||||
expect(attachedBrowsers).toEqual([
|
||||
{
|
||||
browserId: "browser-first",
|
||||
serverId: "server-a",
|
||||
workspaceId: "workspace-a",
|
||||
partition: "persist:paseo-browser",
|
||||
webContentsId: 101,
|
||||
},
|
||||
{
|
||||
browserId: "browser-second",
|
||||
serverId: "server-a",
|
||||
workspaceId: "workspace-b",
|
||||
partition: "persist:paseo-browser",
|
||||
webContentsId: 202,
|
||||
|
||||
@@ -25,6 +25,7 @@ interface BrowserWebviewElement extends HTMLElement {
|
||||
interface BrowserWebviewIdentity {
|
||||
partition: string;
|
||||
browserId: string;
|
||||
serverId: string;
|
||||
workspaceId: string;
|
||||
}
|
||||
|
||||
@@ -80,6 +81,7 @@ function registerBrowserWhenAttached(
|
||||
await browser.registerAttachedBrowser({
|
||||
partition: identity.partition,
|
||||
browserId: identity.browserId,
|
||||
serverId: identity.serverId,
|
||||
workspaceId: identity.workspaceId,
|
||||
webContentsId,
|
||||
});
|
||||
@@ -327,6 +329,7 @@ export function prepareBrowserWebview(
|
||||
webview: HTMLElement,
|
||||
input: {
|
||||
browserId: string;
|
||||
serverId: string;
|
||||
workspaceId: string;
|
||||
initialUrl?: string | null;
|
||||
partition?: string;
|
||||
@@ -348,6 +351,7 @@ export function prepareBrowserWebview(
|
||||
{
|
||||
partition: targetPartition,
|
||||
browserId: input.browserId,
|
||||
serverId: input.serverId,
|
||||
workspaceId: input.workspaceId,
|
||||
},
|
||||
browser,
|
||||
@@ -360,6 +364,7 @@ export function getResidentBrowserWebviewPartition(webview: HTMLElement): string
|
||||
|
||||
export function ensureResidentBrowserWebview(input: {
|
||||
browserId: string;
|
||||
serverId: string;
|
||||
workspaceId: string;
|
||||
url: string;
|
||||
partition?: string;
|
||||
@@ -400,6 +405,7 @@ export function ensureResidentBrowserWebview(input: {
|
||||
const webview = ownerDocument.createElement("webview") as BrowserWebviewElement;
|
||||
prepareBrowserWebview(webview, {
|
||||
browserId,
|
||||
serverId: input.serverId,
|
||||
workspaceId: input.workspaceId,
|
||||
initialUrl: input.url,
|
||||
partition: desiredPartition,
|
||||
|
||||
@@ -145,10 +145,16 @@ export interface DesktopBrowserNewTabRequestEvent {
|
||||
export interface DesktopAttachedBrowserRegistration {
|
||||
partition: string;
|
||||
browserId: string;
|
||||
serverId: string;
|
||||
workspaceId: string;
|
||||
webContentsId: number;
|
||||
}
|
||||
|
||||
export interface DesktopAutomationExecutionContext {
|
||||
serverId: string;
|
||||
uploadRoot: string | null;
|
||||
}
|
||||
|
||||
export type BrowserProfileColor = IdentityColorName;
|
||||
|
||||
export interface BrowserProfileEntry {
|
||||
@@ -206,6 +212,7 @@ export interface DesktopBrowserBridge {
|
||||
registerAttachedBrowser?: (input: DesktopAttachedBrowserRegistration) => Promise<void>;
|
||||
unregisterWorkspaceBrowser?: (browserId: string) => Promise<void>;
|
||||
setWorkspaceActiveBrowser?: (input: {
|
||||
serverId: string;
|
||||
workspaceId: string;
|
||||
browserId: string | null;
|
||||
}) => Promise<void>;
|
||||
@@ -232,6 +239,7 @@ export interface DesktopBrowserBridge {
|
||||
}) => Promise<void>;
|
||||
executeAutomationCommand?: (
|
||||
request: BrowserAutomationExecuteRequest,
|
||||
context: DesktopAutomationExecutionContext,
|
||||
) => Promise<BrowserAutomationExecuteResponse["payload"]>;
|
||||
acknowledgeFocusGuard?: (input: { token: string; composing: boolean }) => void;
|
||||
/** Capture a PNG screenshot of the guest viewport cropped to `rect`. */
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { Text, View } from "react-native";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { StyleSheet } from "react-native-unistyles";
|
||||
@@ -14,13 +14,15 @@ import type { HostDirectory, HostSummary } from "@getpaseo/protocol/hosts";
|
||||
import {
|
||||
SettingsCard,
|
||||
SettingsCollapsibleRow,
|
||||
SettingsDetailRow,
|
||||
SettingsRow,
|
||||
SettingsSection,
|
||||
} from "@/components/settings";
|
||||
import { StatusBadge } from "@/components/ui/status-badge";
|
||||
import { useHostRuntimeClient, useHostRuntimeSnapshot } from "@/runtime/host-runtime";
|
||||
import { useSessionStore } from "@/stores/session-store";
|
||||
import { useSessionStore, type DaemonServerInfo } from "@/stores/session-store";
|
||||
import { formatConnectedDuration, summarizePermissions } from "./scope-summary";
|
||||
import { DaemonPasswordSheet } from "./daemon-password-sheet";
|
||||
|
||||
const UPDATES_DOCS_URL = "https://paseo.sh/docs/updates";
|
||||
|
||||
@@ -490,6 +492,74 @@ function ConnectedClientsCardBody({
|
||||
);
|
||||
}
|
||||
|
||||
function DevicesAccessSection({
|
||||
serverId,
|
||||
isOnline,
|
||||
serverInfo,
|
||||
}: {
|
||||
serverId: string;
|
||||
isOnline: boolean;
|
||||
serverInfo: DaemonServerInfo | null;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const [passwordSheetMode, setPasswordSheetMode] = useState<"set" | "change" | null>(null);
|
||||
const passwordConfigured = serverInfo?.passwordConfigured === true;
|
||||
const passwordManagedByEnv = serverInfo?.passwordManagedByEnv === true;
|
||||
const handleOpenPasswordSheet = useCallback(() => {
|
||||
setPasswordSheetMode(passwordConfigured ? "change" : "set");
|
||||
}, [passwordConfigured]);
|
||||
const handleClosePasswordSheet = useCallback(() => {
|
||||
setPasswordSheetMode(null);
|
||||
}, []);
|
||||
|
||||
// COMPAT(daemonPasswordManagement): added in v0.19.x, remove gate after 2027-06-15.
|
||||
const supportsPasswordManagement = serverInfo?.features?.daemonPasswordManagement === true;
|
||||
const canManagePassword =
|
||||
!serverInfo?.permissions ||
|
||||
(serverInfo.permissions.includes("daemon.manage") &&
|
||||
serverInfo.permissions.includes("access.manage"));
|
||||
|
||||
if (!isOnline || !supportsPasswordManagement || !canManagePassword) {
|
||||
return null;
|
||||
}
|
||||
|
||||
let passwordSummary: string;
|
||||
let passwordHint: string;
|
||||
if (passwordManagedByEnv) {
|
||||
passwordSummary = t("devices.access.passwordEnvSummary");
|
||||
passwordHint = t("devices.access.passwordEnvHint");
|
||||
} else if (passwordConfigured) {
|
||||
passwordSummary = t("devices.access.passwordSetSummary");
|
||||
passwordHint = t("devices.access.passwordSetHint");
|
||||
} else {
|
||||
passwordSummary = t("devices.access.passwordNotSetSummary");
|
||||
passwordHint = t("devices.access.passwordNotSetHint");
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<SettingsSection title={t("devices.access.title")}>
|
||||
<SettingsCard testID="devices-access-card">
|
||||
<SettingsDetailRow
|
||||
label={t("devices.access.passwordLabel")}
|
||||
summary={passwordSummary}
|
||||
hint={passwordHint}
|
||||
disabled={passwordManagedByEnv}
|
||||
onPress={handleOpenPasswordSheet}
|
||||
testID="devices-password-row"
|
||||
/>
|
||||
</SettingsCard>
|
||||
</SettingsSection>
|
||||
<DaemonPasswordSheet
|
||||
serverId={serverId}
|
||||
visible={passwordSheetMode !== null}
|
||||
initialMode={passwordSheetMode ?? "set"}
|
||||
onClose={handleClosePasswordSheet}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export function ConnectedDevicesView({ serverId }: { serverId: string }) {
|
||||
const { t } = useTranslation();
|
||||
const connectionStatus = useHostRuntimeSnapshot(serverId)?.connectionStatus;
|
||||
@@ -538,6 +608,8 @@ export function ConnectedDevicesView({ serverId }: { serverId: string }) {
|
||||
|
||||
return (
|
||||
<View>
|
||||
<DevicesAccessSection serverId={serverId} isOnline={isOnline} serverInfo={serverInfo} />
|
||||
|
||||
<SettingsSection title={t("devices.connected.title")}>
|
||||
<SettingsCard testID="devices-connected-clients-card">
|
||||
<ConnectedClientsCardBody
|
||||
|
||||
@@ -0,0 +1,181 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
import {
|
||||
DAEMON_PASSWORD_MAX_BYTES,
|
||||
DAEMON_PASSWORD_MIN_CHARS,
|
||||
openDaemonPasswordForm,
|
||||
shouldSyncHostProfilePassword,
|
||||
} from "./daemon-password-form-model";
|
||||
|
||||
describe("daemon password form model", () => {
|
||||
test("set mode validates min 8 chars, max 72 UTF-8 bytes, and confirmation match", () => {
|
||||
const form = openDaemonPasswordForm({
|
||||
mode: "set",
|
||||
isLocalCredential: false,
|
||||
});
|
||||
expect(form.getState()).toMatchObject({
|
||||
step: "set",
|
||||
isLocalCredential: false,
|
||||
submitting: false,
|
||||
});
|
||||
|
||||
// 7 chars fails min length.
|
||||
form.setNewPassword("1234567");
|
||||
form.setConfirmPassword("1234567");
|
||||
expect(form.beginSubmit()).toEqual({ valid: false });
|
||||
expect(form.getState().fieldErrors.newPassword).toBe("too_short");
|
||||
|
||||
// 8 chars with mismatch fails confirm.
|
||||
form.setNewPassword("12345678");
|
||||
form.setConfirmPassword("87654321");
|
||||
expect(form.beginSubmit()).toEqual({ valid: false });
|
||||
expect(form.getState().fieldErrors.newPassword).toBeNull();
|
||||
expect(form.getState().fieldErrors.confirmPassword).toBe("mismatch");
|
||||
|
||||
// 73 UTF-8 bytes fails (including multibyte UTF-8 under 72 chars).
|
||||
const over72Bytes = "🔐".repeat(19); // 76 UTF-8 bytes
|
||||
expect(over72Bytes.length).toBeLessThan(DAEMON_PASSWORD_MAX_BYTES);
|
||||
form.setNewPassword(over72Bytes);
|
||||
form.setConfirmPassword(over72Bytes);
|
||||
expect(form.beginSubmit()).toEqual({ valid: false });
|
||||
expect(form.getState().fieldErrors.newPassword).toBe("too_long");
|
||||
|
||||
// Exact 72 UTF-8 bytes succeeds.
|
||||
const exact72 = "a".repeat(DAEMON_PASSWORD_MAX_BYTES);
|
||||
form.setNewPassword(exact72);
|
||||
form.setConfirmPassword(exact72);
|
||||
expect(form.beginSubmit()).toEqual({
|
||||
valid: true,
|
||||
payload: { password: exact72 },
|
||||
});
|
||||
expect(form.getState().submitting).toBe(true);
|
||||
form.finishSubmitSuccess();
|
||||
expect(form.getState().submitting).toBe(false);
|
||||
|
||||
// Exact 8 chars succeeds.
|
||||
const exact8 = "a".repeat(DAEMON_PASSWORD_MIN_CHARS);
|
||||
form.setNewPassword(exact8);
|
||||
form.setConfirmPassword(exact8);
|
||||
expect(form.beginSubmit()).toEqual({
|
||||
valid: true,
|
||||
payload: { password: exact8 },
|
||||
});
|
||||
});
|
||||
|
||||
test("change mode requires current password on remote sessions and maps server incorrect_password to field error", () => {
|
||||
const form = openDaemonPasswordForm({
|
||||
mode: "change",
|
||||
isLocalCredential: false,
|
||||
});
|
||||
|
||||
form.setNewPassword("new-secret-123");
|
||||
form.setConfirmPassword("new-secret-123");
|
||||
expect(form.beginSubmit()).toEqual({ valid: false });
|
||||
expect(form.getState().fieldErrors.currentPassword).toBe("current_password_required");
|
||||
|
||||
form.setCurrentPassword("wrong-current");
|
||||
expect(form.beginSubmit()).toEqual({
|
||||
valid: true,
|
||||
payload: { password: "new-secret-123", currentPassword: "wrong-current" },
|
||||
});
|
||||
|
||||
form.finishSubmitError({
|
||||
code: "incorrect_password",
|
||||
message: "Current password is incorrect",
|
||||
});
|
||||
expect(form.getState().submitting).toBe(false);
|
||||
expect(form.getState().fieldErrors.currentPassword).toBe("incorrect_password");
|
||||
expect(form.getState().submitError).toBeNull();
|
||||
// Preserves inputs so the user does not retype.
|
||||
expect(form.getState().newPassword).toBe("new-secret-123");
|
||||
expect(form.getState().confirmPassword).toBe("new-secret-123");
|
||||
|
||||
// Network/generic error goes to submitError.
|
||||
form.finishSubmitError({ message: "Network timeout" });
|
||||
expect(form.getState().submitError).toBe("Network timeout");
|
||||
});
|
||||
|
||||
test("change mode omits currentPassword on local-credential sessions", () => {
|
||||
const form = openDaemonPasswordForm({
|
||||
mode: "change",
|
||||
isLocalCredential: true,
|
||||
});
|
||||
|
||||
form.setNewPassword("recovered-secret");
|
||||
form.setConfirmPassword("recovered-secret");
|
||||
expect(form.beginSubmit()).toEqual({
|
||||
valid: true,
|
||||
payload: { password: "recovered-secret" },
|
||||
});
|
||||
});
|
||||
|
||||
test("remote remove step seeds currentPassword from change step and submits password=null", () => {
|
||||
const form = openDaemonPasswordForm({
|
||||
mode: "change",
|
||||
isLocalCredential: false,
|
||||
});
|
||||
form.setCurrentPassword("my-current-pw");
|
||||
form.enterRemoveStep();
|
||||
expect(form.getState().step).toBe("remove");
|
||||
expect(form.getState().currentPassword).toBe("my-current-pw");
|
||||
|
||||
expect(form.beginSubmit()).toEqual({
|
||||
valid: true,
|
||||
payload: { password: null, currentPassword: "my-current-pw" },
|
||||
});
|
||||
|
||||
form.finishSubmitError({
|
||||
code: "incorrect_password",
|
||||
message: "Current password is incorrect",
|
||||
});
|
||||
expect(form.getState().fieldErrors.currentPassword).toBe("incorrect_password");
|
||||
|
||||
form.backToChangeStep();
|
||||
expect(form.getState().step).toBe("change");
|
||||
});
|
||||
|
||||
test("shouldSyncHostProfilePassword skips persisting password on local-only profiles when using localCredentialAuth", () => {
|
||||
expect(
|
||||
shouldSyncHostProfilePassword({
|
||||
localCredentialAuth: true,
|
||||
connections: [
|
||||
{ id: "socket:/tmp/paseo.sock", type: "directSocket", path: "/tmp/paseo.sock" },
|
||||
],
|
||||
}),
|
||||
).toBe(false);
|
||||
|
||||
expect(
|
||||
shouldSyncHostProfilePassword({
|
||||
localCredentialAuth: true,
|
||||
connections: [
|
||||
{ id: "direct:127.0.0.1:6767", type: "directTcp", endpoint: "127.0.0.1:6767" },
|
||||
],
|
||||
}),
|
||||
).toBe(false);
|
||||
|
||||
// Local desktop profile that also has a relay or remote route DOES sync so remote routes stay usable.
|
||||
expect(
|
||||
shouldSyncHostProfilePassword({
|
||||
localCredentialAuth: true,
|
||||
connections: [
|
||||
{ id: "direct:127.0.0.1:6767", type: "directTcp", endpoint: "127.0.0.1:6767" },
|
||||
{
|
||||
id: "relay:relay.paseo.sh:443",
|
||||
type: "relay",
|
||||
relayEndpoint: "relay.paseo.sh:443",
|
||||
daemonPublicKeyB64: "pk",
|
||||
},
|
||||
],
|
||||
}),
|
||||
).toBe(true);
|
||||
|
||||
// Non-local browser session always syncs even on localhost so reload stays authenticated.
|
||||
expect(
|
||||
shouldSyncHostProfilePassword({
|
||||
localCredentialAuth: false,
|
||||
connections: [
|
||||
{ id: "direct:127.0.0.1:6767", type: "directTcp", endpoint: "127.0.0.1:6767" },
|
||||
],
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,269 @@
|
||||
import { isLoopbackEndpoint } from "@/hosts/connection-display";
|
||||
import type { HostConnection } from "@/types/host-connection";
|
||||
|
||||
export const DAEMON_PASSWORD_MIN_CHARS = 8;
|
||||
export const DAEMON_PASSWORD_MAX_BYTES = 72;
|
||||
|
||||
export type DaemonPasswordFormStep = "set" | "change" | "remove";
|
||||
|
||||
export type DaemonPasswordFieldErrorCode =
|
||||
| "current_password_required"
|
||||
| "incorrect_password"
|
||||
| "too_short"
|
||||
| "too_long"
|
||||
| "mismatch"
|
||||
| "invalid_password";
|
||||
|
||||
export interface DaemonPasswordFormFieldErrors {
|
||||
currentPassword: DaemonPasswordFieldErrorCode | null;
|
||||
newPassword: DaemonPasswordFieldErrorCode | null;
|
||||
confirmPassword: DaemonPasswordFieldErrorCode | null;
|
||||
}
|
||||
|
||||
export interface DaemonPasswordFormState {
|
||||
step: DaemonPasswordFormStep;
|
||||
isLocalCredential: boolean;
|
||||
currentPassword: string;
|
||||
newPassword: string;
|
||||
confirmPassword: string;
|
||||
showCurrentPassword: boolean;
|
||||
showNewPassword: boolean;
|
||||
showConfirmPassword: boolean;
|
||||
submitting: boolean;
|
||||
fieldErrors: DaemonPasswordFormFieldErrors;
|
||||
submitError: string | null;
|
||||
}
|
||||
|
||||
export interface DaemonPasswordFormSnapshot {
|
||||
mode: "set" | "change";
|
||||
isLocalCredential: boolean;
|
||||
}
|
||||
|
||||
export type DaemonPasswordSubmitResult =
|
||||
| { valid: false }
|
||||
| { valid: true; payload: { password: string | null; currentPassword?: string } };
|
||||
|
||||
export interface DaemonPasswordFormModel {
|
||||
getState(): DaemonPasswordFormState;
|
||||
subscribe(listener: () => void): () => void;
|
||||
setCurrentPassword(value: string): void;
|
||||
setNewPassword(value: string): void;
|
||||
setConfirmPassword(value: string): void;
|
||||
toggleShowCurrentPassword(): void;
|
||||
toggleShowNewPassword(): void;
|
||||
toggleShowConfirmPassword(): void;
|
||||
enterRemoveStep(): void;
|
||||
backToChangeStep(): void;
|
||||
beginSubmit(): DaemonPasswordSubmitResult;
|
||||
finishSubmitSuccess(): void;
|
||||
finishSubmitError(error: { code?: string; message: string }): void;
|
||||
}
|
||||
|
||||
const textEncoder = new TextEncoder();
|
||||
|
||||
export function utf8ByteLength(value: string): number {
|
||||
return textEncoder.encode(value).byteLength;
|
||||
}
|
||||
|
||||
export function isLocalOnlyHostConnection(connection: HostConnection): boolean {
|
||||
if (connection.type === "directSocket" || connection.type === "directPipe") {
|
||||
return true;
|
||||
}
|
||||
if (connection.type === "directTcp") {
|
||||
return isLoopbackEndpoint(connection.endpoint);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
export function shouldSyncHostProfilePassword(input: {
|
||||
localCredentialAuth: boolean;
|
||||
connections: readonly HostConnection[];
|
||||
}): boolean {
|
||||
if (!input.localCredentialAuth) {
|
||||
return true;
|
||||
}
|
||||
return input.connections.some((connection) => !isLocalOnlyHostConnection(connection));
|
||||
}
|
||||
|
||||
const EMPTY_FIELD_ERRORS: DaemonPasswordFormFieldErrors = {
|
||||
currentPassword: null,
|
||||
newPassword: null,
|
||||
confirmPassword: null,
|
||||
};
|
||||
|
||||
export function openDaemonPasswordForm(
|
||||
snapshot: DaemonPasswordFormSnapshot,
|
||||
): DaemonPasswordFormModel {
|
||||
const listeners = new Set<() => void>();
|
||||
let state: DaemonPasswordFormState = {
|
||||
step: snapshot.mode,
|
||||
isLocalCredential: snapshot.isLocalCredential,
|
||||
currentPassword: "",
|
||||
newPassword: "",
|
||||
confirmPassword: "",
|
||||
showCurrentPassword: false,
|
||||
showNewPassword: false,
|
||||
showConfirmPassword: false,
|
||||
submitting: false,
|
||||
fieldErrors: { ...EMPTY_FIELD_ERRORS },
|
||||
submitError: null,
|
||||
};
|
||||
|
||||
const publish = (next: DaemonPasswordFormState) => {
|
||||
state = next;
|
||||
for (const listener of listeners) {
|
||||
listener();
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
getState: () => state,
|
||||
|
||||
subscribe(listener) {
|
||||
listeners.add(listener);
|
||||
return () => {
|
||||
listeners.delete(listener);
|
||||
};
|
||||
},
|
||||
|
||||
setCurrentPassword(value) {
|
||||
publish({
|
||||
...state,
|
||||
currentPassword: value,
|
||||
fieldErrors: { ...state.fieldErrors, currentPassword: null },
|
||||
submitError: null,
|
||||
});
|
||||
},
|
||||
|
||||
setNewPassword(value) {
|
||||
publish({
|
||||
...state,
|
||||
newPassword: value,
|
||||
fieldErrors: { ...state.fieldErrors, newPassword: null, confirmPassword: null },
|
||||
submitError: null,
|
||||
});
|
||||
},
|
||||
|
||||
setConfirmPassword(value) {
|
||||
publish({
|
||||
...state,
|
||||
confirmPassword: value,
|
||||
fieldErrors: { ...state.fieldErrors, confirmPassword: null },
|
||||
submitError: null,
|
||||
});
|
||||
},
|
||||
|
||||
toggleShowCurrentPassword() {
|
||||
publish({ ...state, showCurrentPassword: !state.showCurrentPassword });
|
||||
},
|
||||
|
||||
toggleShowNewPassword() {
|
||||
publish({ ...state, showNewPassword: !state.showNewPassword });
|
||||
},
|
||||
|
||||
toggleShowConfirmPassword() {
|
||||
publish({ ...state, showConfirmPassword: !state.showConfirmPassword });
|
||||
},
|
||||
|
||||
enterRemoveStep() {
|
||||
if (state.step !== "change" || state.submitting) return;
|
||||
publish({
|
||||
...state,
|
||||
step: "remove",
|
||||
fieldErrors: { ...EMPTY_FIELD_ERRORS },
|
||||
submitError: null,
|
||||
});
|
||||
},
|
||||
|
||||
backToChangeStep() {
|
||||
if (state.step !== "remove" || state.submitting) return;
|
||||
publish({
|
||||
...state,
|
||||
step: "change",
|
||||
fieldErrors: { ...EMPTY_FIELD_ERRORS },
|
||||
submitError: null,
|
||||
});
|
||||
},
|
||||
|
||||
beginSubmit() {
|
||||
if (state.submitting) {
|
||||
return { valid: false };
|
||||
}
|
||||
|
||||
const fieldErrors: DaemonPasswordFormFieldErrors = { ...EMPTY_FIELD_ERRORS };
|
||||
const needsCurrentPassword =
|
||||
(state.step === "change" || state.step === "remove") && !state.isLocalCredential;
|
||||
|
||||
if (needsCurrentPassword && state.currentPassword.length === 0) {
|
||||
fieldErrors.currentPassword = "current_password_required";
|
||||
}
|
||||
|
||||
if (state.step !== "remove") {
|
||||
if (state.newPassword.length < DAEMON_PASSWORD_MIN_CHARS) {
|
||||
fieldErrors.newPassword = "too_short";
|
||||
} else if (utf8ByteLength(state.newPassword) > DAEMON_PASSWORD_MAX_BYTES) {
|
||||
fieldErrors.newPassword = "too_long";
|
||||
} else if (state.confirmPassword !== state.newPassword) {
|
||||
fieldErrors.confirmPassword = "mismatch";
|
||||
}
|
||||
}
|
||||
|
||||
if (
|
||||
fieldErrors.currentPassword !== null ||
|
||||
fieldErrors.newPassword !== null ||
|
||||
fieldErrors.confirmPassword !== null
|
||||
) {
|
||||
publish({
|
||||
...state,
|
||||
fieldErrors,
|
||||
submitError: null,
|
||||
});
|
||||
return { valid: false };
|
||||
}
|
||||
|
||||
publish({
|
||||
...state,
|
||||
submitting: true,
|
||||
fieldErrors: { ...EMPTY_FIELD_ERRORS },
|
||||
submitError: null,
|
||||
});
|
||||
|
||||
return {
|
||||
valid: true,
|
||||
payload: {
|
||||
password: state.step === "remove" ? null : state.newPassword,
|
||||
...(needsCurrentPassword ? { currentPassword: state.currentPassword } : {}),
|
||||
},
|
||||
};
|
||||
},
|
||||
|
||||
finishSubmitSuccess() {
|
||||
publish({
|
||||
...state,
|
||||
submitting: false,
|
||||
fieldErrors: { ...EMPTY_FIELD_ERRORS },
|
||||
submitError: null,
|
||||
});
|
||||
},
|
||||
|
||||
finishSubmitError(error) {
|
||||
const fieldErrors: DaemonPasswordFormFieldErrors = { ...EMPTY_FIELD_ERRORS };
|
||||
let submitError: string | null = null;
|
||||
if (error.code === "incorrect_password") {
|
||||
fieldErrors.currentPassword = "incorrect_password";
|
||||
} else if (error.code === "current_password_required") {
|
||||
fieldErrors.currentPassword = "current_password_required";
|
||||
} else if (error.code === "invalid_password") {
|
||||
fieldErrors.newPassword = "invalid_password";
|
||||
} else {
|
||||
submitError = error.message;
|
||||
}
|
||||
publish({
|
||||
...state,
|
||||
submitting: false,
|
||||
fieldErrors,
|
||||
submitError,
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,532 @@
|
||||
import { useCallback, useMemo, useState, useSyncExternalStore } from "react";
|
||||
import { View } from "react-native";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import type { TFunction } from "i18next";
|
||||
import { Eye, EyeOff } from "lucide-react-native";
|
||||
import { StyleSheet } from "react-native-unistyles";
|
||||
import { DaemonRpcError } from "@getpaseo/client";
|
||||
import { AdaptiveModalSheet, type SheetHeader } from "@/components/adaptive-modal-sheet";
|
||||
import { Alert } from "@/components/ui/alert";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Field, FormTextInput } from "@/components/ui/form-field";
|
||||
import { useIsCompactFormFactor } from "@/constants/layout";
|
||||
import { useToast } from "@/contexts/toast-context";
|
||||
import { useHostMutations, useHostRuntimeClient, useHosts } from "@/runtime/host-runtime";
|
||||
import { useSessionStore } from "@/stores/session-store";
|
||||
import { confirmDialog } from "@/utils/confirm-dialog";
|
||||
import {
|
||||
openDaemonPasswordForm,
|
||||
shouldSyncHostProfilePassword,
|
||||
type DaemonPasswordFieldErrorCode,
|
||||
type DaemonPasswordFormModel,
|
||||
} from "./daemon-password-form-model";
|
||||
|
||||
const FLEX_ONE_STYLE = { flex: 1 } as const;
|
||||
const SNAP_POINTS: string[] = ["72%", "92%"];
|
||||
|
||||
function translateFieldError(
|
||||
code: DaemonPasswordFieldErrorCode | null,
|
||||
t: TFunction,
|
||||
): string | null {
|
||||
switch (code) {
|
||||
case "current_password_required":
|
||||
return t("devices.password.errors.currentRequired");
|
||||
case "incorrect_password":
|
||||
return t("devices.password.errors.currentIncorrect");
|
||||
case "too_short":
|
||||
return t("devices.password.errors.tooShort");
|
||||
case "too_long":
|
||||
case "invalid_password":
|
||||
return t("devices.password.errors.tooLong");
|
||||
case "mismatch":
|
||||
return t("devices.password.errors.mismatch");
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function formatSuccessToast(
|
||||
action: "set" | "change" | "remove",
|
||||
disconnectedSessionCount: number,
|
||||
t: TFunction,
|
||||
): string {
|
||||
if (action === "remove") {
|
||||
return t("devices.password.toast.removed");
|
||||
}
|
||||
if (action === "set") {
|
||||
if (disconnectedSessionCount === 1) {
|
||||
return t("devices.password.toast.setDisconnectedOne");
|
||||
}
|
||||
if (disconnectedSessionCount > 1) {
|
||||
return t("devices.password.toast.setDisconnectedOther", { count: disconnectedSessionCount });
|
||||
}
|
||||
return t("devices.password.toast.set");
|
||||
}
|
||||
if (disconnectedSessionCount === 1) {
|
||||
return t("devices.password.toast.updatedDisconnectedOne");
|
||||
}
|
||||
if (disconnectedSessionCount > 1) {
|
||||
return t("devices.password.toast.updatedDisconnectedOther", {
|
||||
count: disconnectedSessionCount,
|
||||
});
|
||||
}
|
||||
return t("devices.password.toast.updated");
|
||||
}
|
||||
|
||||
function extractRpcError(
|
||||
error: unknown,
|
||||
fallbackMessage: string,
|
||||
): {
|
||||
code?: string;
|
||||
message: string;
|
||||
} {
|
||||
if (error instanceof DaemonRpcError) {
|
||||
return { code: error.code, message: error.userMessage || error.message };
|
||||
}
|
||||
if (error instanceof Error) {
|
||||
return { message: error.message || fallbackMessage };
|
||||
}
|
||||
return { message: fallbackMessage };
|
||||
}
|
||||
|
||||
function resolvePrimaryButtonLabel(
|
||||
step: "set" | "change" | "remove",
|
||||
submitting: boolean,
|
||||
t: TFunction,
|
||||
): string {
|
||||
if (step === "set") {
|
||||
return submitting ? t("devices.password.setting") : t("devices.password.setAction");
|
||||
}
|
||||
if (step === "change") {
|
||||
return submitting ? t("devices.password.saving") : t("devices.password.saveAction");
|
||||
}
|
||||
return submitting ? t("devices.password.removing") : t("devices.password.removeAction");
|
||||
}
|
||||
|
||||
function DaemonPasswordStepBanner({
|
||||
step,
|
||||
t,
|
||||
}: {
|
||||
step: "set" | "change" | "remove";
|
||||
t: TFunction;
|
||||
}) {
|
||||
if (step === "remove") {
|
||||
return (
|
||||
<Alert
|
||||
size="sm"
|
||||
variant="warning"
|
||||
description={t("devices.password.removeWarning")}
|
||||
testID="daemon-password-remove-warning"
|
||||
/>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<Alert
|
||||
size="sm"
|
||||
variant="info"
|
||||
description={
|
||||
step === "set" ? t("devices.password.setInfo") : t("devices.password.changeInfo")
|
||||
}
|
||||
testID="daemon-password-info"
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
interface PasswordInputFieldProps {
|
||||
label: string;
|
||||
initialValue: string;
|
||||
showPassword: boolean;
|
||||
onChangeText: (value: string) => void;
|
||||
onToggleShow: () => void;
|
||||
onSubmitEditing?: () => void;
|
||||
error: string | null;
|
||||
disabled: boolean;
|
||||
autoFocus?: boolean;
|
||||
size: "sm" | "md";
|
||||
returnKeyType?: "next" | "done";
|
||||
testID: string;
|
||||
}
|
||||
|
||||
function PasswordInputField({
|
||||
label,
|
||||
initialValue,
|
||||
showPassword,
|
||||
onChangeText,
|
||||
onToggleShow,
|
||||
onSubmitEditing,
|
||||
error,
|
||||
disabled,
|
||||
autoFocus,
|
||||
size,
|
||||
returnKeyType = "next",
|
||||
testID,
|
||||
}: PasswordInputFieldProps) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<Field label={label} error={error} testID={`${testID}-field`}>
|
||||
<View style={styles.passwordRow}>
|
||||
<View style={styles.passwordInputWrap}>
|
||||
<FormTextInput
|
||||
initialValue={initialValue}
|
||||
onChangeText={onChangeText}
|
||||
onSubmitEditing={onSubmitEditing}
|
||||
secureTextEntry={!showPassword}
|
||||
autoCapitalize="none"
|
||||
autoCorrect={false}
|
||||
autoComplete="off"
|
||||
autoFocus={autoFocus}
|
||||
editable={!disabled}
|
||||
invalid={Boolean(error)}
|
||||
size={size}
|
||||
returnKeyType={returnKeyType}
|
||||
testID={testID}
|
||||
/>
|
||||
</View>
|
||||
<Button
|
||||
variant="outline"
|
||||
size={size}
|
||||
leftIcon={showPassword ? EyeOff : Eye}
|
||||
onPress={onToggleShow}
|
||||
disabled={disabled}
|
||||
accessibilityLabel={
|
||||
showPassword ? t("devices.password.hide") : t("devices.password.show")
|
||||
}
|
||||
testID={`${testID}-toggle`}
|
||||
/>
|
||||
</View>
|
||||
</Field>
|
||||
);
|
||||
}
|
||||
|
||||
export interface DaemonPasswordFormContentProps {
|
||||
serverId: string;
|
||||
initialMode: "set" | "change";
|
||||
model?: DaemonPasswordFormModel;
|
||||
onCancel: () => void;
|
||||
onCompleted: () => void;
|
||||
}
|
||||
|
||||
export function DaemonPasswordFormContent({
|
||||
serverId,
|
||||
initialMode,
|
||||
model: externalModel,
|
||||
onCancel,
|
||||
onCompleted,
|
||||
}: DaemonPasswordFormContentProps) {
|
||||
const { t } = useTranslation();
|
||||
const toast = useToast();
|
||||
const isCompact = useIsCompactFormFactor();
|
||||
const fieldSize = isCompact ? "md" : "sm";
|
||||
const client = useHostRuntimeClient(serverId);
|
||||
const hosts = useHosts();
|
||||
const { setHostPassword } = useHostMutations();
|
||||
const serverInfo = useSessionStore((state) => state.sessions[serverId]?.serverInfo ?? null);
|
||||
const host = useMemo(
|
||||
() => hosts.find((item) => item.serverId === serverId) ?? null,
|
||||
[hosts, serverId],
|
||||
);
|
||||
const isLocalCredential = serverInfo?.localCredentialAuth === true;
|
||||
|
||||
const [internalModel] = useState(() =>
|
||||
openDaemonPasswordForm({
|
||||
mode: initialMode,
|
||||
isLocalCredential,
|
||||
}),
|
||||
);
|
||||
const model = externalModel ?? internalModel;
|
||||
const state = useSyncExternalStore(model.subscribe, model.getState, model.getState);
|
||||
|
||||
const syncProfilePasswordIfNeeded = useCallback(
|
||||
async (nextPassword: string | null) => {
|
||||
if (
|
||||
!shouldSyncHostProfilePassword({
|
||||
localCredentialAuth: serverInfo?.localCredentialAuth === true,
|
||||
connections: host?.connections ?? [],
|
||||
})
|
||||
) {
|
||||
return;
|
||||
}
|
||||
await setHostPassword(serverId, nextPassword ?? "");
|
||||
},
|
||||
[host?.connections, serverId, serverInfo?.localCredentialAuth, setHostPassword],
|
||||
);
|
||||
|
||||
const executeMutation = useCallback(
|
||||
async (
|
||||
action: "set" | "change" | "remove",
|
||||
payload: {
|
||||
password: string | null;
|
||||
currentPassword?: string;
|
||||
},
|
||||
) => {
|
||||
if (!client) {
|
||||
model.finishSubmitError({ message: t("workspace.terminal.hostDisconnected") });
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const result = await client.setDaemonPassword(payload);
|
||||
await syncProfilePasswordIfNeeded(payload.password);
|
||||
model.finishSubmitSuccess();
|
||||
toast.show(formatSuccessToast(action, result.disconnectedSessionCount, t), {
|
||||
variant: "success",
|
||||
});
|
||||
onCompleted();
|
||||
} catch (error) {
|
||||
model.finishSubmitError(extractRpcError(error, t("errors.unableToSave")));
|
||||
}
|
||||
},
|
||||
[client, model, onCompleted, syncProfilePasswordIfNeeded, t, toast],
|
||||
);
|
||||
|
||||
const handleSubmit = useCallback(() => {
|
||||
const attempt = model.beginSubmit();
|
||||
if (!attempt.valid) return;
|
||||
void executeMutation(state.step, attempt.payload);
|
||||
}, [executeMutation, model, state.step]);
|
||||
|
||||
const handleRequestRemove = useCallback(() => {
|
||||
if (state.submitting) return;
|
||||
if (!state.isLocalCredential) {
|
||||
model.enterRemoveStep();
|
||||
return;
|
||||
}
|
||||
void (async () => {
|
||||
const confirmed = await confirmDialog({
|
||||
title: t("devices.password.removeTitle"),
|
||||
message: t("devices.password.removeWarning"),
|
||||
confirmLabel: t("devices.password.removeAction"),
|
||||
cancelLabel: t("common.actions.cancel"),
|
||||
destructive: true,
|
||||
});
|
||||
if (!confirmed) return;
|
||||
model.enterRemoveStep();
|
||||
const attempt = model.beginSubmit();
|
||||
if (!attempt.valid) return;
|
||||
await executeMutation("remove", attempt.payload);
|
||||
})();
|
||||
}, [executeMutation, model, state.isLocalCredential, state.submitting, t]);
|
||||
|
||||
const showCurrentPassword =
|
||||
(state.step === "change" || state.step === "remove") && !state.isLocalCredential;
|
||||
const primaryLabel = resolvePrimaryButtonLabel(state.step, state.submitting, t);
|
||||
|
||||
return (
|
||||
<View style={styles.form} testID={`daemon-password-form-${state.step}`}>
|
||||
<DaemonPasswordStepBanner step={state.step} t={t} />
|
||||
|
||||
{showCurrentPassword ? (
|
||||
<PasswordInputField
|
||||
key={`current-${state.step}`}
|
||||
label={t("devices.password.fields.current")}
|
||||
initialValue={state.currentPassword}
|
||||
showPassword={state.showCurrentPassword}
|
||||
onChangeText={model.setCurrentPassword}
|
||||
onToggleShow={model.toggleShowCurrentPassword}
|
||||
onSubmitEditing={state.step === "remove" ? handleSubmit : undefined}
|
||||
error={translateFieldError(state.fieldErrors.currentPassword, t)}
|
||||
disabled={state.submitting}
|
||||
autoFocus
|
||||
size={fieldSize}
|
||||
returnKeyType={state.step === "remove" ? "done" : "next"}
|
||||
testID="daemon-password-current-input"
|
||||
/>
|
||||
) : null}
|
||||
|
||||
{state.step !== "remove" ? (
|
||||
<>
|
||||
<PasswordInputField
|
||||
key={`new-${state.step}`}
|
||||
label={t("devices.password.fields.new")}
|
||||
initialValue={state.newPassword}
|
||||
showPassword={state.showNewPassword}
|
||||
onChangeText={model.setNewPassword}
|
||||
onToggleShow={model.toggleShowNewPassword}
|
||||
error={translateFieldError(state.fieldErrors.newPassword, t)}
|
||||
disabled={state.submitting}
|
||||
autoFocus={!showCurrentPassword}
|
||||
size={fieldSize}
|
||||
testID="daemon-password-new-input"
|
||||
/>
|
||||
<PasswordInputField
|
||||
key={`confirm-${state.step}`}
|
||||
label={
|
||||
state.step === "set"
|
||||
? t("devices.password.fields.confirm")
|
||||
: t("devices.password.fields.confirmNew")
|
||||
}
|
||||
initialValue={state.confirmPassword}
|
||||
showPassword={state.showConfirmPassword}
|
||||
onChangeText={model.setConfirmPassword}
|
||||
onToggleShow={model.toggleShowConfirmPassword}
|
||||
onSubmitEditing={handleSubmit}
|
||||
error={translateFieldError(state.fieldErrors.confirmPassword, t)}
|
||||
disabled={state.submitting}
|
||||
size={fieldSize}
|
||||
returnKeyType="done"
|
||||
testID="daemon-password-confirm-input"
|
||||
/>
|
||||
</>
|
||||
) : null}
|
||||
|
||||
{state.submitError ? (
|
||||
<Alert
|
||||
size="sm"
|
||||
variant="error"
|
||||
description={state.submitError}
|
||||
testID="daemon-password-submit-error"
|
||||
/>
|
||||
) : null}
|
||||
|
||||
<View style={styles.actions}>
|
||||
<Button
|
||||
variant="secondary"
|
||||
style={FLEX_ONE_STYLE}
|
||||
onPress={state.step === "remove" ? model.backToChangeStep : onCancel}
|
||||
disabled={state.submitting}
|
||||
testID="daemon-password-cancel-button"
|
||||
>
|
||||
{t("common.actions.cancel")}
|
||||
</Button>
|
||||
<Button
|
||||
variant={state.step === "remove" ? "destructive" : "default"}
|
||||
style={FLEX_ONE_STYLE}
|
||||
loading={state.submitting}
|
||||
disabled={state.submitting}
|
||||
onPress={handleSubmit}
|
||||
testID="daemon-password-submit-button"
|
||||
>
|
||||
{primaryLabel}
|
||||
</Button>
|
||||
</View>
|
||||
|
||||
{state.step === "change" ? (
|
||||
<View style={styles.removeSection}>
|
||||
<View style={styles.divider} />
|
||||
<Button
|
||||
variant="ghost"
|
||||
onPress={handleRequestRemove}
|
||||
disabled={state.submitting}
|
||||
textStyle={styles.removeButtonText}
|
||||
testID="daemon-password-remove-trigger"
|
||||
>
|
||||
{t("devices.password.removeAction")}
|
||||
</Button>
|
||||
</View>
|
||||
) : null}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
export interface DaemonPasswordSheetProps {
|
||||
serverId: string;
|
||||
visible: boolean;
|
||||
initialMode: "set" | "change";
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
export function DaemonPasswordSheet({
|
||||
serverId,
|
||||
visible,
|
||||
initialMode,
|
||||
onClose,
|
||||
}: DaemonPasswordSheetProps) {
|
||||
if (!visible) return null;
|
||||
return (
|
||||
<DaemonPasswordSheetOpen
|
||||
key={`${serverId}:${initialMode}`}
|
||||
serverId={serverId}
|
||||
initialMode={initialMode}
|
||||
onClose={onClose}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function DaemonPasswordSheetOpen({
|
||||
serverId,
|
||||
initialMode,
|
||||
onClose,
|
||||
}: Omit<DaemonPasswordSheetProps, "visible">) {
|
||||
const { t } = useTranslation();
|
||||
const isLocalCredential = useSessionStore(
|
||||
(state) => state.sessions[serverId]?.serverInfo?.localCredentialAuth === true,
|
||||
);
|
||||
const [model] = useState(() =>
|
||||
openDaemonPasswordForm({
|
||||
mode: initialMode,
|
||||
isLocalCredential,
|
||||
}),
|
||||
);
|
||||
const state = useSyncExternalStore(model.subscribe, model.getState, model.getState);
|
||||
|
||||
const handleClose = useCallback(() => {
|
||||
if (state.submitting) return;
|
||||
onClose();
|
||||
}, [onClose, state.submitting]);
|
||||
|
||||
const header = useMemo<SheetHeader>(() => {
|
||||
if (state.step === "remove") {
|
||||
return {
|
||||
title: t("devices.password.removeTitle"),
|
||||
back: {
|
||||
onPress: model.backToChangeStep,
|
||||
label: t("common.actions.back"),
|
||||
},
|
||||
};
|
||||
}
|
||||
return {
|
||||
title:
|
||||
state.step === "set" ? t("devices.password.setTitle") : t("devices.password.changeTitle"),
|
||||
};
|
||||
}, [model.backToChangeStep, state.step, t]);
|
||||
|
||||
return (
|
||||
<AdaptiveModalSheet
|
||||
header={header}
|
||||
visible
|
||||
onClose={handleClose}
|
||||
snapPoints={SNAP_POINTS}
|
||||
desktopMaxWidth={440}
|
||||
testID="daemon-password-sheet"
|
||||
>
|
||||
<DaemonPasswordFormContent
|
||||
serverId={serverId}
|
||||
initialMode={initialMode}
|
||||
model={model}
|
||||
onCancel={handleClose}
|
||||
onCompleted={onClose}
|
||||
/>
|
||||
</AdaptiveModalSheet>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
form: {
|
||||
gap: theme.spacing[4],
|
||||
},
|
||||
passwordRow: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: theme.spacing[2],
|
||||
},
|
||||
passwordInputWrap: {
|
||||
flex: 1,
|
||||
minWidth: 0,
|
||||
},
|
||||
actions: {
|
||||
flexDirection: "row",
|
||||
gap: theme.spacing[3],
|
||||
marginTop: theme.spacing[1],
|
||||
},
|
||||
removeSection: {
|
||||
gap: theme.spacing[3],
|
||||
marginTop: theme.spacing[1],
|
||||
},
|
||||
divider: {
|
||||
height: theme.borderWidth[1],
|
||||
backgroundColor: theme.colors.border,
|
||||
},
|
||||
removeButtonText: {
|
||||
color: theme.colors.destructive,
|
||||
},
|
||||
}));
|
||||
@@ -6,9 +6,10 @@ import { AdaptiveModalSheet, type SheetHeader } from "@/components/adaptive-moda
|
||||
import { Button } from "@/components/ui/button";
|
||||
import type { Theme } from "@/styles/theme";
|
||||
import { PairDeviceSection } from "./pair-device-section";
|
||||
import { DaemonPasswordFormContent } from "./daemon-password-sheet";
|
||||
import { WaysToConnect } from "./ways-to-connect";
|
||||
|
||||
const SNAP_POINTS: string[] = ["72%", "92%"];
|
||||
const SNAP_POINTS: string[] = ["80%", "92%"];
|
||||
const ThemedPlus = withUnistyles(Plus);
|
||||
const iconProps = (theme: Theme) => ({
|
||||
size: theme.iconSize.sm,
|
||||
@@ -16,7 +17,7 @@ const iconProps = (theme: Theme) => ({
|
||||
});
|
||||
const plusIcon = <ThemedPlus uniProps={iconProps} />;
|
||||
|
||||
type PairStep = "ways" | "relay";
|
||||
type PairStep = "ways" | "relay" | "password";
|
||||
|
||||
export function PairDeviceHeaderAction({ serverId }: { serverId: string }) {
|
||||
const { t } = useTranslation();
|
||||
@@ -35,22 +36,59 @@ export function PairDeviceHeaderAction({ serverId }: { serverId: string }) {
|
||||
}, []);
|
||||
const handleOpenRelay = useCallback(() => setStep("relay"), []);
|
||||
const handleBackToWays = useCallback(() => setStep("ways"), []);
|
||||
const handleOpenPassword = useCallback(() => setStep("password"), []);
|
||||
const handleBackToRelay = useCallback(() => setStep("relay"), []);
|
||||
|
||||
const header = useMemo<SheetHeader>(
|
||||
() =>
|
||||
step === "relay"
|
||||
? {
|
||||
title: t("devices.relay.title"),
|
||||
back: {
|
||||
onPress: handleBackToWays,
|
||||
label: t("common.actions.back"),
|
||||
},
|
||||
}
|
||||
: {
|
||||
title: t("settings.host.pairDevices.rowTitle"),
|
||||
},
|
||||
[handleBackToWays, step, t],
|
||||
);
|
||||
const header = useMemo<SheetHeader>(() => {
|
||||
if (step === "password") {
|
||||
return {
|
||||
title: t("devices.password.setTitle"),
|
||||
back: {
|
||||
onPress: handleBackToRelay,
|
||||
label: t("common.actions.back"),
|
||||
},
|
||||
};
|
||||
}
|
||||
if (step === "relay") {
|
||||
return {
|
||||
title: t("devices.relay.title"),
|
||||
back: {
|
||||
onPress: handleBackToWays,
|
||||
label: t("common.actions.back"),
|
||||
},
|
||||
};
|
||||
}
|
||||
return {
|
||||
title: t("settings.host.pairDevices.rowTitle"),
|
||||
};
|
||||
}, [handleBackToRelay, handleBackToWays, step, t]);
|
||||
|
||||
let sheetTestID = "devices-pair-sheet";
|
||||
if (step === "relay") sheetTestID = "devices-relay-pairing";
|
||||
else if (step === "password") sheetTestID = "devices-pair-password-step";
|
||||
|
||||
let sheetContent: React.ReactNode;
|
||||
if (step === "password") {
|
||||
sheetContent = (
|
||||
<DaemonPasswordFormContent
|
||||
key={`${serverId}:pair-password`}
|
||||
serverId={serverId}
|
||||
initialMode="set"
|
||||
onCancel={handleBackToRelay}
|
||||
onCompleted={handleBackToRelay}
|
||||
/>
|
||||
);
|
||||
} else if (step === "relay") {
|
||||
sheetContent = (
|
||||
<PairDeviceSection
|
||||
serverId={serverId}
|
||||
onClose={handleClose}
|
||||
onOpenPassword={handleOpenPassword}
|
||||
/>
|
||||
);
|
||||
} else {
|
||||
sheetContent = <WaysToConnect serverId={serverId} onOpenRelay={handleOpenRelay} />;
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
@@ -69,14 +107,10 @@ export function PairDeviceHeaderAction({ serverId }: { serverId: string }) {
|
||||
onDismiss={handleDismiss}
|
||||
snapPoints={SNAP_POINTS}
|
||||
desktopMaxWidth={480}
|
||||
desktopHeight={520}
|
||||
testID={step === "relay" ? "devices-relay-pairing" : "devices-pair-sheet"}
|
||||
desktopHeight={560}
|
||||
testID={sheetTestID}
|
||||
>
|
||||
{step === "relay" ? (
|
||||
<PairDeviceSection serverId={serverId} onClose={handleClose} />
|
||||
) : (
|
||||
<WaysToConnect serverId={serverId} onOpenRelay={handleOpenRelay} />
|
||||
)}
|
||||
{sheetContent}
|
||||
</AdaptiveModalSheet>
|
||||
</>
|
||||
);
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { useMemo } from "react";
|
||||
import { useCallback, useMemo, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { AdaptiveModalSheet, type SheetHeader } from "@/components/adaptive-modal-sheet";
|
||||
import { PairDeviceSection } from "@/devices/pair-device-section";
|
||||
import { DaemonPasswordFormContent } from "@/devices/daemon-password-sheet";
|
||||
|
||||
export interface PairDeviceModalProps {
|
||||
serverId: string;
|
||||
@@ -10,13 +11,28 @@ export interface PairDeviceModalProps {
|
||||
testID?: string;
|
||||
}
|
||||
|
||||
const SNAP_POINTS: string[] = ["72%", "92%"];
|
||||
const SNAP_POINTS: string[] = ["80%", "92%"];
|
||||
|
||||
export function PairDeviceModal({ serverId, visible, onClose, testID }: PairDeviceModalProps) {
|
||||
const { t } = useTranslation();
|
||||
const [step, setStep] = useState<"relay" | "password">("relay");
|
||||
|
||||
const handleOpenPassword = useCallback(() => setStep("password"), []);
|
||||
const handleBackToRelay = useCallback(() => setStep("relay"), []);
|
||||
const handleDismiss = useCallback(() => setStep("relay"), []);
|
||||
|
||||
const header = useMemo<SheetHeader>(
|
||||
() => ({ title: t("settings.host.pairDevices.rowTitle") }),
|
||||
[t],
|
||||
() =>
|
||||
step === "password"
|
||||
? {
|
||||
title: t("devices.password.setTitle"),
|
||||
back: {
|
||||
onPress: handleBackToRelay,
|
||||
label: t("common.actions.back"),
|
||||
},
|
||||
}
|
||||
: { title: t("settings.host.pairDevices.rowTitle") },
|
||||
[handleBackToRelay, step, t],
|
||||
);
|
||||
|
||||
return (
|
||||
@@ -24,11 +40,26 @@ export function PairDeviceModal({ serverId, visible, onClose, testID }: PairDevi
|
||||
header={header}
|
||||
visible={visible}
|
||||
onClose={onClose}
|
||||
onDismiss={handleDismiss}
|
||||
snapPoints={SNAP_POINTS}
|
||||
desktopMaxWidth={480}
|
||||
testID={testID}
|
||||
>
|
||||
<PairDeviceSection serverId={serverId} onClose={onClose} />
|
||||
{step === "password" ? (
|
||||
<DaemonPasswordFormContent
|
||||
key={`${serverId}:modal-password`}
|
||||
serverId={serverId}
|
||||
initialMode="set"
|
||||
onCancel={handleBackToRelay}
|
||||
onCompleted={handleBackToRelay}
|
||||
/>
|
||||
) : (
|
||||
<PairDeviceSection
|
||||
serverId={serverId}
|
||||
onClose={onClose}
|
||||
onOpenPassword={handleOpenPassword}
|
||||
/>
|
||||
)}
|
||||
</AdaptiveModalSheet>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -15,6 +15,7 @@ import { useFetchQuery } from "@/data/query";
|
||||
import { daemonPairingOfferQueryKey } from "@/data/daemon-pairing";
|
||||
import { useDaemonConfig } from "@/hooks/use-daemon-config";
|
||||
import { useHostRuntimeClient, useHostRuntimeSnapshot } from "@/runtime/host-runtime";
|
||||
import { useSessionStore, type DaemonServerInfo } from "@/stores/session-store";
|
||||
import type { Theme } from "@/styles/theme";
|
||||
import {
|
||||
EditingTextInput as TextInput,
|
||||
@@ -33,24 +34,42 @@ const foregroundMutedColorMapping = (theme: Theme) => ({
|
||||
});
|
||||
const accentBrightColorMapping = (theme: Theme) => ({ color: theme.colors.accentBright });
|
||||
|
||||
function canOfferSetPassword(
|
||||
serverInfo: DaemonServerInfo | null,
|
||||
serverFeatures: DaemonServerInfo["features"] | undefined,
|
||||
onOpenPassword: (() => void) | undefined,
|
||||
): boolean {
|
||||
if (!onOpenPassword) return false;
|
||||
// COMPAT(daemonPasswordManagement): added in v0.19.x, remove gate after 2027-06-15.
|
||||
if (serverFeatures?.daemonPasswordManagement !== true) return false;
|
||||
if (serverInfo?.passwordManagedByEnv === true) return false;
|
||||
const permissions = serverInfo?.permissions;
|
||||
if (!permissions) return true;
|
||||
return permissions.includes("daemon.manage") && permissions.includes("access.manage");
|
||||
}
|
||||
|
||||
export interface PairDeviceSectionProps {
|
||||
serverId: string;
|
||||
onClose: () => void;
|
||||
onOpenPassword?: () => void;
|
||||
}
|
||||
|
||||
export function PairDeviceSection({ serverId, onClose }: PairDeviceSectionProps) {
|
||||
export function PairDeviceSection({ serverId, onClose, onOpenPassword }: PairDeviceSectionProps) {
|
||||
const { t } = useTranslation();
|
||||
const client = useHostRuntimeClient(serverId);
|
||||
const runtimeSnapshot = useHostRuntimeSnapshot(serverId);
|
||||
const serverInfo = useSessionStore((state) => state.sessions[serverId]?.serverInfo ?? null);
|
||||
const isConnected = runtimeSnapshot?.connectionStatus === "online";
|
||||
const isDisconnected =
|
||||
runtimeSnapshot?.connectionStatus === "offline" ||
|
||||
runtimeSnapshot?.connectionStatus === "error";
|
||||
const { patchConfig } = useDaemonConfig(serverId);
|
||||
const [copied, setCopied] = useState(false);
|
||||
const serverFeatures = client?.getLastServerInfoMessage()?.features;
|
||||
const serverFeatures = serverInfo?.features ?? client?.getLastServerInfoMessage()?.features;
|
||||
const supportsPairingRpc = serverFeatures?.daemonStatusRpc === true;
|
||||
const canConfigureRelay = supportsPairingRpc && serverFeatures?.relayConfig === true;
|
||||
const passwordConfigured = serverInfo?.passwordConfigured === true;
|
||||
const canSetPassword = canOfferSetPassword(serverInfo, serverFeatures, onOpenPassword);
|
||||
|
||||
const pairingQuery = useFetchQuery({
|
||||
queryKey: daemonPairingOfferQueryKey(serverId),
|
||||
@@ -123,6 +142,9 @@ export function PairDeviceSection({ serverId, onClose }: PairDeviceSectionProps)
|
||||
onEnableRelay={handleEnableRelay}
|
||||
onClose={onClose}
|
||||
onCopy={handleCopyPress}
|
||||
passwordConfigured={passwordConfigured}
|
||||
canSetPassword={canSetPassword}
|
||||
onOpenPassword={onOpenPassword}
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
@@ -143,6 +165,9 @@ interface PairDeviceBodyProps {
|
||||
onEnableRelay: () => void;
|
||||
onClose: () => void;
|
||||
onCopy: () => void;
|
||||
passwordConfigured: boolean;
|
||||
canSetPassword: boolean;
|
||||
onOpenPassword?: () => void;
|
||||
}
|
||||
|
||||
function PairDeviceBody(props: PairDeviceBodyProps) {
|
||||
@@ -267,7 +292,32 @@ function PairingOffer(props: PairDeviceBodyProps & { offer: { url: string } }) {
|
||||
{props.copied ? t("pairing.device.copied") : t("pairing.device.copy")}
|
||||
</Button>
|
||||
</View>
|
||||
<Alert size="sm" variant="warning" description={t("pairing.device.securityWarning")} />
|
||||
{props.passwordConfigured ? (
|
||||
<Alert
|
||||
size="sm"
|
||||
variant="info"
|
||||
description={t("pairing.device.passwordProtected")}
|
||||
testID="pairing-password-protected-alert"
|
||||
/>
|
||||
) : (
|
||||
<Alert
|
||||
size="sm"
|
||||
variant="warning"
|
||||
description={t("pairing.device.securityWarning")}
|
||||
testID="pairing-no-password-alert"
|
||||
>
|
||||
{props.canSetPassword && props.onOpenPassword ? (
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
onPress={props.onOpenPassword}
|
||||
testID="pairing-set-password-button"
|
||||
>
|
||||
{t("devices.password.setAction")}
|
||||
</Button>
|
||||
) : null}
|
||||
</Alert>
|
||||
)}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -353,7 +403,7 @@ const styles = StyleSheet.create((theme) => ({
|
||||
lineHeight: theme.fontSize.sm * 1.5,
|
||||
},
|
||||
offer: {
|
||||
gap: theme.spacing[4],
|
||||
gap: theme.spacing[3],
|
||||
},
|
||||
offerHint: {
|
||||
color: theme.colors.foregroundMuted,
|
||||
@@ -364,7 +414,7 @@ const styles = StyleSheet.create((theme) => ({
|
||||
alignSelf: "center",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
width: 304,
|
||||
width: 224,
|
||||
maxWidth: "100%",
|
||||
aspectRatio: 1,
|
||||
padding: theme.spacing[3],
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { useCheckboxSpaceKey } from "@/components/ui/checkbox";
|
||||
import { PressHighlight } from "@/components/ui/press-highlight";
|
||||
import { useCallback, useMemo, useRef, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
@@ -470,6 +471,7 @@ function DirectFormFields({
|
||||
if (isSaving) return;
|
||||
onChange(editForm(input, { useTls: !input.useTls }));
|
||||
}, [input, isSaving, onChange]);
|
||||
const tlsCheckboxKeyProps = useCheckboxSpaceKey(handleToggleUseTls, isSaving);
|
||||
const handleTogglePasswordVisibility = useCallback(() => {
|
||||
setIsPasswordVisible((current) => !current);
|
||||
}, []);
|
||||
@@ -530,6 +532,7 @@ function DirectFormFields({
|
||||
accessibilityState={useTlsAccessibilityState}
|
||||
aria-checked={input.useTls}
|
||||
testID="direct-ssl-toggle"
|
||||
{...tlsCheckboxKeyProps}
|
||||
>
|
||||
<View style={checkboxStyle}>
|
||||
{input.useTls ? (
|
||||
|
||||
@@ -2019,6 +2019,56 @@ export const ar: TranslationResources = {
|
||||
confirmMessage: "هذا الجهاز متصل عبر Tailscale وسيفقد اتصاله بالمضيف.",
|
||||
confirmAction: "إيقاف",
|
||||
},
|
||||
access: {
|
||||
title: "الوصول",
|
||||
passwordLabel: "كلمة المرور",
|
||||
passwordNotSetSummary: "غير مضبوطة",
|
||||
passwordNotSetHint: "يمكن لأي شخص لديه رابط اقتران الاتصال",
|
||||
passwordSetSummary: "مضبوطة",
|
||||
passwordSetHint: "مطلوبة للاتصالات البعيدة",
|
||||
passwordEnvSummary: "مضبوطة عبر البيئة",
|
||||
passwordEnvHint: "يتم التحكم بها عبر PASEO_PASSWORD على هذا المضيف",
|
||||
},
|
||||
password: {
|
||||
setTitle: "تعيين كلمة المرور",
|
||||
changeTitle: "تغيير كلمة المرور",
|
||||
removeTitle: "إزالة كلمة المرور",
|
||||
setAction: "تعيين كلمة المرور",
|
||||
setting: "جارٍ التعيين...",
|
||||
saveAction: "حفظ كلمة المرور",
|
||||
saving: "جارٍ الحفظ...",
|
||||
removeAction: "إزالة كلمة المرور",
|
||||
removing: "جارٍ الإزالة...",
|
||||
show: "إظهار كلمة المرور",
|
||||
hide: "إخفاء كلمة المرور",
|
||||
setInfo:
|
||||
"سيتم قطع اتصال الأجهزة البعيدة الأخرى فورًا وستحتاج إلى كلمة المرور هذه. سيبقى هذا الجهاز متصلًا.",
|
||||
changeInfo:
|
||||
"سيتم قطع اتصال الأجهزة البعيدة الأخرى فورًا وستحتاج إلى كلمة المرور الجديدة. سيبقى هذا الجهاز متصلًا.",
|
||||
removeWarning: "سيتمكن أي شخص لديه رابط اقتران أو وصول إلى الشبكة من الاتصال دون كلمة مرور.",
|
||||
fields: {
|
||||
current: "كلمة المرور الحالية",
|
||||
new: "كلمة المرور الجديدة",
|
||||
confirm: "تأكيد كلمة المرور",
|
||||
confirmNew: "تأكيد كلمة المرور الجديدة",
|
||||
},
|
||||
errors: {
|
||||
currentRequired: "أدخل كلمة المرور الحالية.",
|
||||
currentIncorrect: "كلمة المرور الحالية غير صحيحة.",
|
||||
tooShort: "استخدم 8 أحرف على الأقل.",
|
||||
tooLong: "يجب أن تكون كلمة المرور 72 بايت أو أقل.",
|
||||
mismatch: "كلمتا المرور غير متطابقتين.",
|
||||
},
|
||||
toast: {
|
||||
set: "تم تعيين كلمة المرور.",
|
||||
setDisconnectedOne: "تم تعيين كلمة المرور. تم قطع اتصال جهاز آخر واحد.",
|
||||
setDisconnectedOther: "تم تعيين كلمة المرور. تم قطع اتصال {{count}} أجهزة أخرى.",
|
||||
updated: "تم تحديث كلمة المرور.",
|
||||
updatedDisconnectedOne: "تم تحديث كلمة المرور. تم قطع اتصال جهاز آخر واحد.",
|
||||
updatedDisconnectedOther: "تم تحديث كلمة المرور. تم قطع اتصال {{count}} أجهزة أخرى.",
|
||||
removed: "تمت إزالة كلمة المرور.",
|
||||
},
|
||||
},
|
||||
connected: {
|
||||
title: "العملاء المتصلون",
|
||||
thisDevice: "هذا الجهاز",
|
||||
@@ -2249,6 +2299,8 @@ export const ar: TranslationResources = {
|
||||
hint: "قم بمسح رمز QR هذا باستخدام Paseo على هاتفك، أو انسخ الرابط أدناه.",
|
||||
securityWarning:
|
||||
"تعامل مع رابط الاقتران هذا ككلمة مرور. يمكن لأي شخص يملكه الوصول إلى هذا البرنامج الخفي.",
|
||||
passwordProtected:
|
||||
"كلمة المرور مطلوبة. ستقوم الأجهزة التي تمسح هذا الرمز بإدخال كلمة مرور هذا المضيف.",
|
||||
qrUnavailable: "رمز QR غير متاح.",
|
||||
qrAccessibility: "رمز QR للإقران",
|
||||
retry: "أعد المحاولة",
|
||||
|
||||
@@ -2049,6 +2049,57 @@ export const en = {
|
||||
"This device is connected through Tailscale and will lose its connection to the host.",
|
||||
confirmAction: "Turn off",
|
||||
},
|
||||
access: {
|
||||
title: "Access",
|
||||
passwordLabel: "Password",
|
||||
passwordNotSetSummary: "Not set",
|
||||
passwordNotSetHint: "Anyone with a pairing link can connect",
|
||||
passwordSetSummary: "Set",
|
||||
passwordSetHint: "Required for remote connections",
|
||||
passwordEnvSummary: "Set by environment",
|
||||
passwordEnvHint: "Controlled by PASEO_PASSWORD on this host",
|
||||
},
|
||||
password: {
|
||||
setTitle: "Set password",
|
||||
changeTitle: "Change password",
|
||||
removeTitle: "Remove password",
|
||||
setAction: "Set password",
|
||||
setting: "Setting...",
|
||||
saveAction: "Save password",
|
||||
saving: "Saving...",
|
||||
removeAction: "Remove password",
|
||||
removing: "Removing...",
|
||||
show: "Show password",
|
||||
hide: "Hide password",
|
||||
setInfo:
|
||||
"Other remote devices disconnect immediately and will need this password. This device stays connected.",
|
||||
changeInfo:
|
||||
"Other remote devices disconnect immediately and will need the new password. This device stays connected.",
|
||||
removeWarning:
|
||||
"Anyone with a pairing link or network access will be able to connect without a password.",
|
||||
fields: {
|
||||
current: "Current password",
|
||||
new: "New password",
|
||||
confirm: "Confirm password",
|
||||
confirmNew: "Confirm new password",
|
||||
},
|
||||
errors: {
|
||||
currentRequired: "Enter the current password.",
|
||||
currentIncorrect: "Current password is incorrect.",
|
||||
tooShort: "Use at least 8 characters.",
|
||||
tooLong: "Password must be 72 bytes or fewer.",
|
||||
mismatch: "Passwords do not match.",
|
||||
},
|
||||
toast: {
|
||||
set: "Password set.",
|
||||
setDisconnectedOne: "Password set. Disconnected 1 other device.",
|
||||
setDisconnectedOther: "Password set. Disconnected {{count}} other devices.",
|
||||
updated: "Password updated.",
|
||||
updatedDisconnectedOne: "Password updated. Disconnected 1 other device.",
|
||||
updatedDisconnectedOther: "Password updated. Disconnected {{count}} other devices.",
|
||||
removed: "Password removed.",
|
||||
},
|
||||
},
|
||||
connected: {
|
||||
title: "Connected clients",
|
||||
thisDevice: "This device",
|
||||
@@ -2279,6 +2330,8 @@ export const en = {
|
||||
hint: "Scan this QR code with Paseo on your phone, or copy the link below.",
|
||||
securityWarning:
|
||||
"Treat this pairing link like a password. Anyone with it can access this daemon.",
|
||||
passwordProtected:
|
||||
"Password required. Devices scanning this code will enter this host's password.",
|
||||
qrUnavailable: "QR code unavailable.",
|
||||
qrAccessibility: "Pairing QR code",
|
||||
retry: "Retry",
|
||||
|
||||
@@ -2073,6 +2073,59 @@ export const es: TranslationResources = {
|
||||
"Este dispositivo está conectado mediante Tailscale y perderá la conexión con el host.",
|
||||
confirmAction: "Desactivar",
|
||||
},
|
||||
access: {
|
||||
title: "Acceso",
|
||||
passwordLabel: "Contraseña",
|
||||
passwordNotSetSummary: "Sin configurar",
|
||||
passwordNotSetHint: "Cualquiera con un enlace de emparejamiento puede conectarse",
|
||||
passwordSetSummary: "Configurada",
|
||||
passwordSetHint: "Obligatoria para conexiones remotas",
|
||||
passwordEnvSummary: "Definida por el entorno",
|
||||
passwordEnvHint: "Controlada por PASEO_PASSWORD en este host",
|
||||
},
|
||||
password: {
|
||||
setTitle: "Establecer contraseña",
|
||||
changeTitle: "Cambiar contraseña",
|
||||
removeTitle: "Eliminar contraseña",
|
||||
setAction: "Establecer contraseña",
|
||||
setting: "Estableciendo...",
|
||||
saveAction: "Guardar contraseña",
|
||||
saving: "Guardando...",
|
||||
removeAction: "Eliminar contraseña",
|
||||
removing: "Eliminando...",
|
||||
show: "Mostrar contraseña",
|
||||
hide: "Ocultar contraseña",
|
||||
setInfo:
|
||||
"Los demás dispositivos remotos se desconectarán de inmediato y necesitarán esta contraseña. Este dispositivo seguirá conectado.",
|
||||
changeInfo:
|
||||
"Los demás dispositivos remotos se desconectarán de inmediato y necesitarán la nueva contraseña. Este dispositivo seguirá conectado.",
|
||||
removeWarning:
|
||||
"Cualquiera con un enlace de emparejamiento o acceso a la red podrá conectarse sin contraseña.",
|
||||
fields: {
|
||||
current: "Contraseña actual",
|
||||
new: "Nueva contraseña",
|
||||
confirm: "Confirmar contraseña",
|
||||
confirmNew: "Confirmar nueva contraseña",
|
||||
},
|
||||
errors: {
|
||||
currentRequired: "Introduce la contraseña actual.",
|
||||
currentIncorrect: "La contraseña actual es incorrecta.",
|
||||
tooShort: "Usa al menos 8 caracteres.",
|
||||
tooLong: "La contraseña debe tener 72 bytes o menos.",
|
||||
mismatch: "Las contraseñas no coinciden.",
|
||||
},
|
||||
toast: {
|
||||
set: "Contraseña establecida.",
|
||||
setDisconnectedOne: "Contraseña establecida. Se desconectó otro dispositivo.",
|
||||
setDisconnectedOther:
|
||||
"Contraseña establecida. Se desconectaron otros {{count}} dispositivos.",
|
||||
updated: "Contraseña actualizada.",
|
||||
updatedDisconnectedOne: "Contraseña actualizada. Se desconectó otro dispositivo.",
|
||||
updatedDisconnectedOther:
|
||||
"Contraseña actualizada. Se desconectaron otros {{count}} dispositivos.",
|
||||
removed: "Contraseña eliminada.",
|
||||
},
|
||||
},
|
||||
connected: {
|
||||
title: "Clientes conectados",
|
||||
thisDevice: "Este dispositivo",
|
||||
@@ -2305,6 +2358,8 @@ export const es: TranslationResources = {
|
||||
hint: "Escanee este códigoQRconPaseoen su teléfono o copie el enlace a continuación.",
|
||||
securityWarning:
|
||||
"Trata este enlace de emparejamiento como una contraseña. Cualquiera que lo tenga puede acceder a este daemon.",
|
||||
passwordProtected:
|
||||
"Contraseña obligatoria. Los dispositivos que escaneen este código deberán introducir la contraseña de este host.",
|
||||
qrUnavailable: "CódigoQRno disponible.",
|
||||
qrAccessibility: "Código QR de emparejamiento",
|
||||
retry: "Rever",
|
||||
|
||||
@@ -2070,6 +2070,58 @@ export const fr: TranslationResources = {
|
||||
confirmMessage: "Cet appareil est connecté via Tailscale et perdra sa connexion à l’hôte.",
|
||||
confirmAction: "Désactiver",
|
||||
},
|
||||
access: {
|
||||
title: "Accès",
|
||||
passwordLabel: "Mot de passe",
|
||||
passwordNotSetSummary: "Non défini",
|
||||
passwordNotSetHint: "Toute personne disposant d’un lien d’association peut se connecter",
|
||||
passwordSetSummary: "Défini",
|
||||
passwordSetHint: "Requis pour les connexions distantes",
|
||||
passwordEnvSummary: "Défini par l’environnement",
|
||||
passwordEnvHint: "Contrôlé par PASEO_PASSWORD sur cet hôte",
|
||||
},
|
||||
password: {
|
||||
setTitle: "Définir le mot de passe",
|
||||
changeTitle: "Modifier le mot de passe",
|
||||
removeTitle: "Supprimer le mot de passe",
|
||||
setAction: "Définir le mot de passe",
|
||||
setting: "Configuration...",
|
||||
saveAction: "Enregistrer le mot de passe",
|
||||
saving: "Enregistrement...",
|
||||
removeAction: "Supprimer le mot de passe",
|
||||
removing: "Suppression...",
|
||||
show: "Afficher le mot de passe",
|
||||
hide: "Masquer le mot de passe",
|
||||
setInfo:
|
||||
"Les autres appareils distants seront immédiatement déconnectés et devront saisir ce mot de passe. Cet appareil reste connecté.",
|
||||
changeInfo:
|
||||
"Les autres appareils distants seront immédiatement déconnectés et devront saisir le nouveau mot de passe. Cet appareil reste connecté.",
|
||||
removeWarning:
|
||||
"Toute personne disposant d’un lien d’association ou d’un accès réseau pourra se connecter sans mot de passe.",
|
||||
fields: {
|
||||
current: "Mot de passe actuel",
|
||||
new: "Nouveau mot de passe",
|
||||
confirm: "Confirmer le mot de passe",
|
||||
confirmNew: "Confirmer le nouveau mot de passe",
|
||||
},
|
||||
errors: {
|
||||
currentRequired: "Saisissez le mot de passe actuel.",
|
||||
currentIncorrect: "Le mot de passe actuel est incorrect.",
|
||||
tooShort: "Utilisez au moins 8 caractères.",
|
||||
tooLong: "Le mot de passe doit faire 72 octets ou moins.",
|
||||
mismatch: "Les mots de passe ne correspondent pas.",
|
||||
},
|
||||
toast: {
|
||||
set: "Mot de passe défini.",
|
||||
setDisconnectedOne: "Mot de passe défini. 1 autre appareil déconnecté.",
|
||||
setDisconnectedOther: "Mot de passe défini. {{count}} autres appareils déconnectés.",
|
||||
updated: "Mot de passe mis à jour.",
|
||||
updatedDisconnectedOne: "Mot de passe mis à jour. 1 autre appareil déconnecté.",
|
||||
updatedDisconnectedOther:
|
||||
"Mot de passe mis à jour. {{count}} autres appareils déconnectés.",
|
||||
removed: "Mot de passe supprimé.",
|
||||
},
|
||||
},
|
||||
connected: {
|
||||
title: "Clients connectés",
|
||||
thisDevice: "Cet appareil",
|
||||
@@ -2302,6 +2354,8 @@ export const fr: TranslationResources = {
|
||||
hint: "Scannez ce code QR avec Paseo sur votre téléphone, ou copiez le lien ci-dessous.",
|
||||
securityWarning:
|
||||
"Traitez ce lien d’association comme un mot de passe. Toute personne qui le possède peut accéder à ce daemon.",
|
||||
passwordProtected:
|
||||
"Mot de passe requis. Les appareils qui scannent ce code devront saisir le mot de passe de cet hôte.",
|
||||
qrUnavailable: "Code QR indisponible.",
|
||||
qrAccessibility: "Code QR d’association",
|
||||
retry: "Réessayer",
|
||||
|
||||
@@ -2040,6 +2040,58 @@ export const ja: TranslationResources = {
|
||||
confirmMessage: "このデバイスは Tailscale 経由で接続しているため、ホストとの接続が切れます。",
|
||||
confirmAction: "オフにする",
|
||||
},
|
||||
access: {
|
||||
title: "アクセス",
|
||||
passwordLabel: "パスワード",
|
||||
passwordNotSetSummary: "未設定",
|
||||
passwordNotSetHint: "ペアリングリンクを知る誰でも接続できます",
|
||||
passwordSetSummary: "設定済み",
|
||||
passwordSetHint: "リモート接続に必須",
|
||||
passwordEnvSummary: "環境変数で設定",
|
||||
passwordEnvHint: "このホストの PASEO_PASSWORD で管理されています",
|
||||
},
|
||||
password: {
|
||||
setTitle: "パスワードを設定",
|
||||
changeTitle: "パスワードを変更",
|
||||
removeTitle: "パスワードを削除",
|
||||
setAction: "パスワードを設定",
|
||||
setting: "設定中...",
|
||||
saveAction: "パスワードを保存",
|
||||
saving: "保存中...",
|
||||
removeAction: "パスワードを削除",
|
||||
removing: "削除中...",
|
||||
show: "パスワードを表示",
|
||||
hide: "パスワードを隠す",
|
||||
setInfo:
|
||||
"他のリモートデバイスは即座に切断され、このパスワードが必要になります。このデバイスは接続を維持します。",
|
||||
changeInfo:
|
||||
"他のリモートデバイスは即座に切断され、新しいパスワードが必要になります。このデバイスは接続を維持します。",
|
||||
removeWarning:
|
||||
"ペアリングリンクまたはネットワークアクセスを持つ誰でもパスワードなしで接続できるようになります。",
|
||||
fields: {
|
||||
current: "現在のパスワード",
|
||||
new: "新しいパスワード",
|
||||
confirm: "パスワードの確認",
|
||||
confirmNew: "新しいパスワードの確認",
|
||||
},
|
||||
errors: {
|
||||
currentRequired: "現在のパスワードを入力してください。",
|
||||
currentIncorrect: "現在のパスワードが正しくありません。",
|
||||
tooShort: "8文字以上入力してください。",
|
||||
tooLong: "パスワードは72バイト以下にしてください。",
|
||||
mismatch: "パスワードが一致しません。",
|
||||
},
|
||||
toast: {
|
||||
set: "パスワードを設定しました。",
|
||||
setDisconnectedOne: "パスワードを設定しました。他の1台のデバイスを切断しました。",
|
||||
setDisconnectedOther: "パスワードを設定しました。他の{{count}}台のデバイスを切断しました。",
|
||||
updated: "パスワードを更新しました。",
|
||||
updatedDisconnectedOne: "パスワードを更新しました。他の1台のデバイスを切断しました。",
|
||||
updatedDisconnectedOther:
|
||||
"パスワードを更新しました。他の{{count}}台のデバイスを切断しました。",
|
||||
removed: "パスワードを削除しました。",
|
||||
},
|
||||
},
|
||||
connected: {
|
||||
title: "接続中のクライアント",
|
||||
thisDevice: "このデバイス",
|
||||
@@ -2272,6 +2324,8 @@ export const ja: TranslationResources = {
|
||||
hint: "スマートフォンのPaseoでこのQRコードをスキャンするか、以下のリンクをコピーしてください。",
|
||||
securityWarning:
|
||||
"このペアリングリンクはパスワードと同様に扱ってください。リンクを知っている人は誰でもこのデーモンにアクセスできます。",
|
||||
passwordProtected:
|
||||
"パスワードが必要です。このコードをスキャンしたデバイスはこのホストのパスワードを入力します。",
|
||||
qrUnavailable: "QRコードが利用できません。",
|
||||
qrAccessibility: "ペアリング QR コード",
|
||||
retry: "再試行",
|
||||
|
||||
@@ -2031,6 +2031,60 @@ export const ko: TranslationResources = {
|
||||
confirmMessage: "이 기기는 Tailscale로 연결되어 있어 호스트와의 연결이 끊깁니다.",
|
||||
confirmAction: "끄기",
|
||||
},
|
||||
access: {
|
||||
title: "접근",
|
||||
passwordLabel: "비밀번호",
|
||||
passwordNotSetSummary: "설정되지 않음",
|
||||
passwordNotSetHint: "페어링 링크를 가진 누구나 연결할 수 있습니다",
|
||||
passwordSetSummary: "설정됨",
|
||||
passwordSetHint: "원격 연결에 필요",
|
||||
passwordEnvSummary: "환경 변수로 설정됨",
|
||||
passwordEnvHint: "이 호스트의 PASEO_PASSWORD로 제어됩니다",
|
||||
},
|
||||
password: {
|
||||
setTitle: "비밀번호 설정",
|
||||
changeTitle: "비밀번호 변경",
|
||||
removeTitle: "비밀번호 제거",
|
||||
setAction: "비밀번호 설정",
|
||||
setting: "설정 중...",
|
||||
saveAction: "비밀번호 저장",
|
||||
saving: "저장 중...",
|
||||
removeAction: "비밀번호 제거",
|
||||
removing: "제거 중...",
|
||||
show: "비밀번호 표시",
|
||||
hide: "비밀번호 숨기기",
|
||||
setInfo:
|
||||
"다른 원격 기기는 즉시 연결이 해제되며 이 비밀번호가 필요합니다. 이 기기는 연결이 유지됩니다.",
|
||||
changeInfo:
|
||||
"다른 원격 기기는 즉시 연결이 해제되며 새 비밀번호가 필요합니다. 이 기기는 연결이 유지됩니다.",
|
||||
removeWarning:
|
||||
"페어링 링크나 네트워크 접근 권한이 있는 누구나 비밀번호 없이 연결할 수 있게 됩니다.",
|
||||
fields: {
|
||||
current: "현재 비밀번호",
|
||||
new: "새 비밀번호",
|
||||
confirm: "비밀번호 확인",
|
||||
confirmNew: "새 비밀번호 확인",
|
||||
},
|
||||
errors: {
|
||||
currentRequired: "현재 비밀번호를 입력하세요.",
|
||||
currentIncorrect: "현재 비밀번호가 올바르지 않습니다.",
|
||||
tooShort: "8자 이상 입력하세요.",
|
||||
tooLong: "비밀번호는 72바이트 이하여야 합니다.",
|
||||
mismatch: "비밀번호가 일치하지 않습니다.",
|
||||
},
|
||||
toast: {
|
||||
set: "비밀번호가 설정되었습니다.",
|
||||
setDisconnectedOne: "비밀번호가 설정되었습니다. 다른 기기 1대의 연결을 해제했습니다.",
|
||||
setDisconnectedOther:
|
||||
"비밀번호가 설정되었습니다. 다른 기기 {{count}}대의 연결을 해제했습니다.",
|
||||
updated: "비밀번호가 업데이트되었습니다.",
|
||||
updatedDisconnectedOne:
|
||||
"비밀번호가 업데이트되었습니다. 다른 기기 1대의 연결을 해제했습니다.",
|
||||
updatedDisconnectedOther:
|
||||
"비밀번호가 업데이트되었습니다. 다른 기기 {{count}}대의 연결을 해제했습니다.",
|
||||
removed: "비밀번호가 제거되었습니다.",
|
||||
},
|
||||
},
|
||||
connected: {
|
||||
title: "연결된 클라이언트",
|
||||
thisDevice: "이 기기",
|
||||
@@ -2261,6 +2315,8 @@ export const ko: TranslationResources = {
|
||||
hint: "휴대폰의 Paseo로 이 QR 코드를 스캔하거나 아래 링크를 복사하세요.",
|
||||
securityWarning:
|
||||
"이 페어링 링크는 비밀번호처럼 취급하세요. 링크를 가진 사람은 누구나 이 데몬에 접근할 수 있습니다.",
|
||||
passwordProtected:
|
||||
"비밀번호가 필요합니다. 이 코드를 스캔하는 기기는 이 호스트의 비밀번호를 입력해야 합니다.",
|
||||
qrUnavailable: "QR 코드를 사용할 수 없습니다.",
|
||||
qrAccessibility: "페어링 QR 코드",
|
||||
retry: "다시 시도",
|
||||
|
||||
@@ -2057,6 +2057,57 @@ export const ptBR: TranslationResources = {
|
||||
"Este dispositivo está conectado pelo Tailscale e perderá a conexão com o host.",
|
||||
confirmAction: "Desativar",
|
||||
},
|
||||
access: {
|
||||
title: "Acesso",
|
||||
passwordLabel: "Senha",
|
||||
passwordNotSetSummary: "Não definida",
|
||||
passwordNotSetHint: "Qualquer pessoa com um link de pareamento pode conectar",
|
||||
passwordSetSummary: "Definida",
|
||||
passwordSetHint: "Obrigatória para conexões remotas",
|
||||
passwordEnvSummary: "Definida pelo ambiente",
|
||||
passwordEnvHint: "Controlada por PASEO_PASSWORD neste host",
|
||||
},
|
||||
password: {
|
||||
setTitle: "Definir senha",
|
||||
changeTitle: "Alterar senha",
|
||||
removeTitle: "Remover senha",
|
||||
setAction: "Definir senha",
|
||||
setting: "Definindo...",
|
||||
saveAction: "Salvar senha",
|
||||
saving: "Salvando...",
|
||||
removeAction: "Remover senha",
|
||||
removing: "Removendo...",
|
||||
show: "Mostrar senha",
|
||||
hide: "Ocultar senha",
|
||||
setInfo:
|
||||
"Outros dispositivos remotos desconectam imediatamente e precisarão desta senha. Este dispositivo permanece conectado.",
|
||||
changeInfo:
|
||||
"Outros dispositivos remotos desconectam imediatamente e precisarão da nova senha. Este dispositivo permanece conectado.",
|
||||
removeWarning:
|
||||
"Qualquer pessoa com um link de pareamento ou acesso à rede poderá conectar sem senha.",
|
||||
fields: {
|
||||
current: "Senha atual",
|
||||
new: "Nova senha",
|
||||
confirm: "Confirmar senha",
|
||||
confirmNew: "Confirmar nova senha",
|
||||
},
|
||||
errors: {
|
||||
currentRequired: "Digite a senha atual.",
|
||||
currentIncorrect: "A senha atual está incorreta.",
|
||||
tooShort: "Use pelo menos 8 caracteres.",
|
||||
tooLong: "A senha deve ter 72 bytes ou menos.",
|
||||
mismatch: "As senhas não coincidem.",
|
||||
},
|
||||
toast: {
|
||||
set: "Senha definida.",
|
||||
setDisconnectedOne: "Senha definida. 1 outro dispositivo desconectado.",
|
||||
setDisconnectedOther: "Senha definida. {{count}} outros dispositivos desconectados.",
|
||||
updated: "Senha atualizada.",
|
||||
updatedDisconnectedOne: "Senha atualizada. 1 outro dispositivo desconectado.",
|
||||
updatedDisconnectedOther: "Senha atualizada. {{count}} outros dispositivos desconectados.",
|
||||
removed: "Senha removida.",
|
||||
},
|
||||
},
|
||||
connected: {
|
||||
title: "Clientes conectados",
|
||||
thisDevice: "Este dispositivo",
|
||||
@@ -2289,6 +2340,8 @@ export const ptBR: TranslationResources = {
|
||||
hint: "Escaneie este QR code com o Paseo no seu celular ou copie o link abaixo.",
|
||||
securityWarning:
|
||||
"Trate este link de pareamento como uma senha. Qualquer pessoa com o link pode acessar este daemon.",
|
||||
passwordProtected:
|
||||
"Senha obrigatória. Os dispositivos que escanearem este código precisarão inserir a senha deste host.",
|
||||
qrUnavailable: "QR code indisponível.",
|
||||
qrAccessibility: "Código QR de pareamento",
|
||||
retry: "Tentar novamente",
|
||||
|
||||
@@ -2056,6 +2056,57 @@ export const ru: TranslationResources = {
|
||||
confirmMessage: "Это устройство подключено через Tailscale и потеряет соединение с хостом.",
|
||||
confirmAction: "Выключить",
|
||||
},
|
||||
access: {
|
||||
title: "Доступ",
|
||||
passwordLabel: "Пароль",
|
||||
passwordNotSetSummary: "Не задан",
|
||||
passwordNotSetHint: "Подключиться может любой, у кого есть ссылка для сопряжения",
|
||||
passwordSetSummary: "Задан",
|
||||
passwordSetHint: "Требуется для удалённых подключений",
|
||||
passwordEnvSummary: "Задан через окружение",
|
||||
passwordEnvHint: "Управляется переменной PASEO_PASSWORD на этом хосте",
|
||||
},
|
||||
password: {
|
||||
setTitle: "Задать пароль",
|
||||
changeTitle: "Изменить пароль",
|
||||
removeTitle: "Удалить пароль",
|
||||
setAction: "Задать пароль",
|
||||
setting: "Сохранение...",
|
||||
saveAction: "Сохранить пароль",
|
||||
saving: "Сохранение...",
|
||||
removeAction: "Удалить пароль",
|
||||
removing: "Удаление...",
|
||||
show: "Показать пароль",
|
||||
hide: "Скрыть пароль",
|
||||
setInfo:
|
||||
"Другие удалённые устройства немедленно отключатся и потребуют этот пароль. Это устройство останется подключённым.",
|
||||
changeInfo:
|
||||
"Другие удалённые устройства немедленно отключатся и потребуют новый пароль. Это устройство останется подключённым.",
|
||||
removeWarning:
|
||||
"Любой, у кого есть ссылка для сопряжения или доступ к сети, сможет подключаться без пароля.",
|
||||
fields: {
|
||||
current: "Текущий пароль",
|
||||
new: "Новый пароль",
|
||||
confirm: "Подтвердите пароль",
|
||||
confirmNew: "Подтвердите новый пароль",
|
||||
},
|
||||
errors: {
|
||||
currentRequired: "Введите текущий пароль.",
|
||||
currentIncorrect: "Неверный текущий пароль.",
|
||||
tooShort: "Используйте не менее 8 символов.",
|
||||
tooLong: "Пароль должен быть не длиннее 72 байт.",
|
||||
mismatch: "Пароли не совпадают.",
|
||||
},
|
||||
toast: {
|
||||
set: "Пароль задан.",
|
||||
setDisconnectedOne: "Пароль задан. Отключено 1 другое устройство.",
|
||||
setDisconnectedOther: "Пароль задан. Отключено других устройств: {{count}}.",
|
||||
updated: "Пароль обновлён.",
|
||||
updatedDisconnectedOne: "Пароль обновлён. Отключено 1 другое устройство.",
|
||||
updatedDisconnectedOther: "Пароль обновлён. Отключено других устройств: {{count}}.",
|
||||
removed: "Пароль удалён.",
|
||||
},
|
||||
},
|
||||
connected: {
|
||||
title: "Подключённые клиенты",
|
||||
thisDevice: "Это устройство",
|
||||
@@ -2289,6 +2340,8 @@ export const ru: TranslationResources = {
|
||||
hint: "Отсканируйте этот QR-код с помощью Paseo на телефоне или скопируйте ссылку ниже.",
|
||||
securityWarning:
|
||||
"Обращайтесь с этой ссылкой для сопряжения как с паролем. Любой, у кого она есть, может получить доступ к этому демону.",
|
||||
passwordProtected:
|
||||
"Требуется пароль. Устройства, сканирующие этот код, должны будут ввести пароль этого хоста.",
|
||||
qrUnavailable: "QR-код недоступен.",
|
||||
qrAccessibility: "QR-код сопряжения",
|
||||
retry: "Повторить попытку",
|
||||
|
||||
@@ -2001,6 +2001,54 @@ export const zhCN: TranslationResources = {
|
||||
confirmMessage: "此设备通过 Tailscale 连接,关闭后将与主机断开连接。",
|
||||
confirmAction: "关闭",
|
||||
},
|
||||
access: {
|
||||
title: "访问",
|
||||
passwordLabel: "密码",
|
||||
passwordNotSetSummary: "未设置",
|
||||
passwordNotSetHint: "任何拥有配对链接的人都可以连接",
|
||||
passwordSetSummary: "已设置",
|
||||
passwordSetHint: "远程连接必填",
|
||||
passwordEnvSummary: "由环境变量设置",
|
||||
passwordEnvHint: "由此主机上的 PASEO_PASSWORD 控制",
|
||||
},
|
||||
password: {
|
||||
setTitle: "设置密码",
|
||||
changeTitle: "更改密码",
|
||||
removeTitle: "移除密码",
|
||||
setAction: "设置密码",
|
||||
setting: "正在设置...",
|
||||
saveAction: "保存密码",
|
||||
saving: "正在保存...",
|
||||
removeAction: "移除密码",
|
||||
removing: "正在移除...",
|
||||
show: "显示密码",
|
||||
hide: "隐藏密码",
|
||||
setInfo: "其他远程设备会立即断开连接,并需要输入此密码。当前设备保持连接。",
|
||||
changeInfo: "其他远程设备会立即断开连接,并需要输入新密码。当前设备保持连接。",
|
||||
removeWarning: "任何拥有配对链接或网络访问权限的人都可以无需密码连接。",
|
||||
fields: {
|
||||
current: "当前密码",
|
||||
new: "新密码",
|
||||
confirm: "确认密码",
|
||||
confirmNew: "确认新密码",
|
||||
},
|
||||
errors: {
|
||||
currentRequired: "请输入当前密码。",
|
||||
currentIncorrect: "当前密码不正确。",
|
||||
tooShort: "请至少使用 8 个字符。",
|
||||
tooLong: "密码不能超过 72 字节。",
|
||||
mismatch: "两次输入的密码不一致。",
|
||||
},
|
||||
toast: {
|
||||
set: "密码已设置。",
|
||||
setDisconnectedOne: "密码已设置。已断开 1 台其他设备。",
|
||||
setDisconnectedOther: "密码已设置。已断开 {{count}} 台其他设备。",
|
||||
updated: "密码已更新。",
|
||||
updatedDisconnectedOne: "密码已更新。已断开 1 台其他设备。",
|
||||
updatedDisconnectedOther: "密码已更新。已断开 {{count}} 台其他设备。",
|
||||
removed: "密码已移除。",
|
||||
},
|
||||
},
|
||||
connected: {
|
||||
title: "已连接的客户端",
|
||||
thisDevice: "此设备",
|
||||
@@ -2225,6 +2273,7 @@ export const zhCN: TranslationResources = {
|
||||
unavailable: "配对 offer 不可用。",
|
||||
hint: "用手机上的 Paseo 扫描此二维码,或复制下方链接。",
|
||||
securityWarning: "请像保管密码一样保管此配对链接。任何获得此链接的人都可以访问此守护进程。",
|
||||
passwordProtected: "需要密码。扫描此二维码的设备将输入此主机的密码。",
|
||||
qrUnavailable: "二维码不可用。",
|
||||
qrAccessibility: "配对二维码",
|
||||
retry: "重试",
|
||||
|
||||
@@ -5918,4 +5918,59 @@ describe("HostRuntimeStore initial connection hint bootstrap", () => {
|
||||
await store.removeHost("srv_rotated");
|
||||
expect(resetHosts).toEqual(["srv_rotated", "srv_rotated"]);
|
||||
});
|
||||
|
||||
it("uses make-before-break when setHostPassword updates an online host so status never flashes offline", async () => {
|
||||
const serverId = "srv_mbb_password";
|
||||
const firstClient = makeConnectedProbeClient(5);
|
||||
const secondClient = new FakeDaemonClient();
|
||||
const connectSecond = new Deferred<void>();
|
||||
secondClient.connect = async () => {
|
||||
await connectSecond.promise;
|
||||
secondClient.setConnectionState({ status: "connected" });
|
||||
};
|
||||
let createCount = 0;
|
||||
|
||||
const store = new HostRuntimeStore({
|
||||
storage: createMemoryHostRuntimeStorage(),
|
||||
deps: {
|
||||
createClient: () => {
|
||||
createCount += 1;
|
||||
return secondClient as unknown as DaemonClient;
|
||||
},
|
||||
connectToDaemon: async () => ({
|
||||
client: firstClient as unknown as DaemonClient,
|
||||
serverId,
|
||||
hostname: null,
|
||||
}),
|
||||
getClientId: async () => "cid_mbb_password",
|
||||
},
|
||||
});
|
||||
|
||||
await store.upsertDirectConnection({ serverId, endpoint: "127.0.0.1:6767" });
|
||||
await waitForHostOnline(store, serverId);
|
||||
|
||||
const observedStatuses: string[] = [];
|
||||
const unsubscribe = store.subscribe(serverId, () => {
|
||||
const status = store.getSnapshot(serverId)?.connectionStatus;
|
||||
if (status) observedStatuses.push(status);
|
||||
});
|
||||
|
||||
const updatePromise = store.setHostPassword(serverId, "new-secret-123");
|
||||
// While replacement client is still connecting, host must stay online with zero flash.
|
||||
await vi.waitFor(() => expect(createCount).toBe(1));
|
||||
expect(store.getSnapshot(serverId)?.connectionStatus).toBe("online");
|
||||
expect(observedStatuses.every((status) => status === "online")).toBe(true);
|
||||
|
||||
connectSecond.resolve();
|
||||
await updatePromise;
|
||||
unsubscribe();
|
||||
|
||||
expect(store.getSnapshot(serverId)?.connectionStatus).toBe("online");
|
||||
expect(observedStatuses.every((status) => status === "online")).toBe(true);
|
||||
expect(store.getHosts().find((item) => item.serverId === serverId)?.password).toBe(
|
||||
"new-secret-123",
|
||||
);
|
||||
|
||||
store.syncHosts([]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -879,7 +879,10 @@ export class HostRuntimeController {
|
||||
passwordChanged)
|
||||
) {
|
||||
this.connectionLastProbedAt.delete(activeConnectionId);
|
||||
await this.switchToConnection({ connectionId: activeConnectionId });
|
||||
await this.switchToConnection({
|
||||
connectionId: activeConnectionId,
|
||||
keepActiveUntilConnected: passwordChanged && this.snapshot.connectionStatus === "online",
|
||||
});
|
||||
}
|
||||
if (passwordChanged) this.connectionLastProbedAt.clear();
|
||||
if (passwordChanged) await this.probeCycleInFlight;
|
||||
@@ -3340,6 +3343,7 @@ export interface HostMutations {
|
||||
}) => Promise<{ profile: HostProfile; serverId: string; hostname: string | null }>;
|
||||
beginLinkPairing: () => LinkPairing;
|
||||
renameHost: (serverId: string, label: string) => Promise<void>;
|
||||
setHostPassword: (serverId: string, password: string) => Promise<void>;
|
||||
setHostColor: (serverId: string, color: HostColor) => Promise<void>;
|
||||
setHostIcon: (serverId: string, icon: HostIcon | null) => Promise<void>;
|
||||
setHostBadgeDisplay: (serverId: string, badgeDisplay: HostBadgeDisplay) => Promise<void>;
|
||||
@@ -3356,6 +3360,7 @@ export function useHostMutations(): HostMutations {
|
||||
probeAndUpsertRemoteSshConnection: (input) => store.probeAndUpsertRemoteSshConnection(input),
|
||||
beginLinkPairing: () => store.beginLinkPairing(),
|
||||
renameHost: (serverId, label) => store.renameHost(serverId, label),
|
||||
setHostPassword: (serverId, password) => store.setHostPassword(serverId, password),
|
||||
setHostColor: (serverId, color) => store.setHostColor(serverId, color),
|
||||
setHostIcon: (serverId, icon) => store.setHostIcon(serverId, icon),
|
||||
setHostBadgeDisplay: (serverId, badgeDisplay) =>
|
||||
|
||||
@@ -237,7 +237,12 @@ export function HostDevicesPage({ serverId }: { serverId: string }) {
|
||||
return <HostNotFound />;
|
||||
}
|
||||
|
||||
return <ConnectedDevicesView serverId={serverId} />;
|
||||
return (
|
||||
<View>
|
||||
<HostConnectionError serverId={serverId} />
|
||||
<ConnectedDevicesView serverId={serverId} />
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
export function HostToolsPage({ serverId }: { serverId: string }) {
|
||||
|
||||
@@ -300,6 +300,7 @@ function decodeSegment(value: string): string {
|
||||
function useSyncWorkspaceActiveBrowser(input: {
|
||||
workspaceLayout: WorkspaceLayout | null;
|
||||
isRouteFocused: boolean;
|
||||
serverId: string;
|
||||
workspaceId: string;
|
||||
}) {
|
||||
const focusedBrowserId = useMemo(
|
||||
@@ -308,14 +309,15 @@ function useSyncWorkspaceActiveBrowser(input: {
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (!getIsElectron()) {
|
||||
if (!getIsElectron() || !input.serverId || !input.workspaceId) {
|
||||
return;
|
||||
}
|
||||
void getDesktopHost()?.browser?.setWorkspaceActiveBrowser?.({
|
||||
serverId: input.serverId,
|
||||
workspaceId: input.workspaceId,
|
||||
browserId: focusedBrowserId,
|
||||
});
|
||||
}, [focusedBrowserId, input.workspaceId]);
|
||||
}, [focusedBrowserId, input.serverId, input.workspaceId]);
|
||||
}
|
||||
|
||||
function WorkspaceDocumentTitleEffect({
|
||||
@@ -1330,6 +1332,7 @@ function WorkspaceScreenContent({
|
||||
useSyncWorkspaceActiveBrowser({
|
||||
workspaceLayout,
|
||||
isRouteFocused,
|
||||
serverId: normalizedServerId,
|
||||
workspaceId: normalizedWorkspaceId,
|
||||
});
|
||||
const openWorkspaceTabInBackground = useCallback(
|
||||
|
||||
@@ -920,3 +920,56 @@ describe("setAgentOverlay", () => {
|
||||
).toBe("low");
|
||||
});
|
||||
});
|
||||
|
||||
describe("updateSessionServerInfo", () => {
|
||||
it("preserves and updates password status, auth mode, and permissions", () => {
|
||||
const store = useSessionStore.getState();
|
||||
initializeTestSession();
|
||||
|
||||
store.updateSessionServerInfo("test-server", {
|
||||
serverId: "srv-1",
|
||||
hostname: "devbox",
|
||||
version: "0.19.0",
|
||||
passwordConfigured: false,
|
||||
passwordManagedByEnv: false,
|
||||
localCredentialAuth: true,
|
||||
permissions: ["daemon.manage", "access.manage"],
|
||||
features: { daemonPasswordManagement: true },
|
||||
});
|
||||
|
||||
const first = useSessionStore.getState().sessions["test-server"]?.serverInfo;
|
||||
expect(first?.passwordConfigured).toBe(false);
|
||||
expect(first?.passwordManagedByEnv).toBe(false);
|
||||
expect(first?.localCredentialAuth).toBe(true);
|
||||
expect(first?.permissions).toEqual(["daemon.manage", "access.manage"]);
|
||||
|
||||
// Content-equal update keeps session identity stable.
|
||||
const beforeSame = getTestSessionReferences();
|
||||
store.updateSessionServerInfo("test-server", {
|
||||
serverId: "srv-1",
|
||||
hostname: "devbox",
|
||||
version: "0.19.0",
|
||||
passwordConfigured: false,
|
||||
passwordManagedByEnv: false,
|
||||
localCredentialAuth: true,
|
||||
permissions: ["daemon.manage", "access.manage"],
|
||||
features: { daemonPasswordManagement: true },
|
||||
});
|
||||
expect(getTestSessionReferences().session).toBe(beforeSame.session);
|
||||
|
||||
// Live password change propagates immediately.
|
||||
store.updateSessionServerInfo("test-server", {
|
||||
serverId: "srv-1",
|
||||
hostname: "devbox",
|
||||
version: "0.19.0",
|
||||
passwordConfigured: true,
|
||||
passwordManagedByEnv: false,
|
||||
localCredentialAuth: true,
|
||||
permissions: ["daemon.manage", "access.manage"],
|
||||
features: { daemonPasswordManagement: true },
|
||||
});
|
||||
const updated = useSessionStore.getState().sessions["test-server"]?.serverInfo;
|
||||
expect(updated?.passwordConfigured).toBe(true);
|
||||
expect(updated?.localCredentialAuth).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -402,6 +402,9 @@ export interface DaemonServerInfo {
|
||||
version: string | null;
|
||||
machineKind?: string | null;
|
||||
desktopManaged?: boolean;
|
||||
passwordConfigured?: boolean;
|
||||
passwordManagedByEnv?: boolean;
|
||||
localCredentialAuth?: boolean;
|
||||
permissions?: ServerInfoStatusPayload["permissions"];
|
||||
capabilities?: ServerCapabilities;
|
||||
features?: ServerInfoStatusPayload["features"];
|
||||
@@ -416,6 +419,15 @@ export function toDaemonServerInfo(serverInfo: ServerInfoStatusPayload): DaemonS
|
||||
...(serverInfo.desktopManaged !== undefined
|
||||
? { desktopManaged: serverInfo.desktopManaged }
|
||||
: {}),
|
||||
...(serverInfo.passwordConfigured !== undefined
|
||||
? { passwordConfigured: serverInfo.passwordConfigured }
|
||||
: {}),
|
||||
...(serverInfo.passwordManagedByEnv !== undefined
|
||||
? { passwordManagedByEnv: serverInfo.passwordManagedByEnv }
|
||||
: {}),
|
||||
...(serverInfo.localCredentialAuth !== undefined
|
||||
? { localCredentialAuth: serverInfo.localCredentialAuth }
|
||||
: {}),
|
||||
...(serverInfo.permissions ? { permissions: serverInfo.permissions } : {}),
|
||||
...(serverInfo.capabilities ? { capabilities: serverInfo.capabilities } : {}),
|
||||
...(serverInfo.features ? { features: serverInfo.features } : {}),
|
||||
@@ -939,36 +951,62 @@ function areServerInfoFeaturesEqual(
|
||||
return JSON.stringify(current ?? null) === JSON.stringify(next ?? null);
|
||||
}
|
||||
|
||||
function areServerInfoPermissionsEqual(
|
||||
left: ServerInfoStatusPayload["permissions"] | undefined,
|
||||
right: ServerInfoStatusPayload["permissions"] | undefined,
|
||||
): boolean {
|
||||
if (left === right) return true;
|
||||
if (!left || !right || left.length !== right.length) return false;
|
||||
return left.every((permission, index) => permission === right[index]);
|
||||
}
|
||||
|
||||
function areServerInfoAuthFieldsEqual(
|
||||
currentServerInfo: DaemonServerInfo,
|
||||
input: {
|
||||
nextPasswordConfigured: boolean | undefined;
|
||||
nextPasswordManagedByEnv: boolean | undefined;
|
||||
nextLocalCredentialAuth: boolean | undefined;
|
||||
nextPermissions: ServerInfoStatusPayload["permissions"] | undefined;
|
||||
},
|
||||
): boolean {
|
||||
return (
|
||||
currentServerInfo.passwordConfigured === input.nextPasswordConfigured &&
|
||||
currentServerInfo.passwordManagedByEnv === input.nextPasswordManagedByEnv &&
|
||||
currentServerInfo.localCredentialAuth === input.nextLocalCredentialAuth &&
|
||||
areServerInfoPermissionsEqual(currentServerInfo.permissions, input.nextPermissions)
|
||||
);
|
||||
}
|
||||
|
||||
function isSessionServerInfoUnchanged(input: {
|
||||
currentServerInfo: SessionState["serverInfo"] | undefined;
|
||||
nextHostname: string | null;
|
||||
nextVersion: string | null;
|
||||
nextMachineKind: string | null;
|
||||
nextDesktopManaged: boolean | undefined;
|
||||
nextPasswordConfigured: boolean | undefined;
|
||||
nextPasswordManagedByEnv: boolean | undefined;
|
||||
nextLocalCredentialAuth: boolean | undefined;
|
||||
nextPermissions: ServerInfoStatusPayload["permissions"] | undefined;
|
||||
nextCapabilities: ServerCapabilities | undefined;
|
||||
nextFeatures: ServerInfoStatusPayload["features"] | undefined;
|
||||
nextServerId: string;
|
||||
}): boolean {
|
||||
const {
|
||||
currentServerInfo,
|
||||
nextHostname,
|
||||
nextVersion,
|
||||
nextMachineKind,
|
||||
nextDesktopManaged,
|
||||
nextCapabilities,
|
||||
nextFeatures,
|
||||
} = input;
|
||||
const prevHostname = currentServerInfo?.hostname?.trim() || null;
|
||||
const prevVersion = currentServerInfo?.version?.trim() || null;
|
||||
const prevMachineKind = currentServerInfo?.machineKind?.trim() || null;
|
||||
const { currentServerInfo } = input;
|
||||
if (!currentServerInfo) {
|
||||
return false;
|
||||
}
|
||||
const prevHostname = currentServerInfo.hostname?.trim() || null;
|
||||
const prevVersion = currentServerInfo.version?.trim() || null;
|
||||
const prevMachineKind = currentServerInfo.machineKind?.trim() || null;
|
||||
return (
|
||||
currentServerInfo?.serverId === input.nextServerId &&
|
||||
prevHostname === nextHostname &&
|
||||
prevVersion === nextVersion &&
|
||||
prevMachineKind === nextMachineKind &&
|
||||
currentServerInfo?.desktopManaged === nextDesktopManaged &&
|
||||
areServerCapabilitiesEqual(currentServerInfo?.capabilities, nextCapabilities) &&
|
||||
areServerInfoFeaturesEqual(currentServerInfo?.features, nextFeatures)
|
||||
currentServerInfo.serverId === input.nextServerId &&
|
||||
prevHostname === input.nextHostname &&
|
||||
prevVersion === input.nextVersion &&
|
||||
prevMachineKind === input.nextMachineKind &&
|
||||
currentServerInfo.desktopManaged === input.nextDesktopManaged &&
|
||||
areServerInfoAuthFieldsEqual(currentServerInfo, input) &&
|
||||
areServerCapabilitiesEqual(currentServerInfo.capabilities, input.nextCapabilities) &&
|
||||
areServerInfoFeaturesEqual(currentServerInfo.features, input.nextFeatures)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1106,6 +1144,10 @@ export const useSessionStore = create<SessionStore>()(
|
||||
const nextVersion = info.version?.trim() || null;
|
||||
const nextMachineKind = info.machineKind?.trim() || null;
|
||||
const nextDesktopManaged = info.desktopManaged;
|
||||
const nextPasswordConfigured = info.passwordConfigured;
|
||||
const nextPasswordManagedByEnv = info.passwordManagedByEnv;
|
||||
const nextLocalCredentialAuth = info.localCredentialAuth;
|
||||
const nextPermissions = info.permissions;
|
||||
const nextCapabilities = info.capabilities;
|
||||
const nextFeatures = info.features;
|
||||
|
||||
@@ -1116,6 +1158,10 @@ export const useSessionStore = create<SessionStore>()(
|
||||
nextVersion,
|
||||
nextMachineKind,
|
||||
nextDesktopManaged,
|
||||
nextPasswordConfigured,
|
||||
nextPasswordManagedByEnv,
|
||||
nextLocalCredentialAuth,
|
||||
nextPermissions,
|
||||
nextCapabilities,
|
||||
nextFeatures,
|
||||
nextServerId: info.serverId,
|
||||
@@ -1138,6 +1184,16 @@ export const useSessionStore = create<SessionStore>()(
|
||||
...(nextDesktopManaged !== undefined
|
||||
? { desktopManaged: nextDesktopManaged }
|
||||
: {}),
|
||||
...(nextPasswordConfigured !== undefined
|
||||
? { passwordConfigured: nextPasswordConfigured }
|
||||
: {}),
|
||||
...(nextPasswordManagedByEnv !== undefined
|
||||
? { passwordManagedByEnv: nextPasswordManagedByEnv }
|
||||
: {}),
|
||||
...(nextLocalCredentialAuth !== undefined
|
||||
? { localCredentialAuth: nextLocalCredentialAuth }
|
||||
: {}),
|
||||
...(nextPermissions ? { permissions: nextPermissions } : {}),
|
||||
...(nextCapabilities ? { capabilities: nextCapabilities } : {}),
|
||||
...(nextFeatures ? { features: nextFeatures } : {}),
|
||||
},
|
||||
|
||||
@@ -50,7 +50,7 @@ export function addSendOptions(cmd: Command): Command {
|
||||
.addOption(
|
||||
new Option(
|
||||
"--behavior <behavior>",
|
||||
"Leave out unless the message cannot wait. From an agent (PASEO_AGENT_ID set): queue (default) waits for the running turn to end, steer joins it, interrupt replaces it. From a person: interrupt (default), steer, or queue",
|
||||
"From an agent (PASEO_AGENT_ID set): steer (default) joins the running turn or waits until it ends if the provider cannot steer, queue waits for the running turn to end, interrupt replaces it. From a person: interrupt (default), steer, or queue",
|
||||
).choices(["queue", "steer", "interrupt"]),
|
||||
)
|
||||
.option("--no-wait", "Return immediately without waiting for completion");
|
||||
|
||||
@@ -25,7 +25,10 @@ export function createDaemonCommand(): Command {
|
||||
daemon.addCommand(command);
|
||||
addJsonOption(
|
||||
addLocalDaemonOptions(
|
||||
daemon.command("set-password").description("Save a hashed daemon password (local operation)"),
|
||||
daemon
|
||||
.command("set-password")
|
||||
.description("Set, change, or remove the daemon password")
|
||||
.option("--remove", "Remove the daemon password"),
|
||||
),
|
||||
).action(withOutput(runSetPasswordCommand));
|
||||
return daemon;
|
||||
|
||||
@@ -0,0 +1,185 @@
|
||||
import { afterEach, describe, expect, test } from "vitest";
|
||||
import { mkdtemp, rm, writeFile } from "node:fs/promises";
|
||||
import { hostname, tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import type { Command } from "commander";
|
||||
import { readPersistedConfig } from "@getpaseo/server/configuration";
|
||||
import { readDaemonInstance } from "@getpaseo/server/daemon-control";
|
||||
import { isBearerTokenValidAsync } from "@getpaseo/server/auth";
|
||||
import {
|
||||
persistDaemonPasswordHash,
|
||||
runSetPasswordCommand,
|
||||
type PromptPassword,
|
||||
} from "./set-password.js";
|
||||
|
||||
function promptSequence(values: string[]): PromptPassword {
|
||||
return async () => {
|
||||
const value = values.shift();
|
||||
if (value === undefined) {
|
||||
throw new Error("prompt called too many times");
|
||||
}
|
||||
return value;
|
||||
};
|
||||
}
|
||||
|
||||
describe("daemon set-password command", () => {
|
||||
const homes: string[] = [];
|
||||
|
||||
afterEach(async () => {
|
||||
while (homes.length > 0) {
|
||||
await rm(homes.pop()!, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("sets and removes password offline when daemon is stopped without telling user to restart", async () => {
|
||||
const home = await mkdtemp(path.join(tmpdir(), "paseo-cli-pw-"));
|
||||
homes.push(home);
|
||||
|
||||
const setRes = await runSetPasswordCommand(
|
||||
{
|
||||
home,
|
||||
daemonTarget: { kind: "instance", home },
|
||||
promptPassword: promptSequence(["offline-secret", "offline-secret"]),
|
||||
},
|
||||
{} as Command,
|
||||
);
|
||||
expect(setRes.data.action).toBe("password_set");
|
||||
expect(setRes.data.appliedLive).toBe(false);
|
||||
expect(setRes.data.message).not.toMatch(/Restart the daemon/i);
|
||||
const hash = readPersistedConfig(home).daemon?.auth?.password;
|
||||
expect(hash).toBeTruthy();
|
||||
expect(await isBearerTokenValidAsync({ password: hash, token: "offline-secret" })).toBe(true);
|
||||
|
||||
const removeRes = await runSetPasswordCommand(
|
||||
{
|
||||
home,
|
||||
remove: true,
|
||||
daemonTarget: { kind: "instance", home },
|
||||
},
|
||||
{} as Command,
|
||||
);
|
||||
expect(removeRes.data.action).toBe("password_removed");
|
||||
expect(removeRes.data.appliedLive).toBe(false);
|
||||
expect(removeRes.data.message).not.toMatch(/Restart the daemon/i);
|
||||
expect(readPersistedConfig(home).daemon?.auth?.password).toBeUndefined();
|
||||
});
|
||||
|
||||
test("rejects passwords over 72 UTF-8 bytes", async () => {
|
||||
const home = await mkdtemp(path.join(tmpdir(), "paseo-cli-pw-len-"));
|
||||
homes.push(home);
|
||||
|
||||
const tooLong = "🔐".repeat(19);
|
||||
await expect(
|
||||
runSetPasswordCommand(
|
||||
{
|
||||
home,
|
||||
daemonTarget: { kind: "instance", home },
|
||||
promptPassword: promptSequence([tooLong, tooLong]),
|
||||
},
|
||||
{} as Command,
|
||||
),
|
||||
).rejects.toMatchObject({ code: "INVALID_PASSWORD" });
|
||||
});
|
||||
|
||||
test("applies live via RPC when a daemon client is reachable", async () => {
|
||||
const home = await mkdtemp(path.join(tmpdir(), "paseo-cli-pw-live-"));
|
||||
homes.push(home);
|
||||
const calls: Array<{ password: string | null }> = [];
|
||||
let closed = false;
|
||||
|
||||
const fakeClient = {
|
||||
getLastServerInfoMessage: () => ({
|
||||
features: { daemonPasswordManagement: true },
|
||||
}),
|
||||
setDaemonPassword: async (input: { password: string | null }) => {
|
||||
calls.push(input);
|
||||
return {
|
||||
requestId: "req-1",
|
||||
passwordConfigured: input.password !== null,
|
||||
disconnectedSessionCount: input.password !== null ? 2 : 0,
|
||||
};
|
||||
},
|
||||
close: async () => {
|
||||
closed = true;
|
||||
},
|
||||
};
|
||||
|
||||
const setRes = await runSetPasswordCommand(
|
||||
{
|
||||
home,
|
||||
daemonTarget: { kind: "instance", home },
|
||||
promptPassword: promptSequence(["live-secret", "live-secret"]),
|
||||
connectLiveClient: async () => fakeClient,
|
||||
},
|
||||
{} as Command,
|
||||
);
|
||||
expect(setRes.data.action).toBe("password_set");
|
||||
expect(setRes.data.appliedLive).toBe(true);
|
||||
expect(setRes.data.disconnectedSessionCount).toBe(2);
|
||||
expect(setRes.data.message).toContain("Disconnected 2 other remote sessions.");
|
||||
expect(closed).toBe(true);
|
||||
|
||||
const removeRes = await runSetPasswordCommand(
|
||||
{
|
||||
home,
|
||||
remove: true,
|
||||
daemonTarget: { kind: "instance", home },
|
||||
connectLiveClient: async () => fakeClient,
|
||||
},
|
||||
{} as Command,
|
||||
);
|
||||
expect(removeRes.data.action).toBe("password_removed");
|
||||
expect(removeRes.data.appliedLive).toBe(true);
|
||||
expect(calls).toEqual([{ password: "live-secret" }, { password: null }]);
|
||||
});
|
||||
|
||||
test("persistDaemonPasswordHash removes empty auth object cleanly", async () => {
|
||||
const home = await mkdtemp(path.join(tmpdir(), "paseo-cli-pw-persist-"));
|
||||
homes.push(home);
|
||||
|
||||
const validHash = "$2b$12$OLxyuuP9uLK30Uzc4wQX0O6liuU/Q1t5P2b0Ebf36mULvpVK3DRZW";
|
||||
persistDaemonPasswordHash(home, validHash);
|
||||
expect(readPersistedConfig(home).daemon?.auth?.password).toBe(validHash);
|
||||
|
||||
persistDaemonPasswordHash(home, null);
|
||||
expect(readPersistedConfig(home).daemon?.auth).toBeUndefined();
|
||||
});
|
||||
|
||||
test("does not silently write offline config when a daemon process is running but unreachable", async () => {
|
||||
const home = await mkdtemp(path.join(tmpdir(), "paseo-cli-pw-running-fail-"));
|
||||
homes.push(home);
|
||||
|
||||
// Write a valid live PID lock (current process PID) pointing to an unreachable loopback port.
|
||||
await writeFile(
|
||||
path.join(home, "paseo.pid"),
|
||||
JSON.stringify({
|
||||
pid: process.pid,
|
||||
startedAt: new Date().toISOString(),
|
||||
hostname: hostname(),
|
||||
uid: typeof process.getuid === "function" ? process.getuid() : 0,
|
||||
listen: "127.0.0.1:1",
|
||||
}),
|
||||
);
|
||||
expect(await readDaemonInstance(home)).toMatchObject({
|
||||
pid: process.pid,
|
||||
listen: "127.0.0.1:1",
|
||||
});
|
||||
|
||||
await expect(
|
||||
runSetPasswordCommand(
|
||||
{
|
||||
home,
|
||||
daemonTarget: { kind: "instance", home },
|
||||
promptPassword: promptSequence(["never-written", "never-written"]),
|
||||
},
|
||||
{} as Command,
|
||||
),
|
||||
).rejects.toMatchObject({
|
||||
code: "DAEMON_UNREACHABLE",
|
||||
message: expect.stringContaining("Cannot connect to daemon"),
|
||||
});
|
||||
|
||||
// Persisted config must NOT have been silently mutated on connection failure.
|
||||
expect(readPersistedConfig(home).daemon?.auth?.password).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -1,13 +1,15 @@
|
||||
import path from "node:path";
|
||||
import type { Command } from "commander";
|
||||
import { isCancel, password as passwordPrompt } from "@clack/prompts";
|
||||
import { hashDaemonPassword } from "@getpaseo/server/auth";
|
||||
import { DaemonRpcError } from "@getpaseo/client";
|
||||
import { DAEMON_PASSWORD_MAX_UTF8_BYTES, hashDaemonPassword } from "@getpaseo/server/auth";
|
||||
import {
|
||||
readPersistedConfig,
|
||||
savePersistedConfig,
|
||||
type PersistedConfig,
|
||||
} from "@getpaseo/server/configuration";
|
||||
import { resolvePaseoHome } from "@getpaseo/server/daemon-control";
|
||||
import { readDaemonInstance, resolvePaseoHome } from "@getpaseo/server/daemon-control";
|
||||
import { connectToDaemon, resolveDaemonPassword } from "../../utils/client.js";
|
||||
import type {
|
||||
CommandError,
|
||||
CommandOptions,
|
||||
@@ -18,15 +20,30 @@ import type {
|
||||
|
||||
const CONFIG_FILENAME = "config.json";
|
||||
|
||||
interface SetPasswordResult {
|
||||
action: "password_set";
|
||||
export interface SetPasswordResult {
|
||||
action: "password_set" | "password_removed";
|
||||
appliedLive: boolean;
|
||||
passwordConfigured: boolean;
|
||||
disconnectedSessionCount: number;
|
||||
configPath: string;
|
||||
restartCommand: string;
|
||||
restartCommand?: string;
|
||||
message: string;
|
||||
}
|
||||
|
||||
export type PromptPassword = (message: string) => Promise<string | symbol>;
|
||||
|
||||
export interface LivePasswordClient {
|
||||
getLastServerInfoMessage(): {
|
||||
localCredentialAuth?: boolean;
|
||||
features?: { daemonPasswordManagement?: boolean };
|
||||
} | null;
|
||||
setDaemonPassword(input: {
|
||||
password: string | null;
|
||||
currentPassword?: string;
|
||||
}): Promise<{ passwordConfigured: boolean; disconnectedSessionCount: number }>;
|
||||
close(): Promise<void>;
|
||||
}
|
||||
|
||||
export interface SetPasswordOptions {
|
||||
home?: string;
|
||||
promptPassword?: PromptPassword;
|
||||
@@ -37,16 +54,14 @@ const setPasswordResultSchema: OutputSchema<SetPasswordResult> = {
|
||||
columns: [
|
||||
{ header: "STATUS", field: "action", color: () => "green" },
|
||||
{ header: "CONFIG", field: "configPath" },
|
||||
{ header: "RESTART", field: "restartCommand" },
|
||||
],
|
||||
renderHuman: (result, options: OutputOptions) => {
|
||||
const data = result.data as SetPasswordResult;
|
||||
const rows = [
|
||||
`Password written to ${data.configPath}`,
|
||||
"Restart the daemon for the change to take effect.",
|
||||
`Run: ${data.restartCommand}`,
|
||||
];
|
||||
if (options.format === "table") {
|
||||
const rows = [data.message];
|
||||
if (data.restartCommand && !data.appliedLive) {
|
||||
rows.push(`Run: ${data.restartCommand}`);
|
||||
}
|
||||
return rows.join("\n");
|
||||
}
|
||||
return data.message;
|
||||
@@ -68,6 +83,19 @@ function terminalPasswordPrompt(): PromptPassword {
|
||||
return (message) => passwordPrompt({ message });
|
||||
}
|
||||
|
||||
function validatePasswordBytes(password: string): void {
|
||||
const bytes = Buffer.byteLength(password, "utf8");
|
||||
if (bytes < 1) {
|
||||
throw createCommandError("PASSWORD_REQUIRED", "Password cannot be empty");
|
||||
}
|
||||
if (bytes > DAEMON_PASSWORD_MAX_UTF8_BYTES) {
|
||||
throw createCommandError(
|
||||
"INVALID_PASSWORD",
|
||||
`Password must be ${DAEMON_PASSWORD_MAX_UTF8_BYTES} bytes or fewer`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async function promptForPassword(promptPassword: PromptPassword): Promise<string> {
|
||||
const first = await promptPassword("New daemon password");
|
||||
if (isCancel(first)) {
|
||||
@@ -76,6 +104,7 @@ async function promptForPassword(promptPassword: PromptPassword): Promise<string
|
||||
if (typeof first !== "string" || first.length === 0) {
|
||||
throw createCommandError("PASSWORD_REQUIRED", "Password cannot be empty");
|
||||
}
|
||||
validatePasswordBytes(first);
|
||||
|
||||
const second = await promptPassword("Confirm daemon password");
|
||||
if (isCancel(second)) {
|
||||
@@ -88,47 +117,197 @@ async function promptForPassword(promptPassword: PromptPassword): Promise<string
|
||||
return first;
|
||||
}
|
||||
|
||||
export async function setDaemonPasswordInConfig(
|
||||
newPassword: string,
|
||||
options: SetPasswordOptions = {},
|
||||
): Promise<SetPasswordResult> {
|
||||
const paseoHome = resolvePaseoHome({ PASEO_HOME: options.home });
|
||||
export function persistDaemonPasswordHash(paseoHome: string, hash: string | null): string {
|
||||
const configPath = path.join(paseoHome, CONFIG_FILENAME);
|
||||
const persisted = readPersistedConfig(paseoHome);
|
||||
const nextConfig: PersistedConfig = {
|
||||
...persisted,
|
||||
daemon: {
|
||||
...persisted.daemon,
|
||||
auth: {
|
||||
...persisted.daemon?.auth,
|
||||
password: hashDaemonPassword(newPassword),
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const nextDaemon: NonNullable<PersistedConfig["daemon"]> = { ...persisted.daemon };
|
||||
if (hash !== null) {
|
||||
nextDaemon.auth = { ...nextDaemon.auth, password: hash };
|
||||
} else if (nextDaemon.auth) {
|
||||
const { password: _removed, ...restAuth } = nextDaemon.auth;
|
||||
if (Object.keys(restAuth).length > 0) {
|
||||
nextDaemon.auth = restAuth;
|
||||
} else {
|
||||
delete nextDaemon.auth;
|
||||
}
|
||||
}
|
||||
const { daemon: _prevDaemon, ...restPersisted } = persisted;
|
||||
const nextConfig: PersistedConfig =
|
||||
Object.keys(nextDaemon).length > 0
|
||||
? { ...restPersisted, daemon: nextDaemon }
|
||||
: (restPersisted as PersistedConfig);
|
||||
savePersistedConfig(paseoHome, nextConfig);
|
||||
return configPath;
|
||||
}
|
||||
|
||||
export async function setDaemonPasswordInConfig(
|
||||
newPassword: string | null,
|
||||
options: SetPasswordOptions & { daemonRunning?: boolean } = {},
|
||||
): Promise<SetPasswordResult> {
|
||||
if (newPassword !== null) {
|
||||
validatePasswordBytes(newPassword);
|
||||
}
|
||||
const paseoHome = resolvePaseoHome({ PASEO_HOME: options.home });
|
||||
const configPath = persistDaemonPasswordHash(
|
||||
paseoHome,
|
||||
newPassword === null ? null : hashDaemonPassword(newPassword),
|
||||
);
|
||||
const restartCommand = `paseo daemon restart --home ${JSON.stringify(paseoHome)}`;
|
||||
const isRemove = newPassword === null;
|
||||
const baseLine = isRemove
|
||||
? `Password removed from ${configPath}`
|
||||
: `Password written to ${configPath}`;
|
||||
const message = options.daemonRunning
|
||||
? `${baseLine}\nRestart the daemon for the change to take effect.\nRun: ${restartCommand}`
|
||||
: baseLine;
|
||||
|
||||
return {
|
||||
action: "password_set",
|
||||
action: isRemove ? "password_removed" : "password_set",
|
||||
appliedLive: false,
|
||||
passwordConfigured: !isRemove,
|
||||
disconnectedSessionCount: 0,
|
||||
configPath,
|
||||
restartCommand: `paseo daemon restart --home ${JSON.stringify(paseoHome)}`,
|
||||
message: `Password written to ${configPath}\nRestart the daemon for the change to take effect.\nRun: paseo daemon restart --home ${JSON.stringify(paseoHome)}`,
|
||||
restartCommand,
|
||||
message,
|
||||
};
|
||||
}
|
||||
|
||||
function formatLiveMessage(isRemove: boolean, disconnectedSessionCount: number): string {
|
||||
if (isRemove) {
|
||||
return "Daemon password removed.";
|
||||
}
|
||||
if (disconnectedSessionCount === 1) {
|
||||
return "Daemon password updated.\nDisconnected 1 other remote session.";
|
||||
}
|
||||
if (disconnectedSessionCount > 1) {
|
||||
return `Daemon password updated.\nDisconnected ${disconnectedSessionCount} other remote sessions.`;
|
||||
}
|
||||
return "Daemon password updated.";
|
||||
}
|
||||
|
||||
interface LivePasswordConnection {
|
||||
client: LivePasswordClient;
|
||||
connectedPassword?: string;
|
||||
}
|
||||
|
||||
async function tryConnectLiveClient(
|
||||
options: CommandOptions,
|
||||
): Promise<LivePasswordConnection | null> {
|
||||
if (typeof options.connectLiveClient === "function") {
|
||||
const client = await (options.connectLiveClient as () => Promise<LivePasswordClient | null>)();
|
||||
return client ? { client } : null;
|
||||
}
|
||||
const target = options.daemonTarget;
|
||||
if (target.kind === "instance") {
|
||||
const instance = await readDaemonInstance(target.home);
|
||||
if (!instance) {
|
||||
return null;
|
||||
}
|
||||
const client = await connectToDaemon({
|
||||
target,
|
||||
instance,
|
||||
timeout: 2_000,
|
||||
preferLocalCredential: true,
|
||||
});
|
||||
return {
|
||||
client,
|
||||
connectedPassword: instance.listen ? resolveDaemonPassword(instance.listen) : undefined,
|
||||
};
|
||||
}
|
||||
const client = await connectToDaemon({
|
||||
target,
|
||||
timeout: 2_000,
|
||||
});
|
||||
return {
|
||||
client,
|
||||
connectedPassword: resolveDaemonPassword(target.host),
|
||||
};
|
||||
}
|
||||
|
||||
function toPasswordRpcCommandError(error: DaemonRpcError): CommandError {
|
||||
if (error.code === "managed_by_env") {
|
||||
return createCommandError(
|
||||
"PASSWORD_MANAGED_BY_ENV",
|
||||
"Daemon password is controlled by PASEO_PASSWORD",
|
||||
"Update or unset PASEO_PASSWORD in the daemon's environment and restart.",
|
||||
);
|
||||
}
|
||||
return createCommandError(
|
||||
(error.code ?? "PASSWORD_UPDATE_FAILED").toUpperCase(),
|
||||
error.userMessage || error.message,
|
||||
);
|
||||
}
|
||||
|
||||
export async function runSetPasswordCommand(
|
||||
options: CommandOptions,
|
||||
_command: Command,
|
||||
): Promise<SingleResult<SetPasswordResult>> {
|
||||
const promptPassword =
|
||||
typeof options.promptPassword === "function"
|
||||
? (options.promptPassword as PromptPassword)
|
||||
: terminalPasswordPrompt();
|
||||
const newPassword = await promptForPassword(promptPassword);
|
||||
const result = await setDaemonPasswordInConfig(newPassword, {
|
||||
home: options.daemonTarget.kind === "instance" ? options.daemonTarget.home : undefined,
|
||||
});
|
||||
const isRemove = options.remove === true;
|
||||
const newPassword = isRemove
|
||||
? null
|
||||
: await promptForPassword(
|
||||
typeof options.promptPassword === "function"
|
||||
? (options.promptPassword as PromptPassword)
|
||||
: terminalPasswordPrompt(),
|
||||
);
|
||||
|
||||
const home = options.daemonTarget.kind === "instance" ? options.daemonTarget.home : undefined;
|
||||
const paseoHome = resolvePaseoHome({ PASEO_HOME: home });
|
||||
const configPath = path.join(paseoHome, CONFIG_FILENAME);
|
||||
|
||||
const liveConnection = await tryConnectLiveClient(options);
|
||||
if (liveConnection) {
|
||||
const { client: liveClient, connectedPassword } = liveConnection;
|
||||
try {
|
||||
const serverInfo = liveClient.getLastServerInfoMessage();
|
||||
if (serverInfo?.features?.daemonPasswordManagement === true) {
|
||||
const res = await liveClient.setDaemonPassword({
|
||||
password: newPassword,
|
||||
...(serverInfo.localCredentialAuth !== true && connectedPassword
|
||||
? { currentPassword: connectedPassword }
|
||||
: {}),
|
||||
});
|
||||
return {
|
||||
type: "single",
|
||||
data: {
|
||||
action: isRemove ? "password_removed" : "password_set",
|
||||
appliedLive: true,
|
||||
passwordConfigured: res.passwordConfigured,
|
||||
disconnectedSessionCount: res.disconnectedSessionCount,
|
||||
configPath,
|
||||
message: formatLiveMessage(isRemove, res.disconnectedSessionCount),
|
||||
},
|
||||
schema: setPasswordResultSchema,
|
||||
};
|
||||
}
|
||||
if (options.daemonTarget.kind === "endpoint") {
|
||||
throw createCommandError(
|
||||
"DAEMON_UPDATE_REQUIRED",
|
||||
"Remote daemon does not support live password updates",
|
||||
"Update the remote daemon or run paseo daemon set-password directly on that host.",
|
||||
);
|
||||
}
|
||||
// Older running daemon does not support live password management; write config.json and advise restart.
|
||||
const fallback = await setDaemonPasswordInConfig(newPassword, {
|
||||
home,
|
||||
daemonRunning: true,
|
||||
});
|
||||
return {
|
||||
type: "single",
|
||||
data: fallback,
|
||||
schema: setPasswordResultSchema,
|
||||
};
|
||||
} catch (error) {
|
||||
if (error instanceof DaemonRpcError) {
|
||||
throw toPasswordRpcCommandError(error);
|
||||
}
|
||||
throw error;
|
||||
} finally {
|
||||
await liveClient.close().catch(() => undefined);
|
||||
}
|
||||
}
|
||||
|
||||
const result = await setDaemonPasswordInConfig(newPassword, { home, daemonRunning: false });
|
||||
return {
|
||||
type: "single",
|
||||
data: result,
|
||||
|
||||
@@ -45,20 +45,28 @@ export async function resolveWorkspaceScriptWorkspaceId(
|
||||
}
|
||||
|
||||
const cwd = resolve(options.cwd ?? process.cwd());
|
||||
const payload = await client.fetchWorkspaces({ page: { limit: 200 } });
|
||||
const matches = payload.entries.filter(
|
||||
(workspace) => resolve(workspace.workspaceDirectory) === cwd,
|
||||
);
|
||||
if (matches.length === 1) {
|
||||
return matches[0]!.id;
|
||||
}
|
||||
if (matches.length > 1) {
|
||||
throw {
|
||||
code: "WORKSPACE_AMBIGUOUS",
|
||||
message: `Multiple workspaces use ${cwd}`,
|
||||
details: "Pass --workspace <workspace-id> to select one.",
|
||||
} satisfies CommandError;
|
||||
}
|
||||
let match: string | undefined;
|
||||
let cursor: string | undefined;
|
||||
do {
|
||||
const payload = await client.fetchWorkspaces({
|
||||
// Activity changes should not move a workspace across the cursor.
|
||||
sort: [{ key: "project_id", direction: "asc" }],
|
||||
page: { limit: 200, cursor },
|
||||
});
|
||||
for (const workspace of payload.entries) {
|
||||
if (resolve(workspace.workspaceDirectory) !== cwd) continue;
|
||||
if (match) {
|
||||
throw {
|
||||
code: "WORKSPACE_AMBIGUOUS",
|
||||
message: `Multiple workspaces use ${cwd}`,
|
||||
details: "Pass --workspace <workspace-id> to select one.",
|
||||
} satisfies CommandError;
|
||||
}
|
||||
match = workspace.id;
|
||||
}
|
||||
cursor = payload.pageInfo.nextCursor ?? undefined;
|
||||
} while (cursor);
|
||||
if (match) return match;
|
||||
throw {
|
||||
code: "WORKSPACE_NOT_FOUND",
|
||||
message: `No Paseo workspace found for ${cwd}`,
|
||||
|
||||
@@ -3,6 +3,7 @@ import type { Command } from "commander";
|
||||
import { connectToDaemon } from "../../utils/client.js";
|
||||
import type { CommandError, OutputSchema, SingleResult } from "../../output/index.js";
|
||||
import { buildCreateWorktreeRequest, type WorktreeCreateOptions } from "./create-input.js";
|
||||
import { resolveRepositoryDirectory } from "./repository-directory.js";
|
||||
|
||||
export interface WorktreeCreateResult {
|
||||
name: string;
|
||||
@@ -38,7 +39,7 @@ export async function runCreateCommandWithDeps(
|
||||
): Promise<Pick<Awaited<ReturnType<typeof connectToDaemon>>, "createPaseoWorktree" | "close">>;
|
||||
},
|
||||
): Promise<SingleResult<WorktreeCreateResult>> {
|
||||
const cwd = options.cwd ?? process.cwd();
|
||||
const cwd = resolveRepositoryDirectory(options);
|
||||
const request = buildCreateWorktreeRequest(options, cwd);
|
||||
|
||||
const client = await deps.connectToDaemon({ target: options.daemonTarget });
|
||||
|
||||
@@ -25,6 +25,7 @@ export interface ConnectOptions {
|
||||
target: DaemonTarget;
|
||||
timeout?: number;
|
||||
instance?: DaemonInstance;
|
||||
preferLocalCredential?: boolean;
|
||||
}
|
||||
export function resolveClientPaseoHome(
|
||||
target: DaemonTarget,
|
||||
@@ -195,7 +196,14 @@ export function resolveDaemonPassword(host: string): string | undefined {
|
||||
export function resolveDaemonCredential(
|
||||
host: string,
|
||||
home: string,
|
||||
options?: { preferLocalCredential?: boolean },
|
||||
): { kind: "password"; password: string } | { kind: "localCredential"; token: string } | null {
|
||||
if (options?.preferLocalCredential) {
|
||||
const token = readLocalCredentialForTarget(home, host);
|
||||
if (token) return { kind: "localCredential", token };
|
||||
const password = resolveDaemonPassword(host);
|
||||
return password ? { kind: "password", password } : null;
|
||||
}
|
||||
const password = resolveDaemonPassword(host);
|
||||
if (password) return { kind: "password", password };
|
||||
const token = readLocalCredentialForTarget(home, host);
|
||||
@@ -214,7 +222,9 @@ async function connectSelectedDaemon(options: ConnectOptions): Promise<DaemonCli
|
||||
})
|
||||
).listen;
|
||||
const home = resolveClientPaseoHome(options.target);
|
||||
const credential = resolveDaemonCredential(host, home);
|
||||
const credential = resolveDaemonCredential(host, home, {
|
||||
preferLocalCredential: options.preferLocalCredential,
|
||||
});
|
||||
const client = createLeanHostClient(host, {
|
||||
clientId: await getOrCreateCliClientId(home),
|
||||
clientType: "cli",
|
||||
|
||||
@@ -99,6 +99,19 @@ test("CLI selects an explicit password before a matching local credential and ne
|
||||
kind: "password",
|
||||
password: "explicit",
|
||||
});
|
||||
process.env.PASEO_PASSWORD = "from-env";
|
||||
expect(
|
||||
resolveDaemonCredential("tcp://localhost:6767", home, { preferLocalCredential: true }),
|
||||
).toEqual({
|
||||
kind: "localCredential",
|
||||
token,
|
||||
});
|
||||
expect(
|
||||
resolveDaemonCredential("tcp://remote.example:6767", home, { preferLocalCredential: true }),
|
||||
).toEqual({
|
||||
kind: "password",
|
||||
password: "from-env",
|
||||
});
|
||||
} finally {
|
||||
if (previousPassword === undefined) delete process.env.PASEO_PASSWORD;
|
||||
else process.env.PASEO_PASSWORD = previousPassword;
|
||||
|
||||
@@ -181,7 +181,7 @@ const git = promisify(execFile);
|
||||
let daemon: TestDaemonContext | undefined;
|
||||
try {
|
||||
await mkdir(repo);
|
||||
await git("git", ["init", repo]);
|
||||
await git("git", ["init", "-b", "main", repo]);
|
||||
await git("git", [
|
||||
"-C",
|
||||
repo,
|
||||
@@ -235,6 +235,29 @@ try {
|
||||
assert.notStrictEqual(result.exitCode, 0);
|
||||
assert.strictEqual(JSON.parse(result.stderr).error.code, "WORKTREE_NOT_FOUND", result.stderr);
|
||||
}
|
||||
|
||||
const created = await runPaseoCli(
|
||||
daemon,
|
||||
[
|
||||
"worktree",
|
||||
"create",
|
||||
"--cwd",
|
||||
"./repository",
|
||||
"--mode",
|
||||
"branch-off",
|
||||
"--new-branch",
|
||||
"topic",
|
||||
"--base",
|
||||
"main",
|
||||
"--json",
|
||||
],
|
||||
{ cwd: fixtureDir },
|
||||
);
|
||||
assert.strictEqual(created.exitCode, 0, created.stderr);
|
||||
const { worktreePath } = JSON.parse(created.stdout);
|
||||
const source = await git("git", ["-C", repo, "rev-parse", "HEAD"]);
|
||||
const checkout = await git("git", ["-C", worktreePath, "rev-parse", "HEAD"]);
|
||||
assert.strictEqual(checkout.stdout, source.stdout);
|
||||
} finally {
|
||||
try {
|
||||
await daemon?.stop();
|
||||
|
||||
@@ -213,7 +213,16 @@ try {
|
||||
return session;
|
||||
});
|
||||
|
||||
// Exit just this provider while the host is up to prove failure reporting remains active.
|
||||
// Exit just this provider during a turn while the host is up to prove failure reporting
|
||||
// remains active. An idle exit of a resumable session closes cleanly instead.
|
||||
await daemon.client.sendMessage(crashing.id, "Hold the turn open.");
|
||||
// Wait for the provider itself to log the prompt, not just for the agent to report running.
|
||||
await waitFor(async () => {
|
||||
const events = await readEvents();
|
||||
return events.find(
|
||||
(event) => event.type === "prompt" && event.sessionId === sessions[2].sessionId,
|
||||
);
|
||||
}, "crashing provider did not receive its prompt");
|
||||
process.kill(sessions[2].pid, "SIGTERM");
|
||||
await waitFor(async () => {
|
||||
const { agent } = (await daemon!.client.fetchAgent(crashing.id)) ?? {};
|
||||
@@ -260,6 +269,11 @@ try {
|
||||
assert.deepEqual(
|
||||
(await readEvents()).filter((event) => event.type === "prompt"),
|
||||
[
|
||||
{
|
||||
type: "prompt",
|
||||
sessionId: sessions[2].sessionId,
|
||||
text: "Hold the turn open.",
|
||||
},
|
||||
{
|
||||
type: "prompt",
|
||||
sessionId: sessions[1].sessionId,
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { mkdir, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { createPaseoClient } from "@getpaseo/client";
|
||||
import { createE2ETestContext } from "./helpers/test-daemon.ts";
|
||||
|
||||
const ctx = await createE2ETestContext();
|
||||
const sdk = createPaseoClient({ url: `${ctx.wsUrl}/ws`, reconnect: { enabled: false } });
|
||||
|
||||
try {
|
||||
await sdk.connect();
|
||||
for (let i = 0; i < 201; i++) {
|
||||
const path = join(ctx.workDir, String(i));
|
||||
await mkdir(path);
|
||||
await writeFile(
|
||||
join(path, "paseo.json"),
|
||||
JSON.stringify({ scripts: { check: { command: "echo ok" } } }),
|
||||
);
|
||||
await sdk.workspaces.create({ source: { kind: "directory", path } });
|
||||
}
|
||||
|
||||
const first = await sdk.workspaces.list({ page: { limit: 200 } });
|
||||
assert.ok(first.pageInfo.nextCursor);
|
||||
const next = await sdk.workspaces.list({
|
||||
page: { cursor: first.pageInfo.nextCursor, limit: 200 },
|
||||
});
|
||||
assert.equal(next.entries.length, 1);
|
||||
const { id, workspaceDirectory } = next.entries[0]!;
|
||||
const listByCwd = () => ctx.paseo(["script", "ls", "--cwd", workspaceDirectory, "--json"]);
|
||||
const unique = await listByCwd();
|
||||
assert.equal(unique.exitCode, 0, unique.stderr);
|
||||
assert.deepEqual(
|
||||
JSON.parse(unique.stdout).map((script: { scriptName: string }) => script.scriptName),
|
||||
["check"],
|
||||
);
|
||||
|
||||
await sdk.workspaces.create({
|
||||
source: { kind: "directory", path: workspaceDirectory },
|
||||
title: "Second workspace",
|
||||
});
|
||||
const ambiguous = await listByCwd();
|
||||
assert.equal(ambiguous.exitCode, 1);
|
||||
assert.equal(JSON.parse(ambiguous.stderr).error.code, "WORKSPACE_AMBIGUOUS");
|
||||
const explicit = await ctx.paseo(["script", "ls", "--workspace", id, "--json"]);
|
||||
assert.equal(explicit.exitCode, 0, explicit.stderr);
|
||||
assert.deepEqual(JSON.parse(explicit.stdout), JSON.parse(unique.stdout));
|
||||
} finally {
|
||||
await sdk.close();
|
||||
await ctx.stop();
|
||||
}
|
||||
@@ -139,6 +139,7 @@ import type {
|
||||
DaemonTailscaleSetResponse,
|
||||
DaemonGetPairingOfferResponse,
|
||||
DaemonConfigReloadResponse,
|
||||
DaemonAuthPasswordSetResponse,
|
||||
DiagnosticsResponse,
|
||||
AgentRewindResponseMessage,
|
||||
AgentProviderSwitchRequest,
|
||||
@@ -1205,7 +1206,7 @@ export class DaemonConnectionError extends Error {
|
||||
}
|
||||
}
|
||||
|
||||
class DaemonRpcError extends Error {
|
||||
export class DaemonRpcError extends Error {
|
||||
readonly requestId: string;
|
||||
readonly requestType?: string;
|
||||
readonly code?: string;
|
||||
@@ -6688,6 +6689,21 @@ export class DaemonClientCore {
|
||||
});
|
||||
}
|
||||
|
||||
async setDaemonPassword(
|
||||
input: { password: string | null; currentPassword?: string },
|
||||
requestId?: string,
|
||||
): Promise<DaemonAuthPasswordSetResponse["payload"]> {
|
||||
this.requireDaemonPasswordManagementSupport();
|
||||
return this.sendNamespacedCorrelatedSessionRequest<"daemon.auth.password.set.response">({
|
||||
requestId,
|
||||
message: {
|
||||
type: "daemon.auth.password.set.request",
|
||||
password: input.password,
|
||||
...(input.currentPassword !== undefined ? { currentPassword: input.currentPassword } : {}),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async connectHub(
|
||||
hubUrl: string,
|
||||
token: string,
|
||||
@@ -8021,6 +8037,13 @@ export class DaemonClientCore {
|
||||
}
|
||||
}
|
||||
|
||||
private requireDaemonPasswordManagementSupport(): void {
|
||||
// COMPAT(daemonPasswordManagement): added in v0.19.x, remove gate after 2027-06-15.
|
||||
if (this.lastServerInfoMessage?.features?.daemonPasswordManagement !== true) {
|
||||
throw new Error("Update the host to manage the daemon password.");
|
||||
}
|
||||
}
|
||||
|
||||
private resolveTransportUrlForAttempt(): string {
|
||||
return this.config.url;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,217 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
import { DaemonClient, DaemonRpcError, type DaemonTransport } from "./daemon-client.js";
|
||||
|
||||
function createFakeTransport(options: {
|
||||
features?: Record<string, boolean | undefined>;
|
||||
onSetPassword?: (
|
||||
request: Record<string, unknown>,
|
||||
) =>
|
||||
| { ok: true; passwordConfigured: boolean; disconnectedSessionCount: number }
|
||||
| { ok: false; code: string; error: string };
|
||||
}): {
|
||||
transport: DaemonTransport;
|
||||
sent: Array<{ type: string; message?: Record<string, unknown> }>;
|
||||
} {
|
||||
const sent: Array<{ type: string; message?: Record<string, unknown> }> = [];
|
||||
const openHandlers = new Set<() => void>();
|
||||
const messageHandlers = new Set<(data: unknown, isBinary: boolean) => void | Promise<void>>();
|
||||
const closeHandlers = new Set<(event?: unknown) => void>();
|
||||
const errorHandlers = new Set<(event?: unknown) => void>();
|
||||
|
||||
const emitMessage = (text: string) => {
|
||||
queueMicrotask(() => {
|
||||
for (const handler of messageHandlers) {
|
||||
void handler(text, false);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
const transport: DaemonTransport = {
|
||||
onOpen(handler) {
|
||||
openHandlers.add(handler);
|
||||
queueMicrotask(() => handler());
|
||||
return () => openHandlers.delete(handler);
|
||||
},
|
||||
onMessage(handler) {
|
||||
messageHandlers.add(handler);
|
||||
return () => messageHandlers.delete(handler);
|
||||
},
|
||||
onClose(handler) {
|
||||
closeHandlers.add(handler);
|
||||
return () => closeHandlers.delete(handler);
|
||||
},
|
||||
onError(handler) {
|
||||
errorHandlers.add(handler);
|
||||
return () => errorHandlers.delete(handler);
|
||||
},
|
||||
send(data) {
|
||||
if (typeof data !== "string") return;
|
||||
const parsed = JSON.parse(data) as { type: string; message?: Record<string, unknown> };
|
||||
sent.push(parsed);
|
||||
|
||||
if (parsed.type === "hello") {
|
||||
emitMessage(
|
||||
JSON.stringify({
|
||||
type: "session",
|
||||
message: {
|
||||
type: "status",
|
||||
payload: {
|
||||
status: "server_info",
|
||||
serverId: "srv_test",
|
||||
version: "0.19.0",
|
||||
passwordConfigured: false,
|
||||
passwordManagedByEnv: false,
|
||||
localCredentialAuth: true,
|
||||
features: options.features ?? { daemonPasswordManagement: true },
|
||||
},
|
||||
},
|
||||
}),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (parsed.type !== "session" || !parsed.message) return;
|
||||
const requestId = parsed.message.requestId;
|
||||
if (typeof requestId !== "string") return;
|
||||
|
||||
if (parsed.message.type === "daemon.auth.password.set.request") {
|
||||
const result = options.onSetPassword?.(parsed.message) ?? {
|
||||
ok: true as const,
|
||||
passwordConfigured: parsed.message.password !== null,
|
||||
disconnectedSessionCount: 1,
|
||||
};
|
||||
if (result.ok) {
|
||||
emitMessage(
|
||||
JSON.stringify({
|
||||
type: "session",
|
||||
message: {
|
||||
type: "daemon.auth.password.set.response",
|
||||
payload: {
|
||||
requestId,
|
||||
passwordConfigured: result.passwordConfigured,
|
||||
disconnectedSessionCount: result.disconnectedSessionCount,
|
||||
},
|
||||
},
|
||||
}),
|
||||
);
|
||||
} else {
|
||||
emitMessage(
|
||||
JSON.stringify({
|
||||
type: "session",
|
||||
message: {
|
||||
type: "rpc_error",
|
||||
payload: {
|
||||
requestId,
|
||||
requestType: "daemon.auth.password.set.request",
|
||||
code: result.code,
|
||||
error: result.error,
|
||||
},
|
||||
},
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
},
|
||||
close() {
|
||||
for (const handler of closeHandlers) {
|
||||
handler({ code: 1000, reason: "closed" });
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
return { transport, sent };
|
||||
}
|
||||
|
||||
describe("DaemonClient.setDaemonPassword", () => {
|
||||
test("sends daemon.auth.password.set.request for set and remove", async () => {
|
||||
const { transport, sent } = createFakeTransport({});
|
||||
const client = new DaemonClient({
|
||||
url: "ws://127.0.0.1:6767/ws",
|
||||
clientId: "test-client-1",
|
||||
transportFactory: () => transport,
|
||||
reconnect: { enabled: false },
|
||||
});
|
||||
await client.connect();
|
||||
|
||||
const setResult = await client.setDaemonPassword({ password: "new-password-123" });
|
||||
expect(setResult).toEqual({
|
||||
requestId: expect.any(String),
|
||||
passwordConfigured: true,
|
||||
disconnectedSessionCount: 1,
|
||||
});
|
||||
|
||||
const removeResult = await client.setDaemonPassword({
|
||||
password: null,
|
||||
currentPassword: "new-password-123",
|
||||
});
|
||||
expect(removeResult).toEqual({
|
||||
requestId: expect.any(String),
|
||||
passwordConfigured: false,
|
||||
disconnectedSessionCount: 1,
|
||||
});
|
||||
|
||||
const rpcRequests = sent
|
||||
.map((item) => item.message)
|
||||
.filter((msg) => msg?.type === "daemon.auth.password.set.request");
|
||||
expect(rpcRequests).toEqual([
|
||||
{
|
||||
type: "daemon.auth.password.set.request",
|
||||
requestId: expect.any(String),
|
||||
password: "new-password-123",
|
||||
},
|
||||
{
|
||||
type: "daemon.auth.password.set.request",
|
||||
requestId: expect.any(String),
|
||||
password: null,
|
||||
currentPassword: "new-password-123",
|
||||
},
|
||||
]);
|
||||
|
||||
await client.close();
|
||||
});
|
||||
|
||||
test("gates on server_info.features.daemonPasswordManagement", async () => {
|
||||
const { transport } = createFakeTransport({ features: {} });
|
||||
const client = new DaemonClient({
|
||||
url: "ws://127.0.0.1:6767/ws",
|
||||
clientId: "test-client-1",
|
||||
transportFactory: () => transport,
|
||||
reconnect: { enabled: false },
|
||||
});
|
||||
await client.connect();
|
||||
|
||||
await expect(client.setDaemonPassword({ password: "secret123" })).rejects.toThrow(
|
||||
/Update the host/i,
|
||||
);
|
||||
|
||||
await client.close();
|
||||
});
|
||||
|
||||
test("propagates structured rpc_error codes via DaemonRpcError", async () => {
|
||||
const { transport } = createFakeTransport({
|
||||
onSetPassword: () => ({
|
||||
ok: false,
|
||||
code: "incorrect_password",
|
||||
error: "Current password is incorrect",
|
||||
}),
|
||||
});
|
||||
const client = new DaemonClient({
|
||||
url: "ws://127.0.0.1:6767/ws",
|
||||
clientId: "test-client-1",
|
||||
transportFactory: () => transport,
|
||||
reconnect: { enabled: false },
|
||||
});
|
||||
await client.connect();
|
||||
|
||||
let caught: unknown;
|
||||
try {
|
||||
await client.setDaemonPassword({ password: "new-password", currentPassword: "wrong" });
|
||||
} catch (error) {
|
||||
caught = error;
|
||||
}
|
||||
expect(caught).toBeInstanceOf(DaemonRpcError);
|
||||
expect((caught as DaemonRpcError).code).toBe("incorrect_password");
|
||||
|
||||
await client.close();
|
||||
});
|
||||
});
|
||||
@@ -48,6 +48,7 @@ import type {
|
||||
WorkspaceCreateRequest,
|
||||
} from "@getpaseo/protocol/messages";
|
||||
import { DaemonClient, type CreateAgentRequestOptions } from "./daemon-client.js";
|
||||
export { DaemonRpcError } from "./daemon-client.js";
|
||||
export { AgentQueueCollection } from "@getpaseo/protocol/sync/resources";
|
||||
export type {
|
||||
SyncCollectionDescriptor,
|
||||
|
||||
@@ -10,6 +10,8 @@ import path from "node:path";
|
||||
import process from "node:process";
|
||||
import { setTimeout as delay } from "node:timers/promises";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { experimental_createMCPClient } from "ai";
|
||||
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
|
||||
import { chromium } from "playwright";
|
||||
import { expect } from "@playwright/test";
|
||||
import { WebSocket, WebSocketServer } from "ws";
|
||||
@@ -81,45 +83,56 @@ function writeJson(filePath, value) {
|
||||
fs.writeFileSync(filePath, `${JSON.stringify(value, null, 2)}\n`);
|
||||
}
|
||||
|
||||
function seedPaseoHome({ paseoHome, listen, workspaceRoot, workspaceId, workspaceTitle, relay }) {
|
||||
function seedPaseoHome({
|
||||
paseoHome,
|
||||
listen,
|
||||
workspaceRoot,
|
||||
workspaceId,
|
||||
workspaceTitle,
|
||||
relay,
|
||||
mcpEnabled = false,
|
||||
extraWorkspaces = [],
|
||||
}) {
|
||||
const timestamp = "2026-01-01T00:00:00.000Z";
|
||||
const cwd = path.join(workspaceRoot, workspaceId);
|
||||
fs.mkdirSync(cwd, { recursive: true });
|
||||
const projects = [
|
||||
{
|
||||
projectId: `project-${workspaceId}`,
|
||||
const specs = [{ workspaceId, workspaceTitle, dirName: workspaceId }, ...extraWorkspaces];
|
||||
const projects = [];
|
||||
const workspaces = [];
|
||||
for (const spec of specs) {
|
||||
const cwd = path.join(workspaceRoot, spec.dirName);
|
||||
fs.mkdirSync(cwd, { recursive: true });
|
||||
const projectId = `project-${spec.workspaceId}`;
|
||||
projects.push({
|
||||
projectId,
|
||||
rootPath: cwd,
|
||||
kind: "non_git",
|
||||
displayName: workspaceTitle,
|
||||
displayName: spec.workspaceTitle,
|
||||
customName: null,
|
||||
createdAt: timestamp,
|
||||
updatedAt: timestamp,
|
||||
archivedAt: null,
|
||||
},
|
||||
];
|
||||
const workspaces = [
|
||||
{
|
||||
workspaceId,
|
||||
projectId: projects[0].projectId,
|
||||
});
|
||||
workspaces.push({
|
||||
workspaceId: spec.workspaceId,
|
||||
projectId,
|
||||
cwd,
|
||||
kind: "directory",
|
||||
displayName: workspaceTitle,
|
||||
title: workspaceTitle,
|
||||
displayName: spec.workspaceTitle,
|
||||
title: spec.workspaceTitle,
|
||||
branch: null,
|
||||
baseBranch: null,
|
||||
createdAt: timestamp,
|
||||
updatedAt: timestamp,
|
||||
archivedAt: null,
|
||||
pinnedAt: null,
|
||||
},
|
||||
];
|
||||
});
|
||||
}
|
||||
|
||||
writeJson(path.join(paseoHome, "config.json"), {
|
||||
version: 1,
|
||||
daemon: {
|
||||
listen,
|
||||
relay: relay ?? { enabled: false },
|
||||
mcp: { enabled: false, injectIntoAgents: false },
|
||||
mcp: { enabled: mcpEnabled, injectIntoAgents: mcpEnabled },
|
||||
browserTools: { enabled: true },
|
||||
cors: { allowedOrigins: ["*"] },
|
||||
},
|
||||
@@ -167,6 +180,8 @@ async function startTargetHttpAndWsServer() {
|
||||
<body>
|
||||
<h1 id="heading">Proxied HTTP OK</h1>
|
||||
<div id="ws-result">connecting</div>
|
||||
<label for="proxy-upload">Proxy upload</label>
|
||||
<input id="proxy-upload" type="file" />
|
||||
<script>
|
||||
const ws = new WebSocket("ws://" + location.host + "/ws");
|
||||
ws.addEventListener("open", () => ws.send("hello-tunnel"));
|
||||
@@ -797,20 +812,58 @@ async function verifyHostProxiedProfiles({
|
||||
);
|
||||
await poll(() => guestAt(hostPartition)).toMatchObject({ marker: "from-host-partition" });
|
||||
|
||||
// 7. Remove Work closes its host-proxied tab and deletes its host partition directory.
|
||||
// 7. Remove Work closes its host-proxied tab, revokes its proxy partition, and allows clean re-binding.
|
||||
await acceptNextDialog(inspect, "Remove");
|
||||
await page.getByTestId("settings-browser-profile-menu-work").click();
|
||||
await page.getByTestId("settings-browser-profile-remove-work").click();
|
||||
await expect(page.getByTestId("settings-browser-profile-row-work")).toHaveCount(0);
|
||||
await poll(() => fs.existsSync(hostWorkDir)).toBe(false);
|
||||
const statusAfterRemove = await page.evaluate(
|
||||
async () => await window.paseoDesktop.browser.getHostProxyStatus("e2e-remote-host"),
|
||||
);
|
||||
assert(
|
||||
statusAfterRemove?.status === "ready" &&
|
||||
statusAfterRemove.profilePartitions.default === hostPartition &&
|
||||
!("work" in statusAfterRemove.profilePartitions),
|
||||
`Expected Work partition to be purged from host proxy status, got ${JSON.stringify(statusAfterRemove)}`,
|
||||
);
|
||||
await page.getByTestId("settings-back-to-workspace").click();
|
||||
await poll(async () => (await guestAt(hostWorkPartition)).found).toBe(false);
|
||||
await poll(() => guestAt(hostPartition)).toMatchObject({ marker: "from-host-partition" });
|
||||
|
||||
// Recreate Work: the retired slug stays revoked while the new slug ("work-2") binds cleanly.
|
||||
const hostWork2Partition = `${hostPartition}-profile-work-2`;
|
||||
await picker().click();
|
||||
await page.getByTestId("browser-profile-create-trigger").click();
|
||||
await page.getByTestId("browser-create-profile-input").fill("Work");
|
||||
await page.getByTestId("browser-create-profile-submit").click();
|
||||
await expect(picker()).toHaveAttribute("aria-label", "Browser profile: Work");
|
||||
await poll(() => guestAt(hostWork2Partition)).toMatchObject({ ...loadedPage, marker: null });
|
||||
const statusAfterRebind = await page.evaluate(
|
||||
async () => await window.paseoDesktop.browser.getHostProxyStatus("e2e-remote-host"),
|
||||
);
|
||||
assert(
|
||||
statusAfterRebind?.status === "ready" &&
|
||||
!("work" in statusAfterRebind.profilePartitions) &&
|
||||
statusAfterRebind.profilePartitions["work-2"] === hostWork2Partition &&
|
||||
typeof statusAfterRebind.socksPort === "number",
|
||||
`Expected recreated Work profile ("work-2") to bind while removed "work" stays purged, got ${JSON.stringify(statusAfterRebind)}`,
|
||||
);
|
||||
const reboundResolvedProxy = await inspect(
|
||||
`return await electron.session.fromPartition(${JSON.stringify(hostWork2Partition)}).resolveProxy("http://localhost:${targetServer.port}/");`,
|
||||
);
|
||||
assert(
|
||||
reboundResolvedProxy.includes(`SOCKS5 127.0.0.1:${statusAfterRebind.socksPort}`),
|
||||
`Expected recreated Work profile to resolve to host SOCKS5 port ${statusAfterRebind.socksPort}, got ${reboundResolvedProxy}`,
|
||||
);
|
||||
await choose("default", "Default");
|
||||
await poll(() => guestAt(hostPartition)).toMatchObject({ marker: "from-host-partition" });
|
||||
|
||||
return {
|
||||
hostWorkPartition,
|
||||
socksPort: status.socksPort,
|
||||
resolvedProxy,
|
||||
reboundResolvedProxy,
|
||||
tunnelConnections: after.clientConnections,
|
||||
egressProcess,
|
||||
clearAndRemove: "passed",
|
||||
@@ -1011,6 +1064,191 @@ async function verifyRoutedHostBrowsing({ page, targetServer, targetUrl }) {
|
||||
};
|
||||
}
|
||||
|
||||
async function createMcpClient({ daemonPort, password, callerAgentId }) {
|
||||
const url = new URL(`http://127.0.0.1:${daemonPort}/mcp/agents`);
|
||||
if (callerAgentId) {
|
||||
url.searchParams.set("callerAgentId", callerAgentId);
|
||||
}
|
||||
const transport = new StreamableHTTPClientTransport(
|
||||
url,
|
||||
password ? { requestInit: { headers: { Authorization: `Bearer ${password}` } } } : undefined,
|
||||
);
|
||||
return await experimental_createMCPClient({ transport });
|
||||
}
|
||||
|
||||
async function createMcpCallerAgent({ daemonPort, password, workspaceId }) {
|
||||
const client = await createMcpClient({ daemonPort, password });
|
||||
try {
|
||||
const response = await client.callTool({
|
||||
name: "create_agent",
|
||||
args: {
|
||||
relationship: { kind: "detached" },
|
||||
workspace: { kind: "existing", workspaceId },
|
||||
title: `Browser boundary E2E caller (${workspaceId})`,
|
||||
provider: "mock/ten-second-stream",
|
||||
settings: { modeId: "load-test" },
|
||||
initialPrompt: "Remain available while browser automation checks run.",
|
||||
},
|
||||
});
|
||||
const agentId = response.structuredContent?.agentId;
|
||||
assert(
|
||||
typeof agentId === "string",
|
||||
`create_agent returned no agentId: ${JSON.stringify(response)}`,
|
||||
);
|
||||
return agentId;
|
||||
} finally {
|
||||
await client.close();
|
||||
}
|
||||
}
|
||||
|
||||
async function callMcpBrowserTool(client, name, args = {}) {
|
||||
const response = await client.callTool({ name, args });
|
||||
const payload = response.structuredContent;
|
||||
assert(payload && payload.ok === true, `${name} failed: ${JSON.stringify(response)}`);
|
||||
return payload.result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Verifies cross-host tab isolation when local and remote daemons share an identical
|
||||
* workspaceId, and verifies remote browser_upload fails closed with browser_unsupported.
|
||||
*/
|
||||
async function verifyCrossHostAutomationAndUploadBoundary({
|
||||
localDaemonPort,
|
||||
localDaemonPassword,
|
||||
remoteDaemonPort,
|
||||
sharedWorkspaceId,
|
||||
targetUrl,
|
||||
runtimeDir,
|
||||
}) {
|
||||
const localOnlyFile = path.join(runtimeDir, "local-host-file.txt");
|
||||
fs.writeFileSync(localOnlyFile, "local-host-file-content");
|
||||
|
||||
const localAgentId = await createMcpCallerAgent({
|
||||
daemonPort: localDaemonPort,
|
||||
password: localDaemonPassword,
|
||||
workspaceId: sharedWorkspaceId,
|
||||
});
|
||||
const remoteAgentId = await createMcpCallerAgent({
|
||||
daemonPort: remoteDaemonPort,
|
||||
workspaceId: sharedWorkspaceId,
|
||||
});
|
||||
|
||||
const localClient = await createMcpClient({
|
||||
daemonPort: localDaemonPort,
|
||||
password: localDaemonPassword,
|
||||
callerAgentId: localAgentId,
|
||||
});
|
||||
const remoteClient = await createMcpClient({
|
||||
daemonPort: remoteDaemonPort,
|
||||
callerAgentId: remoteAgentId,
|
||||
});
|
||||
|
||||
let localBrowserId = null;
|
||||
let remoteBrowserId = null;
|
||||
try {
|
||||
const localTab = await callMcpBrowserTool(localClient, "browser_new_tab", { url: targetUrl });
|
||||
localBrowserId = localTab.browserId;
|
||||
await callMcpBrowserTool(localClient, "browser_wait", {
|
||||
browserId: localBrowserId,
|
||||
text: "Proxied HTTP OK",
|
||||
timeoutMs: 15_000,
|
||||
});
|
||||
|
||||
const remoteTab = await callMcpBrowserTool(remoteClient, "browser_new_tab", { url: targetUrl });
|
||||
remoteBrowserId = remoteTab.browserId;
|
||||
await callMcpBrowserTool(remoteClient, "browser_wait", {
|
||||
browserId: remoteBrowserId,
|
||||
text: "Proxied HTTP OK",
|
||||
timeoutMs: 15_000,
|
||||
});
|
||||
|
||||
// Each host sees only its own tab even though both share the same workspaceId.
|
||||
const localTabs = await callMcpBrowserTool(localClient, "browser_list_tabs");
|
||||
const remoteTabs = await callMcpBrowserTool(remoteClient, "browser_list_tabs");
|
||||
assert(
|
||||
localTabs.tabs.map((tab) => tab.browserId).includes(localBrowserId) &&
|
||||
!localTabs.tabs.map((tab) => tab.browserId).includes(remoteBrowserId),
|
||||
`Local list_tabs leaked cross-host tab: ${JSON.stringify(localTabs)}`,
|
||||
);
|
||||
assert(
|
||||
remoteTabs.tabs.map((tab) => tab.browserId).includes(remoteBrowserId) &&
|
||||
!remoteTabs.tabs.map((tab) => tab.browserId).includes(localBrowserId),
|
||||
`Remote list_tabs leaked cross-host tab: ${JSON.stringify(remoteTabs)}`,
|
||||
);
|
||||
|
||||
// Direct tab commands across hosts with matching workspaceId return browser_tab_not_found.
|
||||
const remoteToLocal = await remoteClient.callTool({
|
||||
name: "browser_snapshot",
|
||||
args: { browserId: localBrowserId },
|
||||
});
|
||||
assert(
|
||||
remoteToLocal.structuredContent?.ok === false &&
|
||||
remoteToLocal.structuredContent?.error?.code === "browser_tab_not_found",
|
||||
`Expected cross-host snapshot to fail with browser_tab_not_found, got ${JSON.stringify(remoteToLocal.structuredContent)}`,
|
||||
);
|
||||
|
||||
const localToRemote = await localClient.callTool({
|
||||
name: "browser_snapshot",
|
||||
args: { browserId: remoteBrowserId },
|
||||
});
|
||||
assert(
|
||||
localToRemote.structuredContent?.ok === false &&
|
||||
localToRemote.structuredContent?.error?.code === "browser_tab_not_found",
|
||||
`Expected local->remote snapshot to fail with browser_tab_not_found, got ${JSON.stringify(localToRemote.structuredContent)}`,
|
||||
);
|
||||
|
||||
// Remote browser_upload targeting a local file fails closed with browser_unsupported.
|
||||
const remoteSnapshot = await callMcpBrowserTool(remoteClient, "browser_snapshot", {
|
||||
browserId: remoteBrowserId,
|
||||
});
|
||||
const refMatch = remoteSnapshot.snapshot.match(/Proxy upload"[^\n]*ref=(@e\d+)/);
|
||||
assert(
|
||||
refMatch,
|
||||
`Could not find file input ref in remote snapshot:\n${remoteSnapshot.snapshot}`,
|
||||
);
|
||||
const remoteUpload = await remoteClient.callTool({
|
||||
name: "browser_upload",
|
||||
args: {
|
||||
browserId: remoteBrowserId,
|
||||
ref: refMatch[1],
|
||||
filePaths: [localOnlyFile],
|
||||
},
|
||||
});
|
||||
assert(
|
||||
remoteUpload.structuredContent?.ok === false &&
|
||||
remoteUpload.structuredContent?.error?.code === "browser_unsupported",
|
||||
`Expected remote browser_upload to fail with browser_unsupported, got ${JSON.stringify(remoteUpload.structuredContent)}`,
|
||||
);
|
||||
const attachedCount = await callMcpBrowserTool(remoteClient, "browser_evaluate", {
|
||||
browserId: remoteBrowserId,
|
||||
function: "() => document.getElementById('proxy-upload')?.files?.length ?? -1",
|
||||
});
|
||||
assert(
|
||||
JSON.parse(attachedCount.resultJson) === 0,
|
||||
`Expected remote file input to remain empty, got ${attachedCount.resultJson}`,
|
||||
);
|
||||
|
||||
return {
|
||||
crossHostTabIsolation: "passed",
|
||||
remoteUploadRejected: "passed",
|
||||
};
|
||||
} finally {
|
||||
if (localBrowserId) {
|
||||
await localClient
|
||||
.callTool({ name: "browser_close_tab", args: { browserId: localBrowserId } })
|
||||
.catch(() => undefined);
|
||||
}
|
||||
if (remoteBrowserId) {
|
||||
await remoteClient
|
||||
.callTool({ name: "browser_close_tab", args: { browserId: remoteBrowserId } })
|
||||
.catch(() => undefined);
|
||||
}
|
||||
await localClient.close().catch(() => undefined);
|
||||
await remoteClient.close().catch(() => undefined);
|
||||
fs.rmSync(localOnlyFile, { force: true });
|
||||
}
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const artifactDir =
|
||||
process.env.PASEO_DESKTOP_BROWSER_PROXY_E2E_ARTIFACT_DIR ??
|
||||
@@ -1054,12 +1292,21 @@ async function main() {
|
||||
let appPage = null;
|
||||
|
||||
try {
|
||||
const sharedWorkspaceId = "wks-shared-scope";
|
||||
seedPaseoHome({
|
||||
paseoHome: localHome,
|
||||
listen: `127.0.0.1:${localDaemonPort}`,
|
||||
workspaceRoot,
|
||||
workspaceId: "wks-local-proxy",
|
||||
workspaceTitle: "Local Workspace",
|
||||
mcpEnabled: true,
|
||||
extraWorkspaces: [
|
||||
{
|
||||
workspaceId: sharedWorkspaceId,
|
||||
workspaceTitle: "Shared Local Scope",
|
||||
dirName: "shared-local",
|
||||
},
|
||||
],
|
||||
});
|
||||
seedPaseoHome({
|
||||
paseoHome: remoteHome,
|
||||
@@ -1067,6 +1314,14 @@ async function main() {
|
||||
workspaceRoot,
|
||||
workspaceId: "wks-remote-proxy",
|
||||
workspaceTitle: "Remote Proxy Workspace",
|
||||
mcpEnabled: true,
|
||||
extraWorkspaces: [
|
||||
{
|
||||
workspaceId: sharedWorkspaceId,
|
||||
workspaceTitle: "Shared Remote Scope",
|
||||
dirName: "shared-remote",
|
||||
},
|
||||
],
|
||||
relay: {
|
||||
enabled: true,
|
||||
endpoint: `127.0.0.1:${relayBridge.port}`,
|
||||
@@ -1500,6 +1755,18 @@ async function main() {
|
||||
});
|
||||
await page.screenshot({ path: path.join(artifactDir, "05-routed-host-loaded.png") });
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// 6. Cross-host tab isolation & remote browser_upload rejection
|
||||
// -------------------------------------------------------------------------
|
||||
const crossHostBoundary = await verifyCrossHostAutomationAndUploadBoundary({
|
||||
localDaemonPort,
|
||||
localDaemonPassword,
|
||||
remoteDaemonPort,
|
||||
sharedWorkspaceId,
|
||||
targetUrl,
|
||||
runtimeDir,
|
||||
});
|
||||
|
||||
console.log(
|
||||
JSON.stringify(
|
||||
{
|
||||
@@ -1515,6 +1782,7 @@ async function main() {
|
||||
hostProfiles,
|
||||
oldDaemonFailClosedAndBrowseLocally: "passed",
|
||||
routedHost,
|
||||
crossHostBoundary,
|
||||
artifactDir,
|
||||
},
|
||||
null,
|
||||
|
||||
@@ -258,6 +258,7 @@ async function settleDesktopStartup(page, { approveSeededPlugin = false } = {})
|
||||
}
|
||||
|
||||
const CSP_PAGE_PATH = "/csp-no-eval";
|
||||
const UPLOAD_FIXTURE_PATH = "/upload-fixture";
|
||||
|
||||
async function startTargetPage() {
|
||||
const fillFixture = await buildFillFixture();
|
||||
@@ -281,6 +282,19 @@ async function startTargetPage() {
|
||||
response.end(focusFixture);
|
||||
return;
|
||||
}
|
||||
if (request.url === UPLOAD_FIXTURE_PATH) {
|
||||
response.writeHead(200, { "content-type": "text/html; charset=utf-8" });
|
||||
response.end(`<!doctype html>
|
||||
<html>
|
||||
<head><title>Upload fixture</title></head>
|
||||
<body>
|
||||
<h1>Upload fixture</h1>
|
||||
<label for="file-upload">File upload</label>
|
||||
<input id="file-upload" type="file" />
|
||||
</body>
|
||||
</html>`);
|
||||
return;
|
||||
}
|
||||
if (request.url === CSP_PAGE_PATH) {
|
||||
response.writeHead(200, {
|
||||
"content-type": "text/html; charset=utf-8",
|
||||
@@ -565,6 +579,88 @@ async function verifyEvaluateOnPageWithoutUnsafeEval(client, targetUrl) {
|
||||
}
|
||||
}
|
||||
|
||||
async function verifyLocalUploadContainment({ client, targetUrl, workspaceDir, runtimeDir }) {
|
||||
const allowedPath = path.join(workspaceDir, "allowed-upload.txt");
|
||||
const outsideDir = path.join(runtimeDir, "outside-upload-target");
|
||||
const outsideFile = path.join(outsideDir, "outside.txt");
|
||||
const outsideLink = path.join(workspaceDir, "outside-link.txt");
|
||||
fs.mkdirSync(outsideDir, { recursive: true });
|
||||
fs.writeFileSync(allowedPath, "workspace-upload-ok");
|
||||
fs.writeFileSync(outsideFile, "outside-content");
|
||||
fs.symlinkSync(outsideFile, outsideLink);
|
||||
|
||||
let browserId = null;
|
||||
try {
|
||||
const created = await callBrowserTool(client, "browser_new_tab", {
|
||||
url: new URL(UPLOAD_FIXTURE_PATH, targetUrl).href,
|
||||
});
|
||||
browserId = created.browserId;
|
||||
assert(
|
||||
typeof browserId === "string",
|
||||
"browser_new_tab returned no browserId for upload fixture",
|
||||
);
|
||||
await callBrowserTool(client, "browser_wait", {
|
||||
browserId,
|
||||
text: "Upload fixture",
|
||||
timeoutMs: 15_000,
|
||||
});
|
||||
const snapshot = await callBrowserTool(client, "browser_snapshot", { browserId });
|
||||
const refMatch = snapshot.snapshot.match(/File upload"[^\n]*ref=(@e\d+)/);
|
||||
assert(
|
||||
refMatch,
|
||||
`Could not find file input ref in upload fixture snapshot:\n${snapshot.snapshot}`,
|
||||
);
|
||||
const ref = refMatch[1];
|
||||
|
||||
const uploaded = await callBrowserTool(client, "browser_upload", {
|
||||
browserId,
|
||||
ref,
|
||||
filePaths: ["allowed-upload.txt"],
|
||||
});
|
||||
assert(
|
||||
uploaded.filePaths.length === 1,
|
||||
`Expected 1 uploaded file, got ${JSON.stringify(uploaded)}`,
|
||||
);
|
||||
const readAllowed = await callBrowserTool(client, "browser_evaluate", {
|
||||
browserId,
|
||||
function:
|
||||
"async () => await document.getElementById('file-upload')?.files?.[0]?.text() ?? null",
|
||||
});
|
||||
assert(
|
||||
JSON.parse(readAllowed.resultJson) === "workspace-upload-ok",
|
||||
`Expected uploaded workspace file contents, got ${readAllowed.resultJson}`,
|
||||
);
|
||||
|
||||
await callBrowserTool(client, "browser_evaluate", {
|
||||
browserId,
|
||||
function: "() => { document.getElementById('file-upload').value = ''; return true; }",
|
||||
});
|
||||
const rejected = await client.callTool({
|
||||
name: "browser_upload",
|
||||
args: { browserId, ref, filePaths: ["outside-link.txt"] },
|
||||
});
|
||||
assert(
|
||||
rejected.structuredContent?.ok === false &&
|
||||
rejected.structuredContent?.error?.code === "browser_unsupported",
|
||||
`Expected outside-workspace symlink upload to be rejected, got ${JSON.stringify(rejected.structuredContent)}`,
|
||||
);
|
||||
const remainingFiles = await callBrowserTool(client, "browser_evaluate", {
|
||||
browserId,
|
||||
function: "() => document.getElementById('file-upload')?.files?.length ?? -1",
|
||||
});
|
||||
assert(
|
||||
JSON.parse(remainingFiles.resultJson) === 0,
|
||||
`Expected file input to stay empty after rejected symlink upload, got ${remainingFiles.resultJson}`,
|
||||
);
|
||||
return { allowedUpload: "passed", outsideSymlinkRejected: "passed" };
|
||||
} finally {
|
||||
if (browserId) await callBrowserTool(client, "browser_close_tab", { browserId });
|
||||
fs.rmSync(allowedPath, { force: true });
|
||||
fs.rmSync(outsideLink, { force: true });
|
||||
fs.rmSync(outsideDir, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
async function createCallerAgent(daemonPort, workspaceId = workspaceIds[0]) {
|
||||
const transport = new StreamableHTTPClientTransport(
|
||||
new URL(`http://127.0.0.1:${daemonPort}/mcp/agents`),
|
||||
@@ -1675,6 +1771,12 @@ async function main() {
|
||||
typingAgent,
|
||||
artifactDir,
|
||||
});
|
||||
const localUploadContainment = await verifyLocalUploadContainment({
|
||||
client,
|
||||
targetUrl: target.url,
|
||||
workspaceDir: path.join(workspaceRoot, "workspace-1"),
|
||||
runtimeDir,
|
||||
});
|
||||
const focusIsolation = await checkFocusIsolation(client, callerAgentId, typingAgent);
|
||||
const permissions = await checkPermissions(client);
|
||||
const pluginLinks = await checkPluginLinks();
|
||||
@@ -1693,6 +1795,7 @@ async function main() {
|
||||
const profiles = await checkProfiles();
|
||||
writeJson(path.join(artifactDir, "result.json"), {
|
||||
...report,
|
||||
localUploadContainment,
|
||||
focusIsolation,
|
||||
permissions,
|
||||
settingsMemory,
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
import { describe, expect, test, vi } from "vitest";
|
||||
import { executeAutomationCommand, type BrowserRegistry, type TabImage } from "./service.js";
|
||||
import { adaptWebContents, HostSnapshotEngineRegistry } from "./ipc.js";
|
||||
import {
|
||||
adaptWebContents,
|
||||
HostSnapshotEngineRegistry,
|
||||
registerBrowserAutomationIpc,
|
||||
} from "./ipc.js";
|
||||
import type { IsolatedKeyboardInputEvent } from "./trusted-input.js";
|
||||
|
||||
class FakeImage implements TabImage {
|
||||
@@ -315,10 +319,9 @@ describe("browser automation IPC adapter", () => {
|
||||
["next", adaptWebContents(next)],
|
||||
]);
|
||||
const registry: BrowserRegistry = {
|
||||
listRegisteredBrowserIds: () => [...tabs.keys()],
|
||||
listRegisteredBrowserIdsForWorkspace: () => [...tabs.keys()],
|
||||
getTabContents: (id) => tabs.get(id) ?? null,
|
||||
getBrowserWorkspaceId: () => null,
|
||||
getBrowserScope: () => ({ serverId: "server-a", workspaceId: "workspace-a" }),
|
||||
getWorkspaceActiveBrowserId: () => null,
|
||||
};
|
||||
const capture = (browserId: string) =>
|
||||
@@ -326,9 +329,11 @@ describe("browser automation IPC adapter", () => {
|
||||
{
|
||||
type: "browser.automation.execute.request",
|
||||
requestId: browserId,
|
||||
workspaceId: "workspace-a",
|
||||
command: { command: "screenshot", args: { browserId, fullPage: false } },
|
||||
},
|
||||
registry,
|
||||
{ serverId: "server-a", uploadRoot: null },
|
||||
);
|
||||
let closedResult: unknown;
|
||||
const closedCapture = Promise.resolve(capture("closing")).then((result) => {
|
||||
@@ -753,6 +758,48 @@ describe("browser automation IPC adapter", () => {
|
||||
|
||||
warn.mockRestore();
|
||||
});
|
||||
|
||||
test("IPC handler rejects missing or invalid execution context", async () => {
|
||||
let handler: ((event: unknown, ...args: unknown[]) => unknown) | null = null;
|
||||
registerBrowserAutomationIpc({
|
||||
ipc: {
|
||||
handle: (channel, listener) => {
|
||||
if (channel === "paseo:browser:execute-automation-command") {
|
||||
handler = listener;
|
||||
}
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(handler).not.toBeNull();
|
||||
const host = new FakeHostWebContents(99);
|
||||
const request = {
|
||||
type: "browser.automation.execute.request",
|
||||
requestId: "req-ipc-ctx",
|
||||
workspaceId: "ws-1",
|
||||
command: { command: "list_tabs", args: {} },
|
||||
};
|
||||
|
||||
for (const invalidContext of [
|
||||
undefined,
|
||||
null,
|
||||
{},
|
||||
{ serverId: "", uploadRoot: null },
|
||||
{ serverId: " ", uploadRoot: null },
|
||||
{ serverId: "server-a" },
|
||||
{ serverId: "server-a", uploadRoot: "" },
|
||||
]) {
|
||||
const response = await handler!({ sender: host }, request, invalidContext);
|
||||
expect(response).toEqual({
|
||||
requestId: "req-ipc-ctx",
|
||||
ok: false,
|
||||
error: {
|
||||
code: "browser_unsupported",
|
||||
message: expect.stringMatching(/context/i),
|
||||
retryable: false,
|
||||
},
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
class FakeHostWebContents {
|
||||
|
||||
@@ -4,7 +4,12 @@ import type {
|
||||
BrowserAutomationConsoleLogEntry,
|
||||
BrowserAutomationDialogEvent,
|
||||
} from "@getpaseo/protocol/browser-automation/rpc-schemas";
|
||||
import type { TabContents, BrowserRegistry, TabImage } from "./service.js";
|
||||
import type {
|
||||
AutomationExecutionContext,
|
||||
BrowserRegistry,
|
||||
TabContents,
|
||||
TabImage,
|
||||
} from "./service.js";
|
||||
import type { IsolatedKeyboardInputEvent } from "./trusted-input.js";
|
||||
import { CdpSessionQueue } from "./cdp-session-queue.js";
|
||||
import {
|
||||
@@ -23,11 +28,11 @@ import {
|
||||
} from "./focus-guard.js";
|
||||
import { BrowserSnapshotEngine } from "./snapshot-engine.js";
|
||||
import {
|
||||
listRegisteredPaseoBrowserIds,
|
||||
listRegisteredPaseoBrowserIdsForWorkspace,
|
||||
getPaseoBrowserWebContentsForHostWindow,
|
||||
getWorkspaceActivePaseoBrowserIdForHostWindow,
|
||||
getPaseoBrowserWorkspaceId,
|
||||
getPaseoBrowserScope,
|
||||
type BrowserWorkspaceScope,
|
||||
} from "../browser-webviews/index.js";
|
||||
|
||||
const MAX_CONSOLE_MESSAGES_PER_TAB = 200;
|
||||
@@ -449,7 +454,6 @@ function normalizeConsoleMessage(input: {
|
||||
function createRegistry(hostContents: FocusGuardHostWebContents): BrowserRegistry {
|
||||
const hostWebContentsId = hostContents.id;
|
||||
return {
|
||||
listRegisteredBrowserIds: listRegisteredPaseoBrowserIds,
|
||||
listRegisteredBrowserIdsForWorkspace: listRegisteredPaseoBrowserIdsForWorkspace,
|
||||
getTabContents(browserId: string): TabContents | null {
|
||||
const contents = getPaseoBrowserWebContentsForHostWindow(browserId, hostWebContentsId);
|
||||
@@ -464,46 +468,81 @@ function createRegistry(hostContents: FocusGuardHostWebContents): BrowserRegistr
|
||||
}),
|
||||
});
|
||||
},
|
||||
getBrowserWorkspaceId: getPaseoBrowserWorkspaceId,
|
||||
getWorkspaceActiveBrowserId(workspaceId: string): string | null {
|
||||
return getWorkspaceActivePaseoBrowserIdForHostWindow(workspaceId, hostWebContentsId);
|
||||
getBrowserScope: getPaseoBrowserScope,
|
||||
getWorkspaceActiveBrowserId(scope: BrowserWorkspaceScope): string | null {
|
||||
return getWorkspaceActivePaseoBrowserIdForHostWindow(scope, hostWebContentsId);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function parseAutomationExecutionContext(rawContext: unknown): AutomationExecutionContext | null {
|
||||
if (typeof rawContext !== "object" || rawContext === null || Array.isArray(rawContext)) {
|
||||
return null;
|
||||
}
|
||||
const record = rawContext as Record<string, unknown>;
|
||||
if (typeof record.serverId !== "string" || record.serverId.trim().length === 0) {
|
||||
return null;
|
||||
}
|
||||
if (
|
||||
record.uploadRoot !== null &&
|
||||
(typeof record.uploadRoot !== "string" || record.uploadRoot.trim().length === 0)
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
serverId: record.serverId.trim(),
|
||||
uploadRoot: typeof record.uploadRoot === "string" ? record.uploadRoot.trim() : null,
|
||||
};
|
||||
}
|
||||
|
||||
export function registerBrowserAutomationIpc(options?: { ipc?: IpcHandlerRegistry }): void {
|
||||
const ipc = options?.ipc ?? ipcMain;
|
||||
|
||||
ipc.handle("paseo:browser:execute-automation-command", async (event, rawRequest: unknown) => {
|
||||
const hostContents = (event as { sender?: FocusGuardHostWebContents }).sender;
|
||||
const hostWebContentsId = hostContents?.id;
|
||||
if (!hostContents || typeof hostWebContentsId !== "number") {
|
||||
return {
|
||||
requestId: readRequestId(rawRequest),
|
||||
ok: false as const,
|
||||
error: {
|
||||
code: "browser_unsupported" as const,
|
||||
message: "Browser automation requires a host window.",
|
||||
},
|
||||
};
|
||||
}
|
||||
const registry = createRegistry(hostContents);
|
||||
const parsed = BrowserAutomationExecuteRequestSchema.safeParse(rawRequest);
|
||||
if (!parsed.success) {
|
||||
return {
|
||||
requestId: readRequestId(rawRequest),
|
||||
ok: false as const,
|
||||
error: {
|
||||
code: "browser_unsupported" as const,
|
||||
message: `Invalid automation request: ${parsed.error.message}`,
|
||||
retryable: false,
|
||||
},
|
||||
};
|
||||
}
|
||||
return executeAutomationCommand(parsed.data, registry, {
|
||||
snapshotEngine: hostSnapshotEngines.get(hostContents),
|
||||
});
|
||||
});
|
||||
ipc.handle(
|
||||
"paseo:browser:execute-automation-command",
|
||||
async (event, rawRequest: unknown, rawContext: unknown) => {
|
||||
const hostContents = (event as { sender?: FocusGuardHostWebContents }).sender;
|
||||
const hostWebContentsId = hostContents?.id;
|
||||
if (!hostContents || typeof hostWebContentsId !== "number") {
|
||||
return {
|
||||
requestId: readRequestId(rawRequest),
|
||||
ok: false as const,
|
||||
error: {
|
||||
code: "browser_unsupported" as const,
|
||||
message: "Browser automation requires a host window.",
|
||||
},
|
||||
};
|
||||
}
|
||||
const parsedContext = parseAutomationExecutionContext(rawContext);
|
||||
if (!parsedContext) {
|
||||
return {
|
||||
requestId: readRequestId(rawRequest),
|
||||
ok: false as const,
|
||||
error: {
|
||||
code: "browser_unsupported" as const,
|
||||
message: "Invalid automation execution context.",
|
||||
retryable: false,
|
||||
},
|
||||
};
|
||||
}
|
||||
const registry = createRegistry(hostContents);
|
||||
const parsed = BrowserAutomationExecuteRequestSchema.safeParse(rawRequest);
|
||||
if (!parsed.success) {
|
||||
return {
|
||||
requestId: readRequestId(rawRequest),
|
||||
ok: false as const,
|
||||
error: {
|
||||
code: "browser_unsupported" as const,
|
||||
message: `Invalid automation request: ${parsed.error.message}`,
|
||||
retryable: false,
|
||||
},
|
||||
};
|
||||
}
|
||||
return executeAutomationCommand(parsed.data, registry, parsedContext, {
|
||||
snapshotEngine: hostSnapshotEngines.get(hostContents),
|
||||
});
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
function readRequestId(rawRequest: unknown): string {
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import { resolve as resolvePath } from "node:path";
|
||||
import { mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join as joinPath } from "node:path";
|
||||
import { createContext, runInContext } from "node:vm";
|
||||
|
||||
import { describe, expect, test, vi } from "vitest";
|
||||
@@ -8,15 +10,24 @@ import type {
|
||||
BrowserAutomationDialogEvent,
|
||||
BrowserAutomationExecuteRequest,
|
||||
} from "@getpaseo/protocol/browser-automation/rpc-schemas";
|
||||
import type { BrowserWorkspaceScope } from "../browser-webviews/registry.js";
|
||||
import { BrowserSnapshotEngine } from "./snapshot-engine.js";
|
||||
import type { BrowserRegistry, TabContents, TabImage } from "./service.js";
|
||||
import type {
|
||||
AutomationExecutionContext,
|
||||
BrowserRegistry,
|
||||
TabContents,
|
||||
TabImage,
|
||||
} from "./service.js";
|
||||
import { executeAutomationCommand } from "./service.js";
|
||||
import type { IsolatedKeyboardInputEvent } from "./trusted-input.js";
|
||||
|
||||
const BROWSER_A = "11111111-1111-4111-8111-111111111111";
|
||||
const BROWSER_B = "22222222-2222-4222-8222-222222222222";
|
||||
const SERVER_A = "server-a";
|
||||
const SERVER_B = "server-b";
|
||||
const WORKSPACE_A = "workspace-a";
|
||||
const WORKSPACE_B = "workspace-b";
|
||||
const DEFAULT_CONTEXT: AutomationExecutionContext = { serverId: SERVER_A, uploadRoot: null };
|
||||
|
||||
class FakeImage implements TabImage {
|
||||
public constructor(
|
||||
@@ -316,37 +327,49 @@ class FakeTab implements TabContents {
|
||||
}
|
||||
|
||||
class FakeRegistry implements BrowserRegistry {
|
||||
private readonly tabs = new Map<string, { workspaceId: string; tab: FakeTab }>();
|
||||
private readonly activeBrowserIdsByWorkspace = new Map<string, string>();
|
||||
private readonly tabs = new Map<string, { scope: BrowserWorkspaceScope; tab: FakeTab }>();
|
||||
private readonly activeBrowserIdsByScope = new Map<string, string>();
|
||||
|
||||
public register(browserId: string, workspaceId: string, tab: FakeTab): void {
|
||||
this.tabs.set(browserId, { workspaceId, tab });
|
||||
public register(
|
||||
browserId: string,
|
||||
workspaceId: string,
|
||||
tab: FakeTab,
|
||||
serverId: string = SERVER_A,
|
||||
): void {
|
||||
this.tabs.set(browserId, { scope: { serverId, workspaceId }, tab });
|
||||
}
|
||||
|
||||
public setActiveBrowser(workspaceId: string, browserId: string): void {
|
||||
this.activeBrowserIdsByWorkspace.set(workspaceId, browserId);
|
||||
public setActiveBrowser(
|
||||
workspaceId: string,
|
||||
browserId: string,
|
||||
serverId: string = SERVER_A,
|
||||
): void {
|
||||
this.activeBrowserIdsByScope.set(this.scopeKey({ serverId, workspaceId }), browserId);
|
||||
}
|
||||
|
||||
public listRegisteredBrowserIds(): string[] {
|
||||
return Array.from(this.tabs.keys());
|
||||
}
|
||||
|
||||
public listRegisteredBrowserIdsForWorkspace(workspaceId: string): string[] {
|
||||
public listRegisteredBrowserIdsForWorkspace(scope: BrowserWorkspaceScope): string[] {
|
||||
return Array.from(this.tabs.entries())
|
||||
.filter((entry) => entry[1].workspaceId === workspaceId)
|
||||
.map((entry) => entry[0]);
|
||||
.filter(
|
||||
([, entry]) =>
|
||||
entry.scope.serverId === scope.serverId && entry.scope.workspaceId === scope.workspaceId,
|
||||
)
|
||||
.map(([browserId]) => browserId);
|
||||
}
|
||||
|
||||
public getTabContents(browserId: string): TabContents | null {
|
||||
return this.tabs.get(browserId)?.tab ?? null;
|
||||
}
|
||||
|
||||
public getBrowserWorkspaceId(browserId: string): string | null {
|
||||
return this.tabs.get(browserId)?.workspaceId ?? null;
|
||||
public getBrowserScope(browserId: string): BrowserWorkspaceScope | null {
|
||||
return this.tabs.get(browserId)?.scope ?? null;
|
||||
}
|
||||
|
||||
public getWorkspaceActiveBrowserId(workspaceId: string): string | null {
|
||||
return this.activeBrowserIdsByWorkspace.get(workspaceId) ?? null;
|
||||
public getWorkspaceActiveBrowserId(scope: BrowserWorkspaceScope): string | null {
|
||||
return this.activeBrowserIdsByScope.get(this.scopeKey(scope)) ?? null;
|
||||
}
|
||||
|
||||
private scopeKey(scope: BrowserWorkspaceScope): string {
|
||||
return JSON.stringify([scope.serverId, scope.workspaceId]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -356,17 +379,29 @@ class BrowserAutomationHarness {
|
||||
public readonly tab = new FakeTab(1, "https://a.test/form", "Fixture");
|
||||
|
||||
public constructor() {
|
||||
this.registry.register(BROWSER_A, WORKSPACE_A, this.tab);
|
||||
this.registry.setActiveBrowser(WORKSPACE_A, BROWSER_A);
|
||||
this.registry.register(BROWSER_A, WORKSPACE_A, this.tab, SERVER_A);
|
||||
this.registry.setActiveBrowser(WORKSPACE_A, BROWSER_A, SERVER_A);
|
||||
}
|
||||
|
||||
public async execute(
|
||||
command: BrowserAutomationCommand,
|
||||
input: { requestId?: string; workspaceId?: string; cwd?: string } = {},
|
||||
input: {
|
||||
requestId?: string;
|
||||
workspaceId?: string;
|
||||
cwd?: string;
|
||||
serverId?: string;
|
||||
uploadRoot?: string | null;
|
||||
} = {},
|
||||
) {
|
||||
return executeAutomationCommand(automationRequest(command, input), this.registry, {
|
||||
snapshotEngine: this.snapshotEngine,
|
||||
});
|
||||
return executeAutomationCommand(
|
||||
automationRequest(command, input),
|
||||
this.registry,
|
||||
{
|
||||
serverId: input.serverId ?? SERVER_A,
|
||||
uploadRoot: input.uploadRoot ?? null,
|
||||
},
|
||||
{ snapshotEngine: this.snapshotEngine },
|
||||
);
|
||||
}
|
||||
|
||||
public async snapshot() {
|
||||
@@ -559,38 +594,76 @@ function requireSnapshotRefs(result: Awaited<ReturnType<BrowserAutomationHarness
|
||||
}
|
||||
|
||||
describe("executeAutomationCommand", () => {
|
||||
test("list tabs without a workspace reports every live registered tab", () => {
|
||||
test.each([
|
||||
{
|
||||
label: "list_tabs",
|
||||
command: { command: "list_tabs", args: {} } as BrowserAutomationCommand,
|
||||
},
|
||||
{
|
||||
label: "snapshot",
|
||||
command: { command: "snapshot", args: { browserId: BROWSER_A } } as BrowserAutomationCommand,
|
||||
},
|
||||
{
|
||||
label: "evaluate",
|
||||
command: {
|
||||
command: "evaluate",
|
||||
args: { browserId: BROWSER_A, function: "() => document.title" },
|
||||
} as BrowserAutomationCommand,
|
||||
},
|
||||
{
|
||||
label: "click",
|
||||
command: {
|
||||
command: "click",
|
||||
args: { browserId: BROWSER_A, ref: "@e1" },
|
||||
} as BrowserAutomationCommand,
|
||||
},
|
||||
{
|
||||
label: "upload",
|
||||
command: {
|
||||
command: "upload",
|
||||
args: { browserId: BROWSER_A, ref: "@e1", filePaths: ["a.txt"] },
|
||||
} as BrowserAutomationCommand,
|
||||
},
|
||||
])("$label fails closed with browser_denied when workspaceId is omitted", async ({ command }) => {
|
||||
const registry = new FakeRegistry();
|
||||
registry.register(BROWSER_A, WORKSPACE_A, new FakeTab(1, "https://a.test", "A"));
|
||||
registry.register(BROWSER_B, WORKSPACE_B, new FakeTab(2, "https://b.test", "B"));
|
||||
registry.register(BROWSER_A, WORKSPACE_A, new FakeTab(1, "https://a.test", "A"), SERVER_A);
|
||||
|
||||
const result = executeAutomationCommand(
|
||||
automationRequest(
|
||||
{ command: "list_tabs", args: {} },
|
||||
{ requestId: "req-list", workspaceId: "" },
|
||||
),
|
||||
const result = await executeAutomationCommand(
|
||||
automationRequest(command, { requestId: "req-missing-ws", workspaceId: "" }),
|
||||
registry,
|
||||
DEFAULT_CONTEXT,
|
||||
);
|
||||
|
||||
expect(result).toEqual({
|
||||
requestId: "req-list",
|
||||
requestId: "req-missing-ws",
|
||||
ok: false,
|
||||
error: {
|
||||
code: "browser_denied",
|
||||
message: expect.stringMatching(/workspace/i),
|
||||
retryable: false,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
test("isolates tabs across servers even when workspaceId matches", async () => {
|
||||
const registry = new FakeRegistry();
|
||||
registry.register(BROWSER_A, WORKSPACE_A, new FakeTab(1, "https://a.test", "A"), SERVER_A);
|
||||
registry.register(BROWSER_B, WORKSPACE_A, new FakeTab(2, "https://b.test", "B"), SERVER_B);
|
||||
|
||||
const listed = await executeAutomationCommand(
|
||||
automationRequest({ command: "list_tabs", args: {} }, { requestId: "req-list-b" }),
|
||||
registry,
|
||||
{ serverId: SERVER_B, uploadRoot: null },
|
||||
);
|
||||
expect(listed).toEqual({
|
||||
requestId: "req-list-b",
|
||||
ok: true,
|
||||
result: {
|
||||
command: "list_tabs",
|
||||
tabs: [
|
||||
{
|
||||
browserId: BROWSER_A,
|
||||
workspaceId: WORKSPACE_A,
|
||||
url: "https://a.test",
|
||||
title: "A",
|
||||
isActive: false,
|
||||
isLoading: false,
|
||||
canGoBack: true,
|
||||
canGoForward: false,
|
||||
},
|
||||
{
|
||||
browserId: BROWSER_B,
|
||||
workspaceId: WORKSPACE_B,
|
||||
workspaceId: WORKSPACE_A,
|
||||
url: "https://b.test",
|
||||
title: "B",
|
||||
isActive: false,
|
||||
@@ -601,6 +674,24 @@ describe("executeAutomationCommand", () => {
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
const crossHostSnapshot = await executeAutomationCommand(
|
||||
automationRequest(
|
||||
{ command: "snapshot", args: { browserId: BROWSER_A } },
|
||||
{ requestId: "req-cross-host" },
|
||||
),
|
||||
registry,
|
||||
{ serverId: SERVER_B, uploadRoot: null },
|
||||
);
|
||||
expect(crossHostSnapshot).toEqual({
|
||||
requestId: "req-cross-host",
|
||||
ok: false,
|
||||
error: {
|
||||
code: "browser_tab_not_found",
|
||||
message: `No browser tab found for ID: ${BROWSER_A}`,
|
||||
retryable: false,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
test("list tabs filters destroyed tabs out of the visible tab list", () => {
|
||||
@@ -615,6 +706,7 @@ describe("executeAutomationCommand", () => {
|
||||
const result = executeAutomationCommand(
|
||||
automationRequest({ command: "list_tabs", args: {} }, { requestId: "req-live" }),
|
||||
registry,
|
||||
DEFAULT_CONTEXT,
|
||||
);
|
||||
|
||||
expect(result).toEqual({
|
||||
@@ -642,6 +734,7 @@ describe("executeAutomationCommand", () => {
|
||||
const result = executeAutomationCommand(
|
||||
automationRequest({ command: "list_tabs", args: {} }, { requestId: "req-empty" }),
|
||||
new FakeRegistry(),
|
||||
DEFAULT_CONTEXT,
|
||||
);
|
||||
|
||||
expect(result).toEqual({
|
||||
@@ -661,6 +754,7 @@ describe("executeAutomationCommand", () => {
|
||||
{ requestId: "req-snapshot" },
|
||||
),
|
||||
registry,
|
||||
DEFAULT_CONTEXT,
|
||||
);
|
||||
|
||||
expect(result).toEqual({
|
||||
@@ -686,6 +780,7 @@ describe("executeAutomationCommand", () => {
|
||||
{ requestId: "req-snapshot" },
|
||||
),
|
||||
registry,
|
||||
DEFAULT_CONTEXT,
|
||||
);
|
||||
|
||||
expect(result).toEqual({
|
||||
@@ -1375,6 +1470,7 @@ describe("executeAutomationCommand", () => {
|
||||
{ requestId: "req-back" },
|
||||
),
|
||||
browser.registry,
|
||||
DEFAULT_CONTEXT,
|
||||
);
|
||||
const forward = await executeAutomationCommand(
|
||||
automationRequest(
|
||||
@@ -1382,6 +1478,7 @@ describe("executeAutomationCommand", () => {
|
||||
{ requestId: "req-forward" },
|
||||
),
|
||||
browser.registry,
|
||||
DEFAULT_CONTEXT,
|
||||
);
|
||||
const reload = await executeAutomationCommand(
|
||||
automationRequest(
|
||||
@@ -1389,6 +1486,7 @@ describe("executeAutomationCommand", () => {
|
||||
{ requestId: "req-reload" },
|
||||
),
|
||||
browser.registry,
|
||||
DEFAULT_CONTEXT,
|
||||
);
|
||||
|
||||
expect(back).toEqual({
|
||||
@@ -1966,6 +2064,7 @@ describe("executeAutomationCommand", () => {
|
||||
args: { browserId: BROWSER_A },
|
||||
}),
|
||||
registry,
|
||||
DEFAULT_CONTEXT,
|
||||
);
|
||||
await firstTab.waitForCaptureStart(1);
|
||||
|
||||
@@ -1978,6 +2077,7 @@ describe("executeAutomationCommand", () => {
|
||||
{ requestId: "req-screenshot-2" },
|
||||
),
|
||||
registry,
|
||||
DEFAULT_CONTEXT,
|
||||
);
|
||||
await Promise.resolve();
|
||||
|
||||
@@ -2164,134 +2264,171 @@ describe("executeAutomationCommand", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
test("upload resolves workspace files before setting them on the file input", async () => {
|
||||
const browser = new BrowserAutomationHarness();
|
||||
browser.tab.snapshotNodes = [
|
||||
{
|
||||
role: "textbox",
|
||||
tagName: "input",
|
||||
name: "Upload",
|
||||
ref: "@e1",
|
||||
},
|
||||
];
|
||||
const workspaceRoot = resolvePath("/workspace/project");
|
||||
test("upload resolves regular workspace files inside uploadRoot, including subdirectory cwd", async () => {
|
||||
const tempRoot = mkdtempSync(joinPath(tmpdir(), "paseo-upload-test-"));
|
||||
try {
|
||||
const workspaceRoot = joinPath(tempRoot, "workspace");
|
||||
const subDir = joinPath(workspaceRoot, "packages", "web");
|
||||
mkdirSync(joinPath(subDir, "uploads"), { recursive: true });
|
||||
const filePath = joinPath(subDir, "uploads", "a.txt");
|
||||
writeFileSync(filePath, "hello");
|
||||
const canonicalFilePath = realpathSync(filePath);
|
||||
|
||||
await browser.snapshot();
|
||||
const result = await browser.execute(
|
||||
{
|
||||
command: "upload",
|
||||
args: { browserId: BROWSER_A, ref: "@e1", filePaths: ["uploads/a.txt"] },
|
||||
},
|
||||
{ cwd: workspaceRoot },
|
||||
);
|
||||
|
||||
expect(result).toEqual({
|
||||
requestId: "req-upload",
|
||||
ok: true,
|
||||
result: {
|
||||
command: "upload",
|
||||
browserId: BROWSER_A,
|
||||
ref: "@e1",
|
||||
filePaths: [resolvePath(workspaceRoot, "uploads/a.txt")],
|
||||
},
|
||||
});
|
||||
expect(browser.tab.debugCommands).toEqual([
|
||||
{
|
||||
command: "Runtime.evaluate",
|
||||
params: {
|
||||
expression: expect.stringContaining('"@e1"'),
|
||||
objectGroup: "paseo-browser-automation",
|
||||
returnByValue: false,
|
||||
const browser = new BrowserAutomationHarness();
|
||||
browser.tab.snapshotNodes = [
|
||||
{
|
||||
role: "textbox",
|
||||
tagName: "input",
|
||||
name: "Upload",
|
||||
ref: "@e1",
|
||||
},
|
||||
},
|
||||
{ command: "DOM.describeNode", params: { objectId: "object-1" } },
|
||||
{
|
||||
command: "DOM.setFileInputFiles",
|
||||
params: { backendNodeId: 2, files: [resolvePath(workspaceRoot, "uploads/a.txt")] },
|
||||
},
|
||||
]);
|
||||
];
|
||||
|
||||
await browser.snapshot();
|
||||
const result = await browser.execute(
|
||||
{
|
||||
command: "upload",
|
||||
args: { browserId: BROWSER_A, ref: "@e1", filePaths: ["uploads/a.txt"] },
|
||||
},
|
||||
{ cwd: subDir, uploadRoot: workspaceRoot },
|
||||
);
|
||||
|
||||
expect(result).toEqual({
|
||||
requestId: "req-upload",
|
||||
ok: true,
|
||||
result: {
|
||||
command: "upload",
|
||||
browserId: BROWSER_A,
|
||||
ref: "@e1",
|
||||
filePaths: [canonicalFilePath],
|
||||
},
|
||||
});
|
||||
expect(browser.tab.debugCommands).toEqual([
|
||||
{
|
||||
command: "Runtime.evaluate",
|
||||
params: {
|
||||
expression: expect.stringContaining('"@e1"'),
|
||||
objectGroup: "paseo-browser-automation",
|
||||
returnByValue: false,
|
||||
},
|
||||
},
|
||||
{ command: "DOM.describeNode", params: { objectId: "object-1" } },
|
||||
{
|
||||
command: "DOM.setFileInputFiles",
|
||||
params: { backendNodeId: 2, files: [canonicalFilePath] },
|
||||
},
|
||||
]);
|
||||
} finally {
|
||||
rmSync(tempRoot, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("upload denies paths outside the agent workspace", async () => {
|
||||
const browser = new BrowserAutomationHarness();
|
||||
browser.tab.snapshotNodes = [
|
||||
{
|
||||
role: "textbox",
|
||||
tagName: "input",
|
||||
name: "Upload",
|
||||
ref: "@e1",
|
||||
},
|
||||
];
|
||||
const workspaceRoot = resolvePath("/workspace/project");
|
||||
test("upload rejects symlinks escaping uploadRoot, outside cwd, directories, and missing files", async () => {
|
||||
const tempRoot = mkdtempSync(joinPath(tmpdir(), "paseo-upload-containment-"));
|
||||
try {
|
||||
const workspaceRoot = joinPath(tempRoot, "workspace");
|
||||
const outsideDir = joinPath(tempRoot, "outside");
|
||||
mkdirSync(joinPath(workspaceRoot, "subdir"), { recursive: true });
|
||||
mkdirSync(outsideDir, { recursive: true });
|
||||
const outsideFile = joinPath(outsideDir, "outside.txt");
|
||||
writeFileSync(outsideFile, "outside-content");
|
||||
const escapeLink = joinPath(workspaceRoot, "escape-link.txt");
|
||||
symlinkSync(outsideFile, escapeLink);
|
||||
|
||||
await browser.snapshot();
|
||||
const result = await browser.execute(
|
||||
{
|
||||
command: "upload",
|
||||
args: { browserId: BROWSER_A, ref: "@e1", filePaths: ["../secret.txt"] },
|
||||
},
|
||||
{ cwd: workspaceRoot },
|
||||
);
|
||||
|
||||
expect(result).toEqual({
|
||||
requestId: "req-upload",
|
||||
ok: false,
|
||||
error: {
|
||||
code: "browser_unsupported",
|
||||
message: "browser_upload only accepts files inside the agent workspace.",
|
||||
retryable: false,
|
||||
},
|
||||
});
|
||||
expect(browser.tab.debugCommands).toEqual([
|
||||
{
|
||||
command: "Runtime.evaluate",
|
||||
params: {
|
||||
expression: expect.stringContaining('"@e1"'),
|
||||
objectGroup: "paseo-browser-automation",
|
||||
returnByValue: false,
|
||||
const cases: Array<{ label: string; cwd?: string; filePaths: string[] }> = [
|
||||
{
|
||||
label: "symlink pointing outside uploadRoot",
|
||||
cwd: workspaceRoot,
|
||||
filePaths: ["escape-link.txt"],
|
||||
},
|
||||
},
|
||||
{ command: "DOM.describeNode", params: { objectId: "object-1" } },
|
||||
]);
|
||||
{
|
||||
label: "relative traversal outside uploadRoot",
|
||||
cwd: workspaceRoot,
|
||||
filePaths: ["../outside/outside.txt"],
|
||||
},
|
||||
{ label: "cwd outside uploadRoot", cwd: outsideDir, filePaths: ["outside.txt"] },
|
||||
{ label: "directory path", cwd: workspaceRoot, filePaths: ["subdir"] },
|
||||
{ label: "missing file", cwd: workspaceRoot, filePaths: ["does-not-exist.txt"] },
|
||||
];
|
||||
|
||||
for (const testCase of cases) {
|
||||
const browser = new BrowserAutomationHarness();
|
||||
browser.tab.snapshotNodes = [
|
||||
{
|
||||
role: "textbox",
|
||||
tagName: "input",
|
||||
name: "Upload",
|
||||
ref: "@e1",
|
||||
},
|
||||
];
|
||||
|
||||
await browser.snapshot();
|
||||
const result = await browser.execute(
|
||||
{
|
||||
command: "upload",
|
||||
args: { browserId: BROWSER_A, ref: "@e1", filePaths: testCase.filePaths },
|
||||
},
|
||||
{ cwd: testCase.cwd, uploadRoot: workspaceRoot },
|
||||
);
|
||||
|
||||
expect(result, testCase.label).toEqual({
|
||||
requestId: "req-upload",
|
||||
ok: false,
|
||||
error: {
|
||||
code: "browser_unsupported",
|
||||
message: "browser_upload only accepts files inside the agent workspace.",
|
||||
retryable: false,
|
||||
},
|
||||
});
|
||||
expect(
|
||||
browser.tab.debugCommands.some((entry) => entry.command === "DOM.setFileInputFiles"),
|
||||
testCase.label,
|
||||
).toBe(false);
|
||||
}
|
||||
} finally {
|
||||
rmSync(tempRoot, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("upload reports missing cwd before setting files on the file input", async () => {
|
||||
const browser = new BrowserAutomationHarness();
|
||||
browser.tab.snapshotNodes = [
|
||||
{
|
||||
role: "textbox",
|
||||
tagName: "input",
|
||||
name: "Upload",
|
||||
ref: "@e1",
|
||||
},
|
||||
];
|
||||
|
||||
await browser.snapshot();
|
||||
const result = await browser.execute({
|
||||
command: "upload",
|
||||
args: { browserId: BROWSER_A, ref: "@e1", filePaths: ["uploads/a.txt"] },
|
||||
});
|
||||
|
||||
expect(result).toEqual({
|
||||
requestId: "req-upload",
|
||||
ok: false,
|
||||
error: {
|
||||
code: "browser_unsupported",
|
||||
message: "browser_upload requires request cwd",
|
||||
retryable: false,
|
||||
},
|
||||
});
|
||||
expect(browser.tab.debugCommands).toEqual([
|
||||
{
|
||||
command: "Runtime.evaluate",
|
||||
params: {
|
||||
expression: expect.stringContaining('"@e1"'),
|
||||
objectGroup: "paseo-browser-automation",
|
||||
returnByValue: false,
|
||||
test("upload fails closed when uploadRoot is null without calling DOM.setFileInputFiles", async () => {
|
||||
const tempRoot = mkdtempSync(joinPath(tmpdir(), "paseo-upload-null-root-"));
|
||||
try {
|
||||
const localFile = joinPath(tempRoot, "local.txt");
|
||||
writeFileSync(localFile, "local");
|
||||
const browser = new BrowserAutomationHarness();
|
||||
browser.tab.snapshotNodes = [
|
||||
{
|
||||
role: "textbox",
|
||||
tagName: "input",
|
||||
name: "Upload",
|
||||
ref: "@e1",
|
||||
},
|
||||
},
|
||||
{ command: "DOM.describeNode", params: { objectId: "object-1" } },
|
||||
]);
|
||||
];
|
||||
|
||||
await browser.snapshot();
|
||||
const result = await browser.execute(
|
||||
{
|
||||
command: "upload",
|
||||
args: { browserId: BROWSER_A, ref: "@e1", filePaths: [localFile] },
|
||||
},
|
||||
{ cwd: tempRoot, uploadRoot: null },
|
||||
);
|
||||
|
||||
expect(result).toEqual({
|
||||
requestId: "req-upload",
|
||||
ok: false,
|
||||
error: {
|
||||
code: "browser_unsupported",
|
||||
message: expect.stringMatching(/local/i),
|
||||
retryable: false,
|
||||
},
|
||||
});
|
||||
expect(
|
||||
browser.tab.debugCommands.some((entry) => entry.command === "DOM.setFileInputFiles"),
|
||||
).toBe(false);
|
||||
} finally {
|
||||
rmSync(tempRoot, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("click and drag bracket CDP pointer presses with focus guard and release on failure", async () => {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { realpathSync, statSync } from "node:fs";
|
||||
import { isAbsolute, relative, resolve as resolvePath } from "node:path";
|
||||
import { Script } from "node:vm";
|
||||
|
||||
@@ -10,6 +11,7 @@ import type {
|
||||
BrowserAutomationExecuteRequest,
|
||||
BrowserAutomationNetworkLogEntry,
|
||||
} from "@getpaseo/protocol/browser-automation/rpc-schemas";
|
||||
import type { BrowserWorkspaceScope } from "../browser-webviews/registry.js";
|
||||
import { waitForActionableTarget, type ActionabilityResult } from "./actionability.js";
|
||||
import type { PointerFocusGuardResult } from "./focus-guard.js";
|
||||
import { BrowserSnapshotEngine } from "./snapshot-engine.js";
|
||||
@@ -74,12 +76,16 @@ export function hasPaintedPixels(image: TabImage): boolean {
|
||||
return false;
|
||||
}
|
||||
|
||||
export interface AutomationExecutionContext {
|
||||
serverId: string;
|
||||
uploadRoot: string | null;
|
||||
}
|
||||
|
||||
export interface BrowserRegistry {
|
||||
listRegisteredBrowserIds(): string[];
|
||||
listRegisteredBrowserIdsForWorkspace(workspaceId: string): string[];
|
||||
listRegisteredBrowserIdsForWorkspace(scope: BrowserWorkspaceScope): string[];
|
||||
getTabContents(browserId: string): TabContents | null;
|
||||
getBrowserWorkspaceId(browserId: string): string | null;
|
||||
getWorkspaceActiveBrowserId(workspaceId: string): string | null;
|
||||
getBrowserScope(browserId: string): BrowserWorkspaceScope | null;
|
||||
getWorkspaceActiveBrowserId(scope: BrowserWorkspaceScope): string | null;
|
||||
}
|
||||
|
||||
export type AutomationCommandPayload = BrowserAutomationExecuteResponse["payload"];
|
||||
@@ -280,21 +286,40 @@ function tabInfoFromContents(
|
||||
export function executeAutomationCommand(
|
||||
request: BrowserAutomationExecuteRequest,
|
||||
registry: BrowserRegistry,
|
||||
context: AutomationExecutionContext,
|
||||
options?: { snapshotEngine?: BrowserSnapshotEngine },
|
||||
): AutomationCommandPayload | Promise<AutomationCommandPayload> {
|
||||
const { requestId, command } = request;
|
||||
const workspaceId = request.workspaceId;
|
||||
const serverId = context.serverId.trim();
|
||||
const workspaceId = request.workspaceId?.trim();
|
||||
if (!serverId || !workspaceId) {
|
||||
return fail(
|
||||
requestId,
|
||||
"browser_denied",
|
||||
"Browser automation requires a server and workspace context.",
|
||||
);
|
||||
}
|
||||
const scope: BrowserWorkspaceScope = { serverId, workspaceId };
|
||||
const snapshotEngine = options?.snapshotEngine ?? defaultSnapshotEngine;
|
||||
const handler = commandHandlers[command.command];
|
||||
|
||||
return handler({ request, command, requestId, workspaceId, registry, snapshotEngine });
|
||||
return handler({
|
||||
request,
|
||||
command,
|
||||
requestId,
|
||||
scope,
|
||||
uploadRoot: context.uploadRoot,
|
||||
registry,
|
||||
snapshotEngine,
|
||||
});
|
||||
}
|
||||
|
||||
interface CommandHandlerContext {
|
||||
request: BrowserAutomationExecuteRequest;
|
||||
command: BrowserAutomationCommand;
|
||||
requestId: string;
|
||||
workspaceId: string | undefined;
|
||||
scope: BrowserWorkspaceScope;
|
||||
uploadRoot: string | null;
|
||||
registry: BrowserRegistry;
|
||||
snapshotEngine: BrowserSnapshotEngine;
|
||||
}
|
||||
@@ -304,25 +329,24 @@ type CommandHandler = (
|
||||
) => AutomationCommandPayload | Promise<AutomationCommandPayload>;
|
||||
|
||||
const commandHandlers: Record<BrowserAutomationCommand["command"], CommandHandler> = {
|
||||
list_tabs: ({ requestId, workspaceId, registry }) =>
|
||||
executeListTabs(requestId, workspaceId, registry),
|
||||
list_tabs: ({ requestId, scope, registry }) => executeListTabs(requestId, scope, registry),
|
||||
new_tab: ({ requestId }) =>
|
||||
fail(requestId, "browser_unsupported", "browser_new_tab is handled by the app runtime."),
|
||||
snapshot: ({ command, requestId, workspaceId, registry, snapshotEngine }) => {
|
||||
snapshot: ({ command, requestId, scope, registry, snapshotEngine }) => {
|
||||
const snapshotCommand = command as Extract<BrowserAutomationCommand, { command: "snapshot" }>;
|
||||
return executeSnapshot(
|
||||
requestId,
|
||||
workspaceId,
|
||||
scope,
|
||||
snapshotCommand.args.browserId,
|
||||
registry,
|
||||
snapshotEngine,
|
||||
);
|
||||
},
|
||||
click: ({ command, requestId, workspaceId, registry, snapshotEngine }) => {
|
||||
click: ({ command, requestId, scope, registry, snapshotEngine }) => {
|
||||
const clickCommand = command as Extract<BrowserAutomationCommand, { command: "click" }>;
|
||||
return executeClick(
|
||||
requestId,
|
||||
workspaceId,
|
||||
scope,
|
||||
clickCommand.args.browserId,
|
||||
clickCommand.args.ref,
|
||||
{
|
||||
@@ -334,11 +358,11 @@ const commandHandlers: Record<BrowserAutomationCommand["command"], CommandHandle
|
||||
snapshotEngine,
|
||||
);
|
||||
},
|
||||
fill: ({ command, requestId, workspaceId, registry, snapshotEngine }) => {
|
||||
fill: ({ command, requestId, scope, registry, snapshotEngine }) => {
|
||||
const fillCommand = command as Extract<BrowserAutomationCommand, { command: "fill" }>;
|
||||
return executeFill(
|
||||
requestId,
|
||||
workspaceId,
|
||||
scope,
|
||||
fillCommand.args.browserId,
|
||||
fillCommand.args.ref,
|
||||
fillCommand.args.value,
|
||||
@@ -346,11 +370,11 @@ const commandHandlers: Record<BrowserAutomationCommand["command"], CommandHandle
|
||||
snapshotEngine,
|
||||
);
|
||||
},
|
||||
wait: ({ command, requestId, workspaceId, registry }) => {
|
||||
wait: ({ command, requestId, scope, registry }) => {
|
||||
const waitCommand = command as Extract<BrowserAutomationCommand, { command: "wait" }>;
|
||||
return executeWait(
|
||||
requestId,
|
||||
workspaceId,
|
||||
scope,
|
||||
waitCommand.args.browserId,
|
||||
{
|
||||
text: waitCommand.args.text,
|
||||
@@ -360,11 +384,11 @@ const commandHandlers: Record<BrowserAutomationCommand["command"], CommandHandle
|
||||
registry,
|
||||
);
|
||||
},
|
||||
type: ({ command, requestId, workspaceId, registry, snapshotEngine }) => {
|
||||
type: ({ command, requestId, scope, registry, snapshotEngine }) => {
|
||||
const typeCommand = command as Extract<BrowserAutomationCommand, { command: "type" }>;
|
||||
return executeType(
|
||||
requestId,
|
||||
workspaceId,
|
||||
scope,
|
||||
typeCommand.args.browserId,
|
||||
typeCommand.args.ref,
|
||||
typeCommand.args.text,
|
||||
@@ -372,11 +396,11 @@ const commandHandlers: Record<BrowserAutomationCommand["command"], CommandHandle
|
||||
snapshotEngine,
|
||||
);
|
||||
},
|
||||
keypress: ({ command, requestId, workspaceId, registry, snapshotEngine }) => {
|
||||
keypress: ({ command, requestId, scope, registry, snapshotEngine }) => {
|
||||
const keypressCommand = command as Extract<BrowserAutomationCommand, { command: "keypress" }>;
|
||||
return executeKeypress(
|
||||
requestId,
|
||||
workspaceId,
|
||||
scope,
|
||||
keypressCommand.args.browserId,
|
||||
keypressCommand.args.ref,
|
||||
keypressCommand.args.key,
|
||||
@@ -384,80 +408,81 @@ const commandHandlers: Record<BrowserAutomationCommand["command"], CommandHandle
|
||||
snapshotEngine,
|
||||
);
|
||||
},
|
||||
navigate: ({ command, requestId, workspaceId, registry, snapshotEngine }) => {
|
||||
navigate: ({ command, requestId, scope, registry, snapshotEngine }) => {
|
||||
const navigateCommand = command as Extract<BrowserAutomationCommand, { command: "navigate" }>;
|
||||
return executeNavigate(
|
||||
requestId,
|
||||
workspaceId,
|
||||
scope,
|
||||
navigateCommand.args.browserId,
|
||||
navigateCommand.args.url,
|
||||
registry,
|
||||
snapshotEngine,
|
||||
);
|
||||
},
|
||||
back: ({ command, requestId, workspaceId, registry, snapshotEngine }) => {
|
||||
back: ({ command, requestId, scope, registry, snapshotEngine }) => {
|
||||
const backCommand = command as Extract<BrowserAutomationCommand, { command: "back" }>;
|
||||
return executeNavigationAction(
|
||||
requestId,
|
||||
workspaceId,
|
||||
scope,
|
||||
backCommand.args.browserId,
|
||||
"back",
|
||||
registry,
|
||||
snapshotEngine,
|
||||
);
|
||||
},
|
||||
forward: ({ command, requestId, workspaceId, registry, snapshotEngine }) => {
|
||||
forward: ({ command, requestId, scope, registry, snapshotEngine }) => {
|
||||
const forwardCommand = command as Extract<BrowserAutomationCommand, { command: "forward" }>;
|
||||
return executeNavigationAction(
|
||||
requestId,
|
||||
workspaceId,
|
||||
scope,
|
||||
forwardCommand.args.browserId,
|
||||
"forward",
|
||||
registry,
|
||||
snapshotEngine,
|
||||
);
|
||||
},
|
||||
reload: ({ command, requestId, workspaceId, registry, snapshotEngine }) => {
|
||||
reload: ({ command, requestId, scope, registry, snapshotEngine }) => {
|
||||
const reloadCommand = command as Extract<BrowserAutomationCommand, { command: "reload" }>;
|
||||
return executeNavigationAction(
|
||||
requestId,
|
||||
workspaceId,
|
||||
scope,
|
||||
reloadCommand.args.browserId,
|
||||
"reload",
|
||||
registry,
|
||||
snapshotEngine,
|
||||
);
|
||||
},
|
||||
screenshot: ({ command, requestId, workspaceId, registry }) => {
|
||||
screenshot: ({ command, requestId, scope, registry }) => {
|
||||
const screenshotCommand = command as Extract<
|
||||
BrowserAutomationCommand,
|
||||
{ command: "screenshot" }
|
||||
>;
|
||||
return executeScreenshot(
|
||||
requestId,
|
||||
workspaceId,
|
||||
scope,
|
||||
screenshotCommand.args.browserId,
|
||||
screenshotCommand.args.fullPage,
|
||||
registry,
|
||||
);
|
||||
},
|
||||
upload: ({ request, command, requestId, workspaceId, registry, snapshotEngine }) => {
|
||||
upload: ({ request, command, requestId, scope, uploadRoot, registry, snapshotEngine }) => {
|
||||
const uploadCommand = command as Extract<BrowserAutomationCommand, { command: "upload" }>;
|
||||
return executeUpload(
|
||||
requestId,
|
||||
request.cwd,
|
||||
workspaceId,
|
||||
uploadRoot,
|
||||
scope,
|
||||
uploadCommand.args.browserId,
|
||||
{ ref: uploadCommand.args.ref, filePaths: uploadCommand.args.filePaths },
|
||||
registry,
|
||||
snapshotEngine,
|
||||
);
|
||||
},
|
||||
select: ({ command, requestId, workspaceId, registry, snapshotEngine }) => {
|
||||
select: ({ command, requestId, scope, registry, snapshotEngine }) => {
|
||||
const selectCommand = command as Extract<BrowserAutomationCommand, { command: "select" }>;
|
||||
return executeSelect(
|
||||
requestId,
|
||||
workspaceId,
|
||||
scope,
|
||||
selectCommand.args.browserId,
|
||||
selectCommand.args.ref,
|
||||
selectCommand.args.value,
|
||||
@@ -465,22 +490,22 @@ const commandHandlers: Record<BrowserAutomationCommand["command"], CommandHandle
|
||||
snapshotEngine,
|
||||
);
|
||||
},
|
||||
hover: ({ command, requestId, workspaceId, registry, snapshotEngine }) => {
|
||||
hover: ({ command, requestId, scope, registry, snapshotEngine }) => {
|
||||
const hoverCommand = command as Extract<BrowserAutomationCommand, { command: "hover" }>;
|
||||
return executeHover(
|
||||
requestId,
|
||||
workspaceId,
|
||||
scope,
|
||||
hoverCommand.args.browserId,
|
||||
hoverCommand.args.ref,
|
||||
registry,
|
||||
snapshotEngine,
|
||||
);
|
||||
},
|
||||
drag: ({ command, requestId, workspaceId, registry, snapshotEngine }) => {
|
||||
drag: ({ command, requestId, scope, registry, snapshotEngine }) => {
|
||||
const dragCommand = command as Extract<BrowserAutomationCommand, { command: "drag" }>;
|
||||
return executeDrag(
|
||||
requestId,
|
||||
workspaceId,
|
||||
scope,
|
||||
dragCommand.args.browserId,
|
||||
dragCommand.args.sourceRef,
|
||||
dragCommand.args.targetRef,
|
||||
@@ -488,21 +513,21 @@ const commandHandlers: Record<BrowserAutomationCommand["command"], CommandHandle
|
||||
snapshotEngine,
|
||||
);
|
||||
},
|
||||
logs: ({ command, requestId, workspaceId, registry }) => {
|
||||
logs: ({ command, requestId, scope, registry }) => {
|
||||
const logsCommand = command as Extract<BrowserAutomationCommand, { command: "logs" }>;
|
||||
return executeLogs(
|
||||
requestId,
|
||||
workspaceId,
|
||||
scope,
|
||||
logsCommand.args.browserId,
|
||||
logsCommand.args.maxEntries,
|
||||
registry,
|
||||
);
|
||||
},
|
||||
evaluate: ({ command, requestId, workspaceId, registry, snapshotEngine }) => {
|
||||
evaluate: ({ command, requestId, scope, registry, snapshotEngine }) => {
|
||||
const evaluateCommand = command as Extract<BrowserAutomationCommand, { command: "evaluate" }>;
|
||||
return executeEvaluate(
|
||||
requestId,
|
||||
workspaceId,
|
||||
scope,
|
||||
evaluateCommand.args.browserId,
|
||||
evaluateCommand.args.function,
|
||||
evaluateCommand.args.ref,
|
||||
@@ -510,11 +535,11 @@ const commandHandlers: Record<BrowserAutomationCommand["command"], CommandHandle
|
||||
snapshotEngine,
|
||||
);
|
||||
},
|
||||
scroll: ({ command, requestId, workspaceId, registry, snapshotEngine }) => {
|
||||
scroll: ({ command, requestId, scope, registry, snapshotEngine }) => {
|
||||
const scrollCommand = command as Extract<BrowserAutomationCommand, { command: "scroll" }>;
|
||||
return executeScroll(
|
||||
requestId,
|
||||
workspaceId,
|
||||
scope,
|
||||
scrollCommand.args.browserId,
|
||||
scrollCommand.args.ref,
|
||||
scrollCommand.args.deltaX,
|
||||
@@ -536,13 +561,11 @@ interface ResolvedTabTarget {
|
||||
|
||||
function executeListTabs(
|
||||
requestId: string,
|
||||
workspaceId: string | undefined,
|
||||
scope: BrowserWorkspaceScope,
|
||||
registry: BrowserRegistry,
|
||||
): AutomationCommandPayload {
|
||||
const browserIds = workspaceId
|
||||
? registry.listRegisteredBrowserIdsForWorkspace(workspaceId)
|
||||
: registry.listRegisteredBrowserIds();
|
||||
const activeBrowserId = workspaceId ? registry.getWorkspaceActiveBrowserId(workspaceId) : null;
|
||||
const browserIds = registry.listRegisteredBrowserIdsForWorkspace(scope);
|
||||
const activeBrowserId = registry.getWorkspaceActiveBrowserId(scope);
|
||||
const tabs: Array<ReturnType<typeof tabInfoFromContents>> = [];
|
||||
|
||||
for (const browserId of browserIds) {
|
||||
@@ -553,7 +576,7 @@ function executeListTabs(
|
||||
browserId,
|
||||
contents,
|
||||
activeBrowserId,
|
||||
registry.getBrowserWorkspaceId(browserId),
|
||||
registry.getBrowserScope(browserId)?.workspaceId ?? null,
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -564,14 +587,14 @@ function executeListTabs(
|
||||
|
||||
async function executeSnapshot(
|
||||
requestId: string,
|
||||
workspaceId: string | undefined,
|
||||
scope: BrowserWorkspaceScope,
|
||||
browserId: string,
|
||||
registry: BrowserRegistry,
|
||||
snapshotEngine: BrowserSnapshotEngine,
|
||||
): Promise<AutomationCommandPayload> {
|
||||
const target = resolveTabTarget({
|
||||
requestId,
|
||||
workspaceId,
|
||||
scope,
|
||||
browserId,
|
||||
registry,
|
||||
});
|
||||
@@ -584,6 +607,7 @@ async function executeSnapshot(
|
||||
browserId: target.browserId,
|
||||
page: target.contents,
|
||||
});
|
||||
const workspaceId = registry.getBrowserScope(target.browserId)?.workspaceId;
|
||||
|
||||
return {
|
||||
requestId,
|
||||
@@ -591,9 +615,7 @@ async function executeSnapshot(
|
||||
result: {
|
||||
command: "snapshot",
|
||||
browserId: target.browserId,
|
||||
...(registry.getBrowserWorkspaceId(target.browserId)
|
||||
? { workspaceId: registry.getBrowserWorkspaceId(target.browserId) ?? undefined }
|
||||
: {}),
|
||||
...(workspaceId ? { workspaceId } : {}),
|
||||
url: target.contents.getURL(),
|
||||
title: target.contents.getTitle(),
|
||||
...snapshot,
|
||||
@@ -604,14 +626,14 @@ async function executeSnapshot(
|
||||
|
||||
async function executeClick(
|
||||
requestId: string,
|
||||
workspaceId: string | undefined,
|
||||
scope: BrowserWorkspaceScope,
|
||||
browserId: string,
|
||||
ref: string,
|
||||
options: ClickInputOptions,
|
||||
registry: BrowserRegistry,
|
||||
snapshotEngine: BrowserSnapshotEngine,
|
||||
): Promise<AutomationCommandPayload> {
|
||||
const target = resolveTabTarget({ requestId, workspaceId, browserId, registry });
|
||||
const target = resolveTabTarget({ requestId, scope, browserId, registry });
|
||||
if ("ok" in target) {
|
||||
return target;
|
||||
}
|
||||
@@ -655,14 +677,14 @@ async function executeClick(
|
||||
|
||||
async function executeFill(
|
||||
requestId: string,
|
||||
workspaceId: string | undefined,
|
||||
scope: BrowserWorkspaceScope,
|
||||
browserId: string,
|
||||
ref: string,
|
||||
value: string,
|
||||
registry: BrowserRegistry,
|
||||
snapshotEngine: BrowserSnapshotEngine,
|
||||
): Promise<AutomationCommandPayload> {
|
||||
const target = resolveTabTarget({ requestId, workspaceId, browserId, registry });
|
||||
const target = resolveTabTarget({ requestId, scope, browserId, registry });
|
||||
if ("ok" in target) {
|
||||
return target;
|
||||
}
|
||||
@@ -682,14 +704,14 @@ async function executeFill(
|
||||
|
||||
async function executeSelect(
|
||||
requestId: string,
|
||||
workspaceId: string | undefined,
|
||||
scope: BrowserWorkspaceScope,
|
||||
browserId: string,
|
||||
ref: string,
|
||||
value: string,
|
||||
registry: BrowserRegistry,
|
||||
snapshotEngine: BrowserSnapshotEngine,
|
||||
): Promise<AutomationCommandPayload> {
|
||||
const target = resolveTabTarget({ requestId, workspaceId, browserId, registry });
|
||||
const target = resolveTabTarget({ requestId, scope, browserId, registry });
|
||||
if ("ok" in target) {
|
||||
return target;
|
||||
}
|
||||
@@ -713,13 +735,13 @@ async function executeSelect(
|
||||
|
||||
async function executeHover(
|
||||
requestId: string,
|
||||
workspaceId: string | undefined,
|
||||
scope: BrowserWorkspaceScope,
|
||||
browserId: string,
|
||||
ref: string,
|
||||
registry: BrowserRegistry,
|
||||
snapshotEngine: BrowserSnapshotEngine,
|
||||
): Promise<AutomationCommandPayload> {
|
||||
const target = resolveTabTarget({ requestId, workspaceId, browserId, registry });
|
||||
const target = resolveTabTarget({ requestId, scope, browserId, registry });
|
||||
if ("ok" in target) {
|
||||
return target;
|
||||
}
|
||||
@@ -758,14 +780,14 @@ async function executeHover(
|
||||
|
||||
async function executeDrag(
|
||||
requestId: string,
|
||||
workspaceId: string | undefined,
|
||||
scope: BrowserWorkspaceScope,
|
||||
browserId: string,
|
||||
sourceRef: string,
|
||||
targetRef: string,
|
||||
registry: BrowserRegistry,
|
||||
snapshotEngine: BrowserSnapshotEngine,
|
||||
): Promise<AutomationCommandPayload> {
|
||||
const target = resolveTabTarget({ requestId, workspaceId, browserId, registry });
|
||||
const target = resolveTabTarget({ requestId, scope, browserId, registry });
|
||||
if ("ok" in target) {
|
||||
return target;
|
||||
}
|
||||
@@ -823,12 +845,12 @@ async function executeDrag(
|
||||
|
||||
async function executeLogs(
|
||||
requestId: string,
|
||||
workspaceId: string | undefined,
|
||||
scope: BrowserWorkspaceScope,
|
||||
browserId: string,
|
||||
maxEntries: number,
|
||||
registry: BrowserRegistry,
|
||||
): Promise<AutomationCommandPayload> {
|
||||
const target = resolveTabTarget({ requestId, workspaceId, browserId, registry });
|
||||
const target = resolveTabTarget({ requestId, scope, browserId, registry });
|
||||
if ("ok" in target) {
|
||||
return target;
|
||||
}
|
||||
@@ -852,14 +874,14 @@ async function executeLogs(
|
||||
|
||||
async function executeEvaluate(
|
||||
requestId: string,
|
||||
workspaceId: string | undefined,
|
||||
scope: BrowserWorkspaceScope,
|
||||
browserId: string,
|
||||
functionSource: string,
|
||||
ref: string | undefined,
|
||||
registry: BrowserRegistry,
|
||||
snapshotEngine: BrowserSnapshotEngine,
|
||||
): Promise<AutomationCommandPayload> {
|
||||
const target = resolveTabTarget({ requestId, workspaceId, browserId, registry });
|
||||
const target = resolveTabTarget({ requestId, scope, browserId, registry });
|
||||
if ("ok" in target) {
|
||||
return target;
|
||||
}
|
||||
@@ -914,7 +936,7 @@ async function executeEvaluate(
|
||||
|
||||
async function executeScroll(
|
||||
requestId: string,
|
||||
workspaceId: string | undefined,
|
||||
scope: BrowserWorkspaceScope,
|
||||
browserId: string,
|
||||
ref: string | undefined,
|
||||
deltaX: number,
|
||||
@@ -922,7 +944,7 @@ async function executeScroll(
|
||||
registry: BrowserRegistry,
|
||||
snapshotEngine: BrowserSnapshotEngine,
|
||||
): Promise<AutomationCommandPayload> {
|
||||
const target = resolveTabTarget({ requestId, workspaceId, browserId, registry });
|
||||
const target = resolveTabTarget({ requestId, scope, browserId, registry });
|
||||
if ("ok" in target) {
|
||||
return target;
|
||||
}
|
||||
@@ -1063,12 +1085,12 @@ async function withPointerFocusGuard<T>(
|
||||
|
||||
async function executeWait(
|
||||
requestId: string,
|
||||
workspaceId: string | undefined,
|
||||
scope: BrowserWorkspaceScope,
|
||||
browserId: string,
|
||||
condition: { text?: string; url?: string; timeoutMs?: number },
|
||||
registry: BrowserRegistry,
|
||||
): Promise<AutomationCommandPayload> {
|
||||
const target = resolveTabTarget({ requestId, workspaceId, browserId, registry });
|
||||
const target = resolveTabTarget({ requestId, scope, browserId, registry });
|
||||
if ("ok" in target) {
|
||||
return target;
|
||||
}
|
||||
@@ -1122,14 +1144,14 @@ async function executeWait(
|
||||
|
||||
async function executeType(
|
||||
requestId: string,
|
||||
workspaceId: string | undefined,
|
||||
scope: BrowserWorkspaceScope,
|
||||
browserId: string,
|
||||
ref: string | undefined,
|
||||
text: string,
|
||||
registry: BrowserRegistry,
|
||||
snapshotEngine: BrowserSnapshotEngine,
|
||||
): Promise<AutomationCommandPayload> {
|
||||
const target = resolveTabTarget({ requestId, workspaceId, browserId, registry });
|
||||
const target = resolveTabTarget({ requestId, scope, browserId, registry });
|
||||
if ("ok" in target) {
|
||||
return target;
|
||||
}
|
||||
@@ -1180,14 +1202,14 @@ async function executeType(
|
||||
|
||||
async function executeKeypress(
|
||||
requestId: string,
|
||||
workspaceId: string | undefined,
|
||||
scope: BrowserWorkspaceScope,
|
||||
browserId: string,
|
||||
ref: string | undefined,
|
||||
key: string,
|
||||
registry: BrowserRegistry,
|
||||
snapshotEngine: BrowserSnapshotEngine,
|
||||
): Promise<AutomationCommandPayload> {
|
||||
const target = resolveTabTarget({ requestId, workspaceId, browserId, registry });
|
||||
const target = resolveTabTarget({ requestId, scope, browserId, registry });
|
||||
if ("ok" in target) {
|
||||
return target;
|
||||
}
|
||||
@@ -1230,13 +1252,13 @@ async function executeKeypress(
|
||||
|
||||
async function executeNavigate(
|
||||
requestId: string,
|
||||
workspaceId: string | undefined,
|
||||
scope: BrowserWorkspaceScope,
|
||||
browserId: string,
|
||||
url: string,
|
||||
registry: BrowserRegistry,
|
||||
snapshotEngine: BrowserSnapshotEngine,
|
||||
): Promise<AutomationCommandPayload> {
|
||||
const target = resolveTabTarget({ requestId, workspaceId, browserId, registry });
|
||||
const target = resolveTabTarget({ requestId, scope, browserId, registry });
|
||||
if ("ok" in target) {
|
||||
return target;
|
||||
}
|
||||
@@ -1260,13 +1282,13 @@ async function executeNavigate(
|
||||
|
||||
async function executeNavigationAction(
|
||||
requestId: string,
|
||||
workspaceId: string | undefined,
|
||||
scope: BrowserWorkspaceScope,
|
||||
browserId: string,
|
||||
action: "back" | "forward" | "reload",
|
||||
registry: BrowserRegistry,
|
||||
snapshotEngine: BrowserSnapshotEngine,
|
||||
): Promise<AutomationCommandPayload> {
|
||||
const target = resolveTabTarget({ requestId, workspaceId, browserId, registry });
|
||||
const target = resolveTabTarget({ requestId, scope, browserId, registry });
|
||||
if ("ok" in target) {
|
||||
return target;
|
||||
}
|
||||
@@ -1295,16 +1317,16 @@ async function executeNavigationAction(
|
||||
|
||||
async function executeScreenshot(
|
||||
requestId: string,
|
||||
workspaceId: string | undefined,
|
||||
scope: BrowserWorkspaceScope,
|
||||
browserId: string,
|
||||
fullPage: boolean,
|
||||
registry: BrowserRegistry,
|
||||
): Promise<AutomationCommandPayload> {
|
||||
if (fullPage) {
|
||||
return executeFullPageScreenshot(requestId, workspaceId, browserId, registry);
|
||||
return executeFullPageScreenshot(requestId, scope, browserId, registry);
|
||||
}
|
||||
|
||||
const target = resolveTabTarget({ requestId, workspaceId, browserId, registry });
|
||||
const target = resolveTabTarget({ requestId, scope, browserId, registry });
|
||||
if ("ok" in target) {
|
||||
return target;
|
||||
}
|
||||
@@ -1397,11 +1419,11 @@ async function getCdpLayoutMetrics(contents: TabContents): Promise<{
|
||||
|
||||
async function executeFullPageScreenshot(
|
||||
requestId: string,
|
||||
workspaceId: string | undefined,
|
||||
scope: BrowserWorkspaceScope,
|
||||
browserId: string,
|
||||
registry: BrowserRegistry,
|
||||
): Promise<AutomationCommandPayload> {
|
||||
const target = resolveTabTarget({ requestId, workspaceId, browserId, registry });
|
||||
const target = resolveTabTarget({ requestId, scope, browserId, registry });
|
||||
if ("ok" in target) {
|
||||
return target;
|
||||
}
|
||||
@@ -1466,17 +1488,25 @@ function isAllowedPageUrl(value: string): boolean {
|
||||
async function executeUpload(
|
||||
requestId: string,
|
||||
cwd: string | undefined,
|
||||
workspaceId: string | undefined,
|
||||
uploadRoot: string | null,
|
||||
scope: BrowserWorkspaceScope,
|
||||
browserId: string,
|
||||
input: { ref: string; filePaths: string[] },
|
||||
registry: BrowserRegistry,
|
||||
snapshotEngine: BrowserSnapshotEngine,
|
||||
): Promise<AutomationCommandPayload> {
|
||||
const target = resolveTabTarget({ requestId, workspaceId, browserId, registry });
|
||||
const target = resolveTabTarget({ requestId, scope, browserId, registry });
|
||||
if ("ok" in target) {
|
||||
return target;
|
||||
}
|
||||
return withDialogCapture(target.contents, async () => {
|
||||
if (!uploadRoot) {
|
||||
return fail(
|
||||
requestId,
|
||||
"browser_unsupported",
|
||||
"browser_upload is only supported for local workspaces.",
|
||||
);
|
||||
}
|
||||
if (!target.contents.sendDebugCommand) {
|
||||
return fail(requestId, "browser_unsupported", "browser_upload requires CDP");
|
||||
}
|
||||
@@ -1503,11 +1533,7 @@ async function executeUpload(
|
||||
if (typeof backendNodeId !== "number" || backendNodeId <= 0) {
|
||||
return staleRefFailure(requestId, input.ref);
|
||||
}
|
||||
const workspaceRoot = resolveUploadWorkspaceRoot(cwd);
|
||||
if (!workspaceRoot) {
|
||||
return fail(requestId, "browser_unsupported", "browser_upload requires request cwd");
|
||||
}
|
||||
const filePaths = resolveWorkspaceFilePaths(input.filePaths, workspaceRoot);
|
||||
const filePaths = resolveWorkspaceFilePaths(input.filePaths, uploadRoot, cwd);
|
||||
if (!filePaths) {
|
||||
return fail(
|
||||
requestId,
|
||||
@@ -1533,17 +1559,51 @@ async function executeUpload(
|
||||
});
|
||||
}
|
||||
|
||||
function resolveUploadWorkspaceRoot(cwd: string | undefined): string | null {
|
||||
return cwd ? resolvePath(cwd) : null;
|
||||
}
|
||||
|
||||
function resolveWorkspaceFilePaths(filePaths: string[], workspaceRoot: string): string[] | null {
|
||||
const resolvedPaths = filePaths.map((filePath) =>
|
||||
isAbsolute(filePath) ? resolvePath(filePath) : resolvePath(workspaceRoot, filePath),
|
||||
);
|
||||
if (resolvedPaths.some((filePath) => !isPathInsideDirectory(filePath, workspaceRoot))) {
|
||||
function resolveWorkspaceFilePaths(
|
||||
filePaths: string[],
|
||||
uploadRoot: string,
|
||||
cwd: string | undefined,
|
||||
): string[] | null {
|
||||
let canonicalRoot: string;
|
||||
try {
|
||||
canonicalRoot = realpathSync(uploadRoot);
|
||||
if (!statSync(canonicalRoot).isDirectory()) {
|
||||
return null;
|
||||
}
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
|
||||
let baseDir = canonicalRoot;
|
||||
const trimmedCwd = cwd?.trim();
|
||||
if (trimmedCwd) {
|
||||
try {
|
||||
const canonicalCwd = realpathSync(trimmedCwd);
|
||||
if (!isPathInsideDirectory(canonicalCwd, canonicalRoot)) {
|
||||
return null;
|
||||
}
|
||||
baseDir = canonicalCwd;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
const resolvedPaths: string[] = [];
|
||||
for (const filePath of filePaths) {
|
||||
const candidate = isAbsolute(filePath) ? resolvePath(filePath) : resolvePath(baseDir, filePath);
|
||||
try {
|
||||
const canonicalPath = realpathSync(candidate);
|
||||
if (
|
||||
!isPathInsideDirectory(canonicalPath, canonicalRoot) ||
|
||||
!statSync(canonicalPath).isFile()
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
resolvedPaths.push(canonicalPath);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
return resolvedPaths;
|
||||
}
|
||||
|
||||
@@ -1774,12 +1834,17 @@ const NETWORK_PERFORMANCE_SCRIPT = String.raw`(() => {
|
||||
|
||||
function resolveTabTarget(input: {
|
||||
requestId: string;
|
||||
workspaceId: string | undefined;
|
||||
scope: BrowserWorkspaceScope;
|
||||
browserId: string;
|
||||
registry: BrowserRegistry;
|
||||
}): ResolvedTabTarget | FailurePayload {
|
||||
const { requestId, workspaceId, browserId, registry } = input;
|
||||
if (workspaceId && registry.getBrowserWorkspaceId(browserId) !== workspaceId) {
|
||||
const { requestId, scope, browserId, registry } = input;
|
||||
const tabScope = registry.getBrowserScope(browserId);
|
||||
if (
|
||||
!tabScope ||
|
||||
tabScope.serverId !== scope.serverId ||
|
||||
tabScope.workspaceId !== scope.workspaceId
|
||||
) {
|
||||
return fail(requestId, "browser_tab_not_found", `No browser tab found for ID: ${browserId}`);
|
||||
}
|
||||
|
||||
|
||||
@@ -451,4 +451,165 @@ describe("BrowserProxyManager", () => {
|
||||
}),
|
||||
).rejects.toThrow(/profile/i);
|
||||
});
|
||||
|
||||
function createGate() {
|
||||
let resolve!: () => void;
|
||||
const promise = new Promise<void>((res) => {
|
||||
resolve = res;
|
||||
});
|
||||
return { promise, resolve };
|
||||
}
|
||||
|
||||
test("releaseProfile revokes host partitions, blocks in-flight route and bind calls, and allows clean re-binding", async () => {
|
||||
const sessionsByPartition = new Map<string, ReturnType<typeof createFakeSession>>();
|
||||
const statuses: BrowserProxyStatusSnapshot[] = [];
|
||||
let setProxyCallsForWork = 0;
|
||||
let resolveProxyCallsForWork = 0;
|
||||
let bindStartedGate: ReturnType<typeof createGate> | null = null;
|
||||
let releaseBindGate: ReturnType<typeof createGate> | null = null;
|
||||
let routeStartedGate: ReturnType<typeof createGate> | null = null;
|
||||
let releaseRouteGate: ReturnType<typeof createGate> | null = null;
|
||||
|
||||
const route = { kind: "host", serverId: "remote-release" } as const;
|
||||
const defaultPartition = getBrowserPartition(route, "default");
|
||||
const workPartition = getBrowserPartition(route, "work");
|
||||
const target = "tcp://10.0.0.22:6767";
|
||||
|
||||
const manager = createBrowserProxyManager({
|
||||
verifySocketOwner: async () => true,
|
||||
requestTicket: async () => "ticket",
|
||||
openTunnelWire: async () => {
|
||||
if (routeStartedGate && releaseRouteGate) {
|
||||
routeStartedGate.resolve();
|
||||
await releaseRouteGate.promise;
|
||||
}
|
||||
return createEchoTunnelWire().wire;
|
||||
},
|
||||
getSessionForPartition: (partition) => {
|
||||
let session = sessionsByPartition.get(partition);
|
||||
if (!session) {
|
||||
const base = createFakeSession();
|
||||
session = {
|
||||
...base,
|
||||
setProxy: async (config) => {
|
||||
if (partition === workPartition) {
|
||||
setProxyCallsForWork += 1;
|
||||
if (bindStartedGate && releaseBindGate) {
|
||||
bindStartedGate.resolve();
|
||||
await releaseBindGate.promise;
|
||||
}
|
||||
}
|
||||
await base.setProxy(config);
|
||||
session!.lastProxyConfig = base.lastProxyConfig;
|
||||
},
|
||||
resolveProxy: async (url) => {
|
||||
if (partition === workPartition) {
|
||||
resolveProxyCallsForWork += 1;
|
||||
}
|
||||
return base.resolveProxy(url);
|
||||
},
|
||||
};
|
||||
sessionsByPartition.set(partition, session);
|
||||
}
|
||||
return session;
|
||||
},
|
||||
onStatusChange: (status) => statuses.push(status),
|
||||
});
|
||||
managers.push(manager);
|
||||
|
||||
await manager.ensureHostProxy({ serverId: "remote-release", target });
|
||||
await manager.ensureHostProxy({ serverId: "remote-release", target, profileSlug: "work" });
|
||||
|
||||
const defaultSession = sessionsByPartition.get(defaultPartition)!;
|
||||
const workSession = sessionsByPartition.get(workPartition)!;
|
||||
expect(manager.isAllowedHostPartition(workPartition)).toBe(true);
|
||||
expect(manager.isProxiedSession(workSession)).toBe(true);
|
||||
expect(manager.listKnownPartitions()).toContain(workPartition);
|
||||
expect(setProxyCallsForWork).toBe(1);
|
||||
expect(resolveProxyCallsForWork).toBe(2);
|
||||
|
||||
const statusCountBeforeRelease = statuses.length;
|
||||
manager.releaseProfile("work");
|
||||
|
||||
expect(manager.isAllowedHostPartition(workPartition)).toBe(false);
|
||||
expect(manager.isProxiedSession(workSession)).toBe(false);
|
||||
expect(manager.listKnownPartitions()).not.toContain(workPartition);
|
||||
expect(manager.getHostProxyStatus("remote-release")?.profilePartitions).toEqual({
|
||||
default: defaultPartition,
|
||||
});
|
||||
expect(statuses.length).toBeGreaterThan(statusCountBeforeRelease);
|
||||
expect(statuses.at(-1)?.profilePartitions).toEqual({ default: defaultPartition });
|
||||
expect(manager.isAllowedHostPartition(defaultPartition)).toBe(true);
|
||||
expect(manager.isProxiedSession(defaultSession)).toBe(true);
|
||||
|
||||
// An in-flight bind that finishes after releaseProfile must not re-insert the removed profile.
|
||||
bindStartedGate = createGate();
|
||||
releaseBindGate = createGate();
|
||||
const inFlight = manager.ensureHostProxy({
|
||||
serverId: "remote-release",
|
||||
target,
|
||||
profileSlug: "work",
|
||||
});
|
||||
await bindStartedGate.promise;
|
||||
manager.releaseProfile("work");
|
||||
releaseBindGate.resolve();
|
||||
bindStartedGate = null;
|
||||
releaseBindGate = null;
|
||||
await inFlight;
|
||||
|
||||
expect(manager.isAllowedHostPartition(workPartition)).toBe(false);
|
||||
expect(manager.isProxiedSession(workSession)).toBe(false);
|
||||
expect(manager.listKnownPartitions()).not.toContain(workPartition);
|
||||
expect(manager.getHostProxyStatus("remote-release")?.profilePartitions).toEqual({
|
||||
default: defaultPartition,
|
||||
});
|
||||
|
||||
// A request removed while waiting for route setup must not bind afterward.
|
||||
const pendingRouteServerId = "remote-release-route-race";
|
||||
const pendingRouteWorkPartition = getBrowserPartition(
|
||||
{ kind: "host", serverId: pendingRouteServerId },
|
||||
"work",
|
||||
);
|
||||
routeStartedGate = createGate();
|
||||
releaseRouteGate = createGate();
|
||||
const inFlightRoute = manager.ensureHostProxy({
|
||||
serverId: pendingRouteServerId,
|
||||
target: "tcp://10.0.0.23:6767",
|
||||
profileSlug: "work",
|
||||
});
|
||||
await routeStartedGate.promise;
|
||||
manager.releaseProfile("work");
|
||||
releaseRouteGate.resolve();
|
||||
routeStartedGate = null;
|
||||
releaseRouteGate = null;
|
||||
await inFlightRoute;
|
||||
|
||||
expect(manager.isAllowedHostPartition(pendingRouteWorkPartition)).toBe(false);
|
||||
expect(manager.listKnownPartitions()).not.toContain(pendingRouteWorkPartition);
|
||||
expect(manager.getHostProxyStatus(pendingRouteServerId)?.profilePartitions).toEqual({});
|
||||
|
||||
// Recreating the same slug later re-runs setProxy + resolveProxy and re-binds cleanly.
|
||||
const setProxyBeforeRebind = setProxyCallsForWork;
|
||||
const resolveProxyBeforeRebind = resolveProxyCallsForWork;
|
||||
const rebound = await manager.ensureHostProxy({
|
||||
serverId: "remote-release",
|
||||
target,
|
||||
profileSlug: "work",
|
||||
});
|
||||
|
||||
expect(rebound.status).toBe("ready");
|
||||
expect(rebound.profilePartitions).toEqual({
|
||||
default: defaultPartition,
|
||||
work: workPartition,
|
||||
});
|
||||
expect(setProxyCallsForWork).toBe(setProxyBeforeRebind + 1);
|
||||
expect(resolveProxyCallsForWork).toBe(resolveProxyBeforeRebind + 2);
|
||||
expect(manager.isAllowedHostPartition(workPartition)).toBe(true);
|
||||
expect(manager.isProxiedSession(workSession)).toBe(true);
|
||||
|
||||
// releaseHostProxy also removes disposed sessions from isProxiedSession.
|
||||
await manager.releaseHostProxy("remote-release");
|
||||
expect(manager.isProxiedSession(defaultSession)).toBe(false);
|
||||
expect(manager.isProxiedSession(workSession)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -68,6 +68,7 @@ export interface BrowserProxyManager {
|
||||
isAllowedHostPartition(partition: string): boolean;
|
||||
isProxiedSession(session: object): boolean;
|
||||
listKnownPartitions(): string[];
|
||||
releaseProfile(profileSlug: string): void;
|
||||
releaseHostProxy(serverId: string): Promise<void>;
|
||||
disposeAll(): Promise<void>;
|
||||
}
|
||||
@@ -83,9 +84,9 @@ interface HostProxyEntry {
|
||||
error: string | null;
|
||||
socksServer: Server | null;
|
||||
socksPort: number | null;
|
||||
/** Profile slug -> partition whose session is bound and verified. */
|
||||
boundPartitions: Map<string, string>;
|
||||
bindPromises: Map<string, Promise<void>>;
|
||||
/** Profile slug -> bound partition and Chromium session. */
|
||||
boundPartitions: Map<string, { partition: string; session: BrowserProxySessionLike }>;
|
||||
bindPromises: Map<string, Promise<boolean>>;
|
||||
mux: TunnelMuxClient | null;
|
||||
connectPromise: Promise<TunnelMuxClient> | null;
|
||||
routePromise: Promise<number> | null;
|
||||
@@ -117,11 +118,14 @@ export function createBrowserProxyManager(deps: BrowserProxyManagerDeps): Browse
|
||||
const allowedPartitions = new Set<string>();
|
||||
const knownPartitions = new Set<string>();
|
||||
const proxiedSessions = new WeakSet<object>();
|
||||
const profileReleaseGeneration = new Map<string, number>();
|
||||
|
||||
function snapshotOf(entry: HostProxyEntry): BrowserProxyStatusSnapshot {
|
||||
return {
|
||||
serverId: entry.serverId,
|
||||
profilePartitions: Object.fromEntries(entry.boundPartitions),
|
||||
profilePartitions: Object.fromEntries(
|
||||
Array.from(entry.boundPartitions, ([slug, bound]) => [slug, bound.partition]),
|
||||
),
|
||||
status: entry.status,
|
||||
error: entry.error,
|
||||
// Only expose socksPort once a Chromium session proxy has been configured and
|
||||
@@ -187,9 +191,13 @@ export function createBrowserProxyManager(deps: BrowserProxyManagerDeps): Browse
|
||||
profileSlug: string,
|
||||
partition: string,
|
||||
socksPort: number,
|
||||
): Promise<void> {
|
||||
releaseGeneration: number,
|
||||
): Promise<boolean> {
|
||||
if ((profileReleaseGeneration.get(profileSlug) ?? 0) !== releaseGeneration) {
|
||||
return false;
|
||||
}
|
||||
if (entry.boundPartitions.has(profileSlug)) {
|
||||
return;
|
||||
return true;
|
||||
}
|
||||
let bindTask = entry.bindPromises.get(profileSlug);
|
||||
if (!bindTask) {
|
||||
@@ -198,10 +206,18 @@ export function createBrowserProxyManager(deps: BrowserProxyManagerDeps): Browse
|
||||
if (entry.disposed) {
|
||||
throw new Error("Host browser proxy was disposed");
|
||||
}
|
||||
entry.boundPartitions.set(profileSlug, partition);
|
||||
if ((profileReleaseGeneration.get(profileSlug) ?? 0) !== releaseGeneration) {
|
||||
if (!entry.bindPromises.has(profileSlug) && !entry.boundPartitions.has(profileSlug)) {
|
||||
knownPartitions.delete(partition);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
entry.boundPartitions.set(profileSlug, { partition, session });
|
||||
allowedPartitions.add(partition);
|
||||
knownPartitions.add(partition);
|
||||
proxiedSessions.add(session);
|
||||
deps.onStatusChange?.(snapshotOf(entry));
|
||||
return true;
|
||||
})();
|
||||
entry.bindPromises.set(profileSlug, bindTask);
|
||||
const settled = () => {
|
||||
@@ -211,7 +227,7 @@ export function createBrowserProxyManager(deps: BrowserProxyManagerDeps): Browse
|
||||
};
|
||||
bindTask.then(settled, settled);
|
||||
}
|
||||
await bindTask;
|
||||
return await bindTask;
|
||||
}
|
||||
|
||||
async function configureSession(
|
||||
@@ -444,6 +460,7 @@ export function createBrowserProxyManager(deps: BrowserProxyManagerDeps): Browse
|
||||
throw new Error("Host serverId is required");
|
||||
}
|
||||
const profileSlug = input.profileSlug ?? DEFAULT_BROWSER_PROFILE_SLUG;
|
||||
const releaseGeneration = profileReleaseGeneration.get(profileSlug) ?? 0;
|
||||
const partition = getBrowserPartition({ kind: "host", serverId }, profileSlug);
|
||||
|
||||
const entry = getOrCreateEntry(serverId, input.target);
|
||||
@@ -457,8 +474,13 @@ export function createBrowserProxyManager(deps: BrowserProxyManagerDeps): Browse
|
||||
setEntryStatus(entry, hasBoundSession(entry) ? "reconnecting" : "connecting", null);
|
||||
}
|
||||
const socksPort = await ensureRoute(entry);
|
||||
await bindSession(entry, profileSlug, partition, socksPort);
|
||||
setEntryStatus(entry, "ready", null);
|
||||
if ((profileReleaseGeneration.get(profileSlug) ?? 0) !== releaseGeneration) {
|
||||
return snapshotOf(entry);
|
||||
}
|
||||
const bound = await bindSession(entry, profileSlug, partition, socksPort, releaseGeneration);
|
||||
if (bound) {
|
||||
setEntryStatus(entry, "ready", null);
|
||||
}
|
||||
} catch (error) {
|
||||
if (!entry.disposed) {
|
||||
setEntryStatus(entry, "error", formatError(error));
|
||||
@@ -497,13 +519,44 @@ export function createBrowserProxyManager(deps: BrowserProxyManagerDeps): Browse
|
||||
return [...knownPartitions];
|
||||
}
|
||||
|
||||
function releaseProfile(profileSlug: string): void {
|
||||
const normalized = profileSlug.trim();
|
||||
if (!normalized || normalized === DEFAULT_BROWSER_PROFILE_SLUG) {
|
||||
return;
|
||||
}
|
||||
profileReleaseGeneration.set(normalized, (profileReleaseGeneration.get(normalized) ?? 0) + 1);
|
||||
|
||||
for (const partition of knownPartitions) {
|
||||
const parsed = parseBrowserPartition(partition);
|
||||
if (parsed?.route === "host" && parsed.profileSlug === normalized) {
|
||||
knownPartitions.delete(partition);
|
||||
allowedPartitions.delete(partition);
|
||||
}
|
||||
}
|
||||
|
||||
for (const entry of entriesByServerId.values()) {
|
||||
if (entry.disposed) continue;
|
||||
entry.bindPromises.delete(normalized);
|
||||
const bound = entry.boundPartitions.get(normalized);
|
||||
if (!bound) continue;
|
||||
entry.boundPartitions.delete(normalized);
|
||||
allowedPartitions.delete(bound.partition);
|
||||
knownPartitions.delete(bound.partition);
|
||||
proxiedSessions.delete(bound.session);
|
||||
deps.onStatusChange?.(snapshotOf(entry));
|
||||
}
|
||||
}
|
||||
|
||||
async function disposeEntry(entry: HostProxyEntry): Promise<void> {
|
||||
if (entry.disposed) return;
|
||||
entry.disposed = true;
|
||||
entriesByServerId.delete(entry.serverId);
|
||||
for (const partition of entry.boundPartitions.values()) {
|
||||
for (const { partition, session } of entry.boundPartitions.values()) {
|
||||
allowedPartitions.delete(partition);
|
||||
proxiedSessions.delete(session);
|
||||
}
|
||||
entry.boundPartitions.clear();
|
||||
entry.bindPromises.clear();
|
||||
|
||||
entry.mux?.close();
|
||||
entry.mux = null;
|
||||
@@ -541,6 +594,7 @@ export function createBrowserProxyManager(deps: BrowserProxyManagerDeps): Browse
|
||||
isAllowedHostPartition,
|
||||
isProxiedSession,
|
||||
listKnownPartitions,
|
||||
releaseProfile,
|
||||
releaseHostProxy,
|
||||
disposeAll,
|
||||
};
|
||||
|
||||
@@ -2,7 +2,7 @@ import { describe, expect, test } from "vitest";
|
||||
import { getBrowserPartition, PASEO_BROWSER_PROFILE_PARTITION } from "../browser-partition.js";
|
||||
import {
|
||||
getPaseoBrowserIdForWebContents,
|
||||
getPaseoBrowserWorkspaceId,
|
||||
getPaseoBrowserScope,
|
||||
isPaseoBrowserWebviewAttach,
|
||||
preparePaseoBrowserWebContents,
|
||||
registerAttachedPaseoBrowser,
|
||||
@@ -98,6 +98,7 @@ describe("browser webview attachment", () => {
|
||||
|
||||
const registered = registerAttachedPaseoBrowser({
|
||||
browserId: "browser-proxied",
|
||||
serverId: "remote-host-a",
|
||||
workspaceId: "workspace-remote",
|
||||
webContentsId: guest.id,
|
||||
sender: renderer,
|
||||
@@ -109,9 +110,35 @@ describe("browser webview attachment", () => {
|
||||
|
||||
expect(registered).toBe(true);
|
||||
expect(getPaseoBrowserIdForWebContents(guest)).toBe("browser-proxied");
|
||||
expect(getPaseoBrowserScope("browser-proxied")).toEqual({
|
||||
serverId: "remote-host-a",
|
||||
workspaceId: "workspace-remote",
|
||||
});
|
||||
unregisterPaseoBrowser("browser-proxied");
|
||||
});
|
||||
|
||||
test("rejects a host partition belonging to another serverId", () => {
|
||||
const otherHostPartition = hostPartitionFor("remote-host-b");
|
||||
const proxiedSession = {};
|
||||
const renderer = new FakeRenderer(91);
|
||||
const guest = new FakeBrowserGuest(911, renderer, proxiedSession);
|
||||
|
||||
const registered = registerAttachedPaseoBrowser({
|
||||
browserId: "browser-mismatched-host",
|
||||
serverId: "remote-host-a",
|
||||
workspaceId: "workspace-remote",
|
||||
webContentsId: guest.id,
|
||||
sender: renderer,
|
||||
partition: otherHostPartition,
|
||||
sessionFromPartition: (partition) => (partition === otherHostPartition ? proxiedSession : {}),
|
||||
isAllowedHostSession: (session) => session === proxiedSession,
|
||||
findWebContents: () => guest,
|
||||
});
|
||||
|
||||
expect(registered).toBe(false);
|
||||
expect(getPaseoBrowserIdForWebContents(guest)).toBeNull();
|
||||
});
|
||||
|
||||
test("admits a host-proxied named profile only once its session is bound to the host proxy", () => {
|
||||
const boundWork = hostPartitionFor("remote-host-a", "work");
|
||||
const unboundWork = hostPartitionFor("remote-host-b", "work");
|
||||
@@ -144,6 +171,7 @@ describe("browser webview attachment", () => {
|
||||
const register = (isAllowedHostSession: (session: object) => boolean) =>
|
||||
registerAttachedPaseoBrowser({
|
||||
browserId: "browser-proxied-work",
|
||||
serverId: "remote-host-a",
|
||||
workspaceId: "workspace-remote",
|
||||
webContentsId: guest.id,
|
||||
sender: renderer,
|
||||
@@ -186,6 +214,7 @@ describe("browser webview attachment", () => {
|
||||
|
||||
const registered = registerAttachedPaseoBrowser({
|
||||
browserId: "browser-a",
|
||||
serverId: "local-host",
|
||||
workspaceId: "workspace-a",
|
||||
webContentsId: guest.id,
|
||||
sender: renderer,
|
||||
@@ -196,7 +225,10 @@ describe("browser webview attachment", () => {
|
||||
|
||||
expect(registered).toBe(true);
|
||||
expect(getPaseoBrowserIdForWebContents(guest)).toBe("browser-a");
|
||||
expect(getPaseoBrowserWorkspaceId("browser-a")).toBe("workspace-a");
|
||||
expect(getPaseoBrowserScope("browser-a")).toEqual({
|
||||
serverId: "local-host",
|
||||
workspaceId: "workspace-a",
|
||||
});
|
||||
unregisterPaseoBrowser("browser-a");
|
||||
});
|
||||
|
||||
@@ -208,6 +240,7 @@ describe("browser webview attachment", () => {
|
||||
|
||||
const registered = registerAttachedPaseoBrowser({
|
||||
browserId: "browser-rejected-owner",
|
||||
serverId: "local-host",
|
||||
workspaceId: "workspace-a",
|
||||
webContentsId: guest.id,
|
||||
sender: claimant,
|
||||
@@ -227,6 +260,7 @@ describe("browser webview attachment", () => {
|
||||
|
||||
const registered = registerAttachedPaseoBrowser({
|
||||
browserId: "browser-rejected-profile",
|
||||
serverId: "local-host",
|
||||
workspaceId: "workspace-a",
|
||||
webContentsId: guest.id,
|
||||
sender: renderer,
|
||||
@@ -252,6 +286,7 @@ describe("browser webview attachment", () => {
|
||||
|
||||
registerAttachedPaseoBrowser({
|
||||
browserId: "browser-second",
|
||||
serverId: "local-host",
|
||||
workspaceId: "workspace-second",
|
||||
webContentsId: secondGuest.id,
|
||||
sender: secondRenderer,
|
||||
@@ -261,6 +296,7 @@ describe("browser webview attachment", () => {
|
||||
});
|
||||
registerAttachedPaseoBrowser({
|
||||
browserId: "browser-first",
|
||||
serverId: "local-host",
|
||||
workspaceId: "workspace-first",
|
||||
webContentsId: firstGuest.id,
|
||||
sender: firstRenderer,
|
||||
@@ -288,6 +324,7 @@ describe("browser webview attachment", () => {
|
||||
] as const) {
|
||||
registerAttachedPaseoBrowser({
|
||||
browserId: "browser-shared-hosts",
|
||||
serverId: "local-host",
|
||||
workspaceId: "workspace-shared",
|
||||
webContentsId: guest.id,
|
||||
sender: renderer,
|
||||
@@ -301,7 +338,10 @@ describe("browser webview attachment", () => {
|
||||
|
||||
expect(getPaseoBrowserIdForWebContents(firstGuest)).toBeNull();
|
||||
expect(getPaseoBrowserIdForWebContents(secondGuest)).toBe("browser-shared-hosts");
|
||||
expect(getPaseoBrowserWorkspaceId("browser-shared-hosts")).toBe("workspace-shared");
|
||||
expect(getPaseoBrowserScope("browser-shared-hosts")).toEqual({
|
||||
serverId: "local-host",
|
||||
workspaceId: "workspace-shared",
|
||||
});
|
||||
unregisterPaseoBrowser("browser-shared-hosts");
|
||||
});
|
||||
|
||||
@@ -312,6 +352,7 @@ describe("browser webview attachment", () => {
|
||||
preparePaseoBrowserWebContents(guest);
|
||||
registerAttachedPaseoBrowser({
|
||||
browserId: "browser-cleanup",
|
||||
serverId: "local-host",
|
||||
workspaceId: "workspace-cleanup",
|
||||
webContentsId: guest.id,
|
||||
sender: renderer,
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { webContents as allWebContents, type WebContents } from "electron";
|
||||
import { parseBrowserPartition } from "../browser-partition.js";
|
||||
import { getBrowserPartition, parseBrowserPartition } from "../browser-partition.js";
|
||||
import {
|
||||
BROWSER_NEW_TAB_REQUEST_EVENT,
|
||||
buildBrowserPopupWebPreferences,
|
||||
@@ -7,7 +7,7 @@ import {
|
||||
isAllowedBrowserWebviewUrl,
|
||||
PendingBrowserWindowOpenRequests,
|
||||
} from "./window-open.js";
|
||||
import { PaseoBrowserWebviewRegistry } from "./registry.js";
|
||||
import { PaseoBrowserWebviewRegistry, type BrowserWorkspaceScope } from "./registry.js";
|
||||
|
||||
export {
|
||||
BROWSER_NEW_TAB_REQUEST_EVENT,
|
||||
@@ -15,6 +15,7 @@ export {
|
||||
decideBrowserWindowOpenRequest,
|
||||
PendingBrowserWindowOpenRequests,
|
||||
};
|
||||
export type { BrowserWorkspaceScope };
|
||||
|
||||
const browserRegistry = new PaseoBrowserWebviewRegistry();
|
||||
|
||||
@@ -29,9 +30,8 @@ interface RegisteredBrowserWebContents extends BrowserWebContentsIdentity {
|
||||
once(event: "destroyed", listener: () => void): void;
|
||||
}
|
||||
|
||||
interface AttachedBrowserRegistration {
|
||||
interface AttachedBrowserRegistration extends BrowserWorkspaceScope {
|
||||
browserId: string;
|
||||
workspaceId: string;
|
||||
webContentsId: number;
|
||||
}
|
||||
|
||||
@@ -77,6 +77,12 @@ export function preparePaseoBrowserWebContents(contents: RegisteredBrowserWebCon
|
||||
}
|
||||
|
||||
export function registerAttachedPaseoBrowser(input: RegisterAttachedBrowserInput): boolean {
|
||||
const serverId = input.serverId.trim();
|
||||
const workspaceId = input.workspaceId.trim();
|
||||
const browserId = input.browserId.trim();
|
||||
if (!serverId || !workspaceId || !browserId) {
|
||||
return false;
|
||||
}
|
||||
const guest = input.findWebContents(input.webContentsId);
|
||||
if (!guest || guest.isDestroyed() || guest.hostWebContents !== input.sender) {
|
||||
return false;
|
||||
@@ -85,18 +91,25 @@ export function registerAttachedPaseoBrowser(input: RegisterAttachedBrowserInput
|
||||
if (!parsed || guest.session !== input.sessionFromPartition(input.partition)) {
|
||||
return false;
|
||||
}
|
||||
if (parsed.route === "host" && !(input.isAllowedHostSession?.(guest.session) ?? false)) {
|
||||
return false;
|
||||
if (parsed.route === "host") {
|
||||
const expectedPartition = getBrowserPartition({ kind: "host", serverId }, parsed.profileSlug);
|
||||
if (
|
||||
input.partition !== expectedPartition ||
|
||||
!(input.isAllowedHostSession?.(guest.session) ?? false)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
browserRegistry.registerWebContents({
|
||||
webContentsId: input.webContentsId,
|
||||
browserId: input.browserId,
|
||||
browserId,
|
||||
hostWebContentsId: input.sender.id,
|
||||
});
|
||||
browserRegistry.registerWorkspace({
|
||||
browserId: input.browserId,
|
||||
workspaceId: input.workspaceId,
|
||||
browserId,
|
||||
serverId,
|
||||
workspaceId,
|
||||
});
|
||||
return true;
|
||||
}
|
||||
@@ -122,31 +135,32 @@ export function unregisterPaseoBrowserHost(hostWebContentsId: number): void {
|
||||
browserRegistry.unregisterHostWebContents(hostWebContentsId);
|
||||
}
|
||||
|
||||
export function getPaseoBrowserWorkspaceId(browserId: string): string | null {
|
||||
return browserRegistry.getWorkspaceId(browserId);
|
||||
export function getPaseoBrowserScope(browserId: string): BrowserWorkspaceScope | null {
|
||||
return browserRegistry.getScope(browserId);
|
||||
}
|
||||
|
||||
export function listRegisteredPaseoBrowserIdsForWorkspace(workspaceId: string): string[] {
|
||||
return browserRegistry.listBrowserIdsForWorkspace(workspaceId);
|
||||
export function listRegisteredPaseoBrowserIdsForWorkspace(scope: BrowserWorkspaceScope): string[] {
|
||||
return browserRegistry.listBrowserIdsForWorkspace(scope);
|
||||
}
|
||||
|
||||
export function setWorkspaceActivePaseoBrowserId(input: {
|
||||
hostWebContentsId: number;
|
||||
serverId: string;
|
||||
workspaceId: string;
|
||||
browserId: string | null;
|
||||
}): void {
|
||||
browserRegistry.setWorkspaceActiveBrowser(input);
|
||||
}
|
||||
|
||||
export function getWorkspaceActivePaseoBrowserId(workspaceId: string): string | null {
|
||||
return browserRegistry.getMostRecentActiveBrowserIdForWorkspace(workspaceId);
|
||||
export function getWorkspaceActivePaseoBrowserId(scope: BrowserWorkspaceScope): string | null {
|
||||
return browserRegistry.getMostRecentActiveBrowserIdForWorkspace(scope);
|
||||
}
|
||||
|
||||
export function getWorkspaceActivePaseoBrowserIdForHostWindow(
|
||||
workspaceId: string,
|
||||
scope: BrowserWorkspaceScope,
|
||||
hostWebContentsId: number,
|
||||
): string | null {
|
||||
return browserRegistry.getActiveBrowserIdForWorkspaceInHostWindow(hostWebContentsId, workspaceId);
|
||||
return browserRegistry.getActiveBrowserIdForWorkspaceInHostWindow(hostWebContentsId, scope);
|
||||
}
|
||||
|
||||
export function getPaseoBrowserWebContentsForHostWindow(
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { PaseoBrowserWebviewRegistry } from "./registry.js";
|
||||
|
||||
const SERVER_A = "server-a";
|
||||
const SERVER_B = "server-b";
|
||||
|
||||
describe("PaseoBrowserWebviewRegistry", () => {
|
||||
it("keeps one authoritative webContents target per host and browser", () => {
|
||||
const registry = new PaseoBrowserWebviewRegistry();
|
||||
@@ -10,9 +13,14 @@ describe("PaseoBrowserWebviewRegistry", () => {
|
||||
browserId: "browser-a",
|
||||
hostWebContentsId: 101,
|
||||
});
|
||||
registry.registerWorkspace({ browserId: "browser-a", workspaceId: "workspace-a" });
|
||||
registry.registerWorkspace({
|
||||
browserId: "browser-a",
|
||||
serverId: SERVER_A,
|
||||
workspaceId: "workspace-a",
|
||||
});
|
||||
registry.setWorkspaceActiveBrowser({
|
||||
hostWebContentsId: 101,
|
||||
serverId: SERVER_A,
|
||||
workspaceId: "workspace-a",
|
||||
browserId: "browser-a",
|
||||
});
|
||||
@@ -29,7 +37,10 @@ describe("PaseoBrowserWebviewRegistry", () => {
|
||||
hostWebContentsId: 101,
|
||||
});
|
||||
expect(registry.getWebContentsIdForBrowserInHostWindow(101, "browser-a")).toBe(2);
|
||||
expect(registry.getWorkspaceId("browser-a")).toBe("workspace-a");
|
||||
expect(registry.getScope("browser-a")).toEqual({
|
||||
serverId: SERVER_A,
|
||||
workspaceId: "workspace-a",
|
||||
});
|
||||
expect(registry.getActiveBrowserIdForHostWindow(101)).toBe("browser-a");
|
||||
});
|
||||
|
||||
@@ -43,6 +54,7 @@ describe("PaseoBrowserWebviewRegistry", () => {
|
||||
});
|
||||
registry.setWorkspaceActiveBrowser({
|
||||
hostWebContentsId: 101,
|
||||
serverId: SERVER_A,
|
||||
workspaceId: "workspace-a",
|
||||
browserId: "browser-a",
|
||||
});
|
||||
@@ -53,9 +65,12 @@ describe("PaseoBrowserWebviewRegistry", () => {
|
||||
hostWebContentsId: 101,
|
||||
});
|
||||
|
||||
expect(registry.getActiveBrowserIdForWorkspaceInHostWindow(101, "workspace-a")).toBe(
|
||||
"browser-a",
|
||||
);
|
||||
expect(
|
||||
registry.getActiveBrowserIdForWorkspaceInHostWindow(101, {
|
||||
serverId: SERVER_A,
|
||||
workspaceId: "workspace-a",
|
||||
}),
|
||||
).toBe("browser-a");
|
||||
expect(registry.getWebContentsIdForBrowserInHostWindow(101, "browser-a")).toBe(1);
|
||||
});
|
||||
|
||||
@@ -92,23 +107,31 @@ describe("PaseoBrowserWebviewRegistry", () => {
|
||||
});
|
||||
registry.setWorkspaceActiveBrowser({
|
||||
hostWebContentsId: 101,
|
||||
serverId: SERVER_A,
|
||||
workspaceId: "workspace-a",
|
||||
browserId: "browser-first-window",
|
||||
});
|
||||
registry.setWorkspaceActiveBrowser({
|
||||
hostWebContentsId: 202,
|
||||
serverId: SERVER_A,
|
||||
workspaceId: "workspace-a",
|
||||
browserId: "browser-second-window",
|
||||
});
|
||||
|
||||
expect(registry.getActiveBrowserIdForHostWindow(101)).toBe("browser-first-window");
|
||||
expect(registry.getActiveBrowserIdForHostWindow(202)).toBe("browser-second-window");
|
||||
expect(registry.getActiveBrowserIdForWorkspaceInHostWindow(101, "workspace-a")).toBe(
|
||||
"browser-first-window",
|
||||
);
|
||||
expect(registry.getActiveBrowserIdForWorkspaceInHostWindow(202, "workspace-a")).toBe(
|
||||
"browser-second-window",
|
||||
);
|
||||
expect(
|
||||
registry.getActiveBrowserIdForWorkspaceInHostWindow(101, {
|
||||
serverId: SERVER_A,
|
||||
workspaceId: "workspace-a",
|
||||
}),
|
||||
).toBe("browser-first-window");
|
||||
expect(
|
||||
registry.getActiveBrowserIdForWorkspaceInHostWindow(202, {
|
||||
serverId: SERVER_A,
|
||||
workspaceId: "workspace-a",
|
||||
}),
|
||||
).toBe("browser-second-window");
|
||||
});
|
||||
|
||||
it("keeps active updates and clears inside their owning host window", () => {
|
||||
@@ -126,22 +149,26 @@ describe("PaseoBrowserWebviewRegistry", () => {
|
||||
});
|
||||
registry.setWorkspaceActiveBrowser({
|
||||
hostWebContentsId: 101,
|
||||
serverId: SERVER_A,
|
||||
workspaceId: "workspace-a",
|
||||
browserId: "browser-first-window",
|
||||
});
|
||||
registry.setWorkspaceActiveBrowser({
|
||||
hostWebContentsId: 202,
|
||||
serverId: SERVER_A,
|
||||
workspaceId: "workspace-a",
|
||||
browserId: "browser-second-window",
|
||||
});
|
||||
|
||||
registry.setWorkspaceActiveBrowser({
|
||||
hostWebContentsId: 101,
|
||||
serverId: SERVER_A,
|
||||
workspaceId: "workspace-a",
|
||||
browserId: "browser-second-window",
|
||||
});
|
||||
registry.setWorkspaceActiveBrowser({
|
||||
hostWebContentsId: 101,
|
||||
serverId: SERVER_A,
|
||||
workspaceId: "workspace-a",
|
||||
browserId: null,
|
||||
});
|
||||
@@ -160,6 +187,7 @@ describe("PaseoBrowserWebviewRegistry", () => {
|
||||
});
|
||||
registry.setWorkspaceActiveBrowser({
|
||||
hostWebContentsId: 101,
|
||||
serverId: SERVER_A,
|
||||
workspaceId: "workspace-a",
|
||||
browserId: "browser-a",
|
||||
});
|
||||
@@ -170,6 +198,7 @@ describe("PaseoBrowserWebviewRegistry", () => {
|
||||
});
|
||||
registry.setWorkspaceActiveBrowser({
|
||||
hostWebContentsId: 202,
|
||||
serverId: SERVER_A,
|
||||
workspaceId: "workspace-a",
|
||||
browserId: "browser-a",
|
||||
});
|
||||
@@ -217,13 +246,20 @@ describe("PaseoBrowserWebviewRegistry", () => {
|
||||
browserId: "browser-a",
|
||||
hostWebContentsId: 202,
|
||||
});
|
||||
registry.registerWorkspace({ browserId: "browser-a", workspaceId: "workspace-a" });
|
||||
registry.registerWorkspace({
|
||||
browserId: "browser-a",
|
||||
serverId: SERVER_A,
|
||||
workspaceId: "workspace-a",
|
||||
});
|
||||
|
||||
registry.unregisterBrowserFromHost(101, "browser-a");
|
||||
|
||||
expect(registry.getWebContentsIdForBrowserInHostWindow(101, "browser-a")).toBeNull();
|
||||
expect(registry.getWebContentsIdForBrowserInHostWindow(202, "browser-a")).toBe(22);
|
||||
expect(registry.getWorkspaceId("browser-a")).toBe("workspace-a");
|
||||
expect(registry.getScope("browser-a")).toEqual({
|
||||
serverId: SERVER_A,
|
||||
workspaceId: "workspace-a",
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps another host's active browser when one guest is destroyed", () => {
|
||||
@@ -241,11 +277,13 @@ describe("PaseoBrowserWebviewRegistry", () => {
|
||||
});
|
||||
registry.setWorkspaceActiveBrowser({
|
||||
hostWebContentsId: 101,
|
||||
serverId: SERVER_A,
|
||||
workspaceId: "workspace-a",
|
||||
browserId: "browser-a",
|
||||
});
|
||||
registry.setWorkspaceActiveBrowser({
|
||||
hostWebContentsId: 202,
|
||||
serverId: SERVER_A,
|
||||
workspaceId: "workspace-a",
|
||||
browserId: "browser-a",
|
||||
});
|
||||
@@ -262,6 +300,7 @@ describe("PaseoBrowserWebviewRegistry", () => {
|
||||
|
||||
registry.setWorkspaceActiveBrowser({
|
||||
hostWebContentsId: 101,
|
||||
serverId: SERVER_A,
|
||||
workspaceId: "workspace-a",
|
||||
browserId: "browser-a",
|
||||
});
|
||||
@@ -279,6 +318,7 @@ describe("PaseoBrowserWebviewRegistry", () => {
|
||||
|
||||
registry.setWorkspaceActiveBrowser({
|
||||
hostWebContentsId: 101,
|
||||
serverId: SERVER_A,
|
||||
workspaceId: "workspace-a",
|
||||
browserId: "browser-a",
|
||||
});
|
||||
@@ -297,6 +337,7 @@ describe("PaseoBrowserWebviewRegistry", () => {
|
||||
|
||||
registry.setWorkspaceActiveBrowser({
|
||||
hostWebContentsId: 101,
|
||||
serverId: SERVER_A,
|
||||
workspaceId: "workspace-a",
|
||||
browserId: "browser-a",
|
||||
});
|
||||
@@ -336,4 +377,82 @@ describe("PaseoBrowserWebviewRegistry", () => {
|
||||
|
||||
expect(registry.hasBrowserInOtherHostWindow(101, "browser-a")).toBe(false);
|
||||
});
|
||||
|
||||
it("isolates tabs and active browser selections that share a workspaceId on different servers", () => {
|
||||
const registry = new PaseoBrowserWebviewRegistry();
|
||||
|
||||
registry.registerWebContents({
|
||||
webContentsId: 11,
|
||||
browserId: "browser-a",
|
||||
hostWebContentsId: 101,
|
||||
});
|
||||
registry.registerWorkspace({ browserId: "browser-a", serverId: SERVER_A, workspaceId: "ws-1" });
|
||||
registry.setWorkspaceActiveBrowser({
|
||||
hostWebContentsId: 101,
|
||||
serverId: SERVER_A,
|
||||
workspaceId: "ws-1",
|
||||
browserId: "browser-a",
|
||||
});
|
||||
|
||||
registry.registerWebContents({
|
||||
webContentsId: 22,
|
||||
browserId: "browser-b",
|
||||
hostWebContentsId: 101,
|
||||
});
|
||||
registry.registerWorkspace({ browserId: "browser-b", serverId: SERVER_B, workspaceId: "ws-1" });
|
||||
registry.setWorkspaceActiveBrowser({
|
||||
hostWebContentsId: 101,
|
||||
serverId: SERVER_B,
|
||||
workspaceId: "ws-1",
|
||||
browserId: "browser-b",
|
||||
});
|
||||
|
||||
expect(
|
||||
registry.listBrowserIdsForWorkspace({ serverId: SERVER_A, workspaceId: "ws-1" }),
|
||||
).toEqual(["browser-a"]);
|
||||
expect(
|
||||
registry.listBrowserIdsForWorkspace({ serverId: SERVER_B, workspaceId: "ws-1" }),
|
||||
).toEqual(["browser-b"]);
|
||||
expect(
|
||||
registry.getActiveBrowserIdForWorkspaceInHostWindow(101, {
|
||||
serverId: SERVER_A,
|
||||
workspaceId: "ws-1",
|
||||
}),
|
||||
).toBe("browser-a");
|
||||
expect(
|
||||
registry.getActiveBrowserIdForWorkspaceInHostWindow(101, {
|
||||
serverId: SERVER_B,
|
||||
workspaceId: "ws-1",
|
||||
}),
|
||||
).toBe("browser-b");
|
||||
});
|
||||
|
||||
it("does not allow setWorkspaceActiveBrowser to reassign a tab to a different scope", () => {
|
||||
const registry = new PaseoBrowserWebviewRegistry();
|
||||
|
||||
registry.registerWebContents({
|
||||
webContentsId: 11,
|
||||
browserId: "browser-a",
|
||||
hostWebContentsId: 101,
|
||||
});
|
||||
registry.registerWorkspace({ browserId: "browser-a", serverId: SERVER_A, workspaceId: "ws-1" });
|
||||
|
||||
registry.setWorkspaceActiveBrowser({
|
||||
hostWebContentsId: 101,
|
||||
serverId: SERVER_B,
|
||||
workspaceId: "ws-1",
|
||||
browserId: "browser-a",
|
||||
});
|
||||
|
||||
expect(registry.getScope("browser-a")).toEqual({
|
||||
serverId: SERVER_A,
|
||||
workspaceId: "ws-1",
|
||||
});
|
||||
expect(
|
||||
registry.getActiveBrowserIdForWorkspaceInHostWindow(101, {
|
||||
serverId: SERVER_B,
|
||||
workspaceId: "ws-1",
|
||||
}),
|
||||
).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,8 +1,12 @@
|
||||
export interface BrowserWorkspaceRegistration {
|
||||
browserId: string;
|
||||
export interface BrowserWorkspaceScope {
|
||||
serverId: string;
|
||||
workspaceId: string;
|
||||
}
|
||||
|
||||
export interface BrowserWorkspaceRegistration extends BrowserWorkspaceScope {
|
||||
browserId: string;
|
||||
}
|
||||
|
||||
export interface BrowserWebContentsRegistration {
|
||||
browserId: string;
|
||||
hostWebContentsId: number;
|
||||
@@ -11,7 +15,7 @@ export interface BrowserWebContentsRegistration {
|
||||
export class PaseoBrowserWebviewRegistry {
|
||||
private readonly registrationsByWebContentsId = new Map<number, BrowserWebContentsRegistration>();
|
||||
private readonly webContentsIdsByHostAndBrowserId = new Map<string, number>();
|
||||
private readonly workspaceIdsByBrowserId = new Map<string, string>();
|
||||
private readonly scopesByBrowserId = new Map<string, BrowserWorkspaceScope>();
|
||||
private readonly activeBrowserIdsByHostWindow = new Map<number, Map<string, string>>();
|
||||
|
||||
public registerWebContents(input: {
|
||||
@@ -79,7 +83,10 @@ export class PaseoBrowserWebviewRegistry {
|
||||
}
|
||||
|
||||
public registerWorkspace(input: BrowserWorkspaceRegistration): void {
|
||||
this.workspaceIdsByBrowserId.set(input.browserId, input.workspaceId);
|
||||
this.scopesByBrowserId.set(input.browserId, {
|
||||
serverId: input.serverId,
|
||||
workspaceId: input.workspaceId,
|
||||
});
|
||||
}
|
||||
|
||||
public unregisterBrowser(browserId: string): void {
|
||||
@@ -91,7 +98,7 @@ export class PaseoBrowserWebviewRegistry {
|
||||
);
|
||||
}
|
||||
}
|
||||
this.workspaceIdsByBrowserId.delete(browserId);
|
||||
this.scopesByBrowserId.delete(browserId);
|
||||
this.deleteActiveBrowserReferences(browserId);
|
||||
}
|
||||
|
||||
@@ -102,8 +109,8 @@ export class PaseoBrowserWebviewRegistry {
|
||||
}
|
||||
}
|
||||
|
||||
public getWorkspaceId(browserId: string): string | null {
|
||||
return this.workspaceIdsByBrowserId.get(browserId) ?? null;
|
||||
public getScope(browserId: string): BrowserWorkspaceScope | null {
|
||||
return this.scopesByBrowserId.get(browserId) ?? null;
|
||||
}
|
||||
|
||||
public hasBrowserInOtherHostWindow(hostWebContentsId: number, browserId: string): boolean {
|
||||
@@ -127,39 +134,50 @@ export class PaseoBrowserWebviewRegistry {
|
||||
this.activeBrowserIdsByHostWindow.delete(hostWebContentsId);
|
||||
}
|
||||
|
||||
public listBrowserIdsForWorkspace(workspaceId: string): string[] {
|
||||
return this.listBrowserIds().filter(
|
||||
(browserId) => this.workspaceIdsByBrowserId.get(browserId) === workspaceId,
|
||||
);
|
||||
public listBrowserIdsForWorkspace(scope: BrowserWorkspaceScope): string[] {
|
||||
return this.listBrowserIds().filter((browserId) => {
|
||||
const registered = this.scopesByBrowserId.get(browserId);
|
||||
return (
|
||||
registered !== undefined &&
|
||||
registered.serverId === scope.serverId &&
|
||||
registered.workspaceId === scope.workspaceId
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
public setWorkspaceActiveBrowser(input: {
|
||||
hostWebContentsId: number;
|
||||
serverId: string;
|
||||
workspaceId: string;
|
||||
browserId: string | null;
|
||||
}): void {
|
||||
const scopeKey = this.scopeKey(input);
|
||||
if (input.browserId === null) {
|
||||
const activeBrowserIdsByWorkspace = this.activeBrowserIdsByHostWindow.get(
|
||||
const activeBrowserIdsByScope = this.activeBrowserIdsByHostWindow.get(
|
||||
input.hostWebContentsId,
|
||||
);
|
||||
if (!activeBrowserIdsByWorkspace) {
|
||||
if (!activeBrowserIdsByScope) {
|
||||
return;
|
||||
}
|
||||
activeBrowserIdsByWorkspace.delete(input.workspaceId);
|
||||
if (activeBrowserIdsByWorkspace.size === 0) {
|
||||
activeBrowserIdsByScope.delete(scopeKey);
|
||||
if (activeBrowserIdsByScope.size === 0) {
|
||||
this.activeBrowserIdsByHostWindow.delete(input.hostWebContentsId);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (this.hasBrowser(input.browserId)) {
|
||||
this.workspaceIdsByBrowserId.set(input.browserId, input.workspaceId);
|
||||
const existingScope = this.scopesByBrowserId.get(input.browserId);
|
||||
if (
|
||||
existingScope &&
|
||||
(existingScope.serverId !== input.serverId || existingScope.workspaceId !== input.workspaceId)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const activeBrowserIdsByWorkspace =
|
||||
const activeBrowserIdsByScope =
|
||||
this.activeBrowserIdsByHostWindow.get(input.hostWebContentsId) ?? new Map<string, string>();
|
||||
activeBrowserIdsByWorkspace.delete(input.workspaceId);
|
||||
activeBrowserIdsByWorkspace.set(input.workspaceId, input.browserId);
|
||||
activeBrowserIdsByScope.delete(scopeKey);
|
||||
activeBrowserIdsByScope.set(scopeKey, input.browserId);
|
||||
this.activeBrowserIdsByHostWindow.delete(input.hostWebContentsId);
|
||||
this.activeBrowserIdsByHostWindow.set(input.hostWebContentsId, activeBrowserIdsByWorkspace);
|
||||
this.activeBrowserIdsByHostWindow.set(input.hostWebContentsId, activeBrowserIdsByScope);
|
||||
}
|
||||
|
||||
public getActiveBrowserIdForHostWindow(hostWebContentsId: number): string | null {
|
||||
@@ -171,15 +189,18 @@ export class PaseoBrowserWebviewRegistry {
|
||||
|
||||
public getActiveBrowserIdForWorkspaceInHostWindow(
|
||||
hostWebContentsId: number,
|
||||
workspaceId: string,
|
||||
scope: BrowserWorkspaceScope,
|
||||
): string | null {
|
||||
return this.activeBrowserIdsByHostWindow.get(hostWebContentsId)?.get(workspaceId) ?? null;
|
||||
return (
|
||||
this.activeBrowserIdsByHostWindow.get(hostWebContentsId)?.get(this.scopeKey(scope)) ?? null
|
||||
);
|
||||
}
|
||||
|
||||
public getMostRecentActiveBrowserIdForWorkspace(workspaceId: string): string | null {
|
||||
public getMostRecentActiveBrowserIdForWorkspace(scope: BrowserWorkspaceScope): string | null {
|
||||
const scopeKey = this.scopeKey(scope);
|
||||
const activeBrowserIdsByHostWindow = Array.from(this.activeBrowserIdsByHostWindow.values());
|
||||
for (let index = activeBrowserIdsByHostWindow.length - 1; index >= 0; index -= 1) {
|
||||
const browserId = activeBrowserIdsByHostWindow[index].get(workspaceId);
|
||||
const browserId = activeBrowserIdsByHostWindow[index].get(scopeKey);
|
||||
if (browserId) {
|
||||
return browserId;
|
||||
}
|
||||
@@ -240,12 +261,6 @@ export class PaseoBrowserWebviewRegistry {
|
||||
}
|
||||
}
|
||||
|
||||
private hasBrowser(browserId: string): boolean {
|
||||
return Array.from(this.registrationsByWebContentsId.values()).some(
|
||||
(registration) => registration.browserId === browserId,
|
||||
);
|
||||
}
|
||||
|
||||
private hasBrowserInHostWindow(browserId: string, hostWebContentsId: number): boolean {
|
||||
return this.webContentsIdsByHostAndBrowserId.has(
|
||||
this.hostBrowserKey(hostWebContentsId, browserId),
|
||||
@@ -255,4 +270,8 @@ export class PaseoBrowserWebviewRegistry {
|
||||
private hostBrowserKey(hostWebContentsId: number, browserId: string): string {
|
||||
return `${hostWebContentsId}:${browserId}`;
|
||||
}
|
||||
|
||||
private scopeKey(scope: BrowserWorkspaceScope): string {
|
||||
return JSON.stringify([scope.serverId, scope.workspaceId]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -163,6 +163,7 @@ log.info("[desktop] app startup", {
|
||||
interface AttachedBrowserInput {
|
||||
partition: string;
|
||||
browserId: string;
|
||||
serverId: string;
|
||||
workspaceId: string;
|
||||
webContentsId: number;
|
||||
}
|
||||
@@ -179,6 +180,9 @@ function readAttachedBrowserInput(input: unknown): AttachedBrowserInput | null {
|
||||
if (typeof record.browserId !== "string" || record.browserId.trim().length === 0) {
|
||||
return null;
|
||||
}
|
||||
if (typeof record.serverId !== "string" || record.serverId.trim().length === 0) {
|
||||
return null;
|
||||
}
|
||||
if (typeof record.workspaceId !== "string" || record.workspaceId.trim().length === 0) {
|
||||
return null;
|
||||
}
|
||||
@@ -192,6 +196,7 @@ function readAttachedBrowserInput(input: unknown): AttachedBrowserInput | null {
|
||||
return {
|
||||
partition,
|
||||
browserId: record.browserId.trim(),
|
||||
serverId: record.serverId.trim(),
|
||||
workspaceId: record.workspaceId.trim(),
|
||||
webContentsId: record.webContentsId,
|
||||
};
|
||||
@@ -199,16 +204,23 @@ function readAttachedBrowserInput(input: unknown): AttachedBrowserInput | null {
|
||||
|
||||
function readActiveBrowserInput(
|
||||
input: unknown,
|
||||
): { workspaceId: string; browserId: string | null } | null {
|
||||
): { serverId: string; workspaceId: string; browserId: string | null } | null {
|
||||
if (typeof input !== "object" || input === null || Array.isArray(input)) {
|
||||
return null;
|
||||
}
|
||||
const record = input as Record<string, unknown>;
|
||||
if (typeof record.serverId !== "string" || record.serverId.trim().length === 0) {
|
||||
return null;
|
||||
}
|
||||
if (typeof record.workspaceId !== "string" || record.workspaceId.trim().length === 0) {
|
||||
return null;
|
||||
}
|
||||
const browserId = typeof record.browserId === "string" ? record.browserId.trim() : null;
|
||||
return { workspaceId: record.workspaceId.trim(), browserId: browserId || null };
|
||||
return {
|
||||
serverId: record.serverId.trim(),
|
||||
workspaceId: record.workspaceId.trim(),
|
||||
browserId: browserId || null,
|
||||
};
|
||||
}
|
||||
|
||||
const browserKeyboard = new BrowserKeyboard(getPaseoBrowserWebviewRegistry());
|
||||
@@ -441,6 +453,7 @@ ipcMain.handle("paseo:browser:remove-profile", async (_event, input: unknown) =>
|
||||
await listBrowserPartitionDirectories(userData),
|
||||
{ slug, hostPartitions: browserProxy.manager.listKnownPartitions() },
|
||||
);
|
||||
browserProxy.manager.releaseProfile(slug);
|
||||
const openGuests = listPaseoBrowserProfileGuests({
|
||||
profileSessions,
|
||||
webContents: webContents.getAllWebContents(),
|
||||
|
||||
@@ -32,6 +32,7 @@ function readWindowChromeMode(): DesktopWindowChromeMode {
|
||||
interface AttachedBrowserRegistration {
|
||||
partition: string;
|
||||
browserId: string;
|
||||
serverId: string;
|
||||
workspaceId: string;
|
||||
webContentsId: number;
|
||||
}
|
||||
@@ -137,8 +138,11 @@ contextBridge.exposeInMainWorld("paseoDesktop", {
|
||||
ipcRenderer.invoke("paseo:browser:register-attached", input),
|
||||
unregisterWorkspaceBrowser: (browserId: string) =>
|
||||
ipcRenderer.invoke("paseo:browser:unregister-workspace-browser", browserId),
|
||||
setWorkspaceActiveBrowser: (input: { workspaceId: string; browserId: string | null }) =>
|
||||
ipcRenderer.invoke("paseo:browser:set-workspace-active-browser", input),
|
||||
setWorkspaceActiveBrowser: (input: {
|
||||
serverId: string;
|
||||
workspaceId: string;
|
||||
browserId: string | null;
|
||||
}) => ipcRenderer.invoke("paseo:browser:set-workspace-active-browser", input),
|
||||
focus: (browserId: string) => ipcRenderer.invoke("paseo:browser:focus", browserId),
|
||||
openDevTools: (browserId: string) =>
|
||||
ipcRenderer.invoke("paseo:browser:open-devtools", browserId),
|
||||
@@ -168,8 +172,10 @@ contextBridge.exposeInMainWorld("paseoDesktop", {
|
||||
ipcRenderer.invoke("paseo:browser-proxy:release-host", serverId),
|
||||
deliverProxyTicket: (input: { requestId: string; ticket?: string; error?: string }) =>
|
||||
ipcRenderer.invoke("paseo:browser-proxy:deliver-ticket", input),
|
||||
executeAutomationCommand: (request: Record<string, unknown>) =>
|
||||
ipcRenderer.invoke("paseo:browser:execute-automation-command", request),
|
||||
executeAutomationCommand: (
|
||||
request: Record<string, unknown>,
|
||||
context: { serverId: string; uploadRoot: string | null },
|
||||
) => ipcRenderer.invoke("paseo:browser:execute-automation-command", request, context),
|
||||
acknowledgeFocusGuard: (input: { token: string; composing: boolean }) =>
|
||||
ipcRenderer.send("paseo:browser:focus-guard-ready", input),
|
||||
captureElement: (
|
||||
|
||||
@@ -136,6 +136,7 @@ export async function createAcpProviderConnection(
|
||||
const listeners = new Set<(event: ProviderEvent) => void>();
|
||||
const sessions = new Map<string, AcpBoundarySession>();
|
||||
const inFlight = new Set<Promise<void>>();
|
||||
const retiring = new Set<Promise<void>>();
|
||||
// Catalogue and listing requests each run a probe runtime that cancellation stops.
|
||||
const cancellable = new Map<string, AbortController>();
|
||||
let closed = false;
|
||||
@@ -189,6 +190,16 @@ export async function createAcpProviderConnection(
|
||||
sessions,
|
||||
emit,
|
||||
isClosed: () => closed,
|
||||
retireSession(sessionId, error) {
|
||||
const session = sessions.get(sessionId);
|
||||
if (!session) return false;
|
||||
sessions.delete(sessionId);
|
||||
const cleanup = session.runtime.close().catch(() => undefined);
|
||||
retiring.add(cleanup);
|
||||
void cleanup.then(() => retiring.delete(cleanup));
|
||||
emit({ type: "session.closed", sessionId, ...(error ? { error } : {}) });
|
||||
return true;
|
||||
},
|
||||
claimWarmProbe,
|
||||
discardWarmProbe,
|
||||
};
|
||||
@@ -243,6 +254,7 @@ export async function createAcpProviderConnection(
|
||||
sessions.clear();
|
||||
await Promise.all([
|
||||
closingWarmProbe,
|
||||
...retiring,
|
||||
...active.map(({ runtime }) => runtime.closeSession()),
|
||||
]);
|
||||
listeners.clear();
|
||||
@@ -260,6 +272,7 @@ interface AcpConnectionState {
|
||||
sessions: Map<string, AcpBoundarySession>;
|
||||
emit(event: ProviderEvent): void;
|
||||
isClosed(): boolean;
|
||||
retireSession(sessionId: string, error?: ProviderError): boolean;
|
||||
claimWarmProbe(binding: {
|
||||
boundarySessionId: string;
|
||||
emit: (event: ProviderEvent) => void;
|
||||
@@ -333,7 +346,7 @@ async function dispatch(
|
||||
const session = requireSession(state, input.sessionId);
|
||||
const result = await session.runtime.interrupt();
|
||||
state.emit({ type: "request.completed", requestId: input.requestId });
|
||||
if (result.retired) retireSession(state, input.sessionId, result.error);
|
||||
if (result.retired) state.retireSession(input.sessionId, result.error);
|
||||
return;
|
||||
}
|
||||
case "session.permission":
|
||||
@@ -476,12 +489,6 @@ function sessionUpdatedAt(session: SessionInfo): number {
|
||||
return Date.parse(session.updatedAt ?? "") || 0;
|
||||
}
|
||||
|
||||
function retireSession(state: AcpConnectionState, sessionId: string, error?: ProviderError): void {
|
||||
if (state.sessions.delete(sessionId)) {
|
||||
state.emit({ type: "session.closed", sessionId, ...(error ? { error } : {}) });
|
||||
}
|
||||
}
|
||||
|
||||
async function openSession(
|
||||
input: Extract<ProviderInput, { type: "session.open" }>,
|
||||
state: AcpConnectionState,
|
||||
@@ -498,7 +505,7 @@ async function openSession(
|
||||
env: input.config.env,
|
||||
wrap: input.config.wrap,
|
||||
emit: state.emit,
|
||||
onRetired: (error) => retireSession(state, input.sessionId, error),
|
||||
onRetired: (error) => state.retireSession(input.sessionId, error),
|
||||
});
|
||||
try {
|
||||
const capabilities = await runtime.open(input, state.capabilities, state.isClosed);
|
||||
@@ -544,7 +551,7 @@ interface StartRuntimeOptions {
|
||||
/** Aborting it during startup closes the runtime and rejects with the abort reason. */
|
||||
signal?: AbortSignal;
|
||||
emit(event: ProviderEvent): void;
|
||||
onRetired?: (error?: ProviderError) => void;
|
||||
onRetired?: (error?: ProviderError) => boolean;
|
||||
}
|
||||
|
||||
type InterruptResult = { retired: false } | { retired: true; error?: ProviderError };
|
||||
@@ -657,6 +664,8 @@ class AcpRuntime {
|
||||
private retirementFinalized = false;
|
||||
private processFailed = false;
|
||||
private processFailureMessage: string | null = null;
|
||||
private canReopen = false;
|
||||
private hadWorkAtTransportClose = false;
|
||||
private configTransaction = false;
|
||||
private stagedTransformerConfig: ProviderConfigState | null = null;
|
||||
private readonly closeConnector: (options?: {
|
||||
@@ -771,7 +780,15 @@ class AcpRuntime {
|
||||
(message) => this.observeWireMessage(message),
|
||||
),
|
||||
);
|
||||
if (!child) void this.connection.closed.then(() => this.handleUnexpectedTransportClose());
|
||||
void this.connection.closed.then(() => {
|
||||
if (child) {
|
||||
// The pipe can close and reject pending RPCs before the child emits "close".
|
||||
this.hadWorkAtTransportClose = this.hasPendingWork();
|
||||
} else {
|
||||
this.handleUnexpectedExit("ACP transport closed unexpectedly");
|
||||
}
|
||||
return undefined;
|
||||
});
|
||||
child?.on("error", (error) => {
|
||||
const message = describeError(error);
|
||||
this.processFailed = true;
|
||||
@@ -785,16 +802,7 @@ class AcpRuntime {
|
||||
});
|
||||
});
|
||||
child?.once("close", (code, signal) => {
|
||||
if (this.closing || this.processFailed || !this.nativeSessionId) return;
|
||||
const message = `ACP process exited (${signal ?? code ?? "unknown"})`;
|
||||
this.processFailed = true;
|
||||
this.processFailureMessage = message;
|
||||
this.settlePendingWork(message);
|
||||
this.emit({
|
||||
type: "session.runtime_failed",
|
||||
sessionId: this.options.boundarySessionId,
|
||||
error: { message },
|
||||
});
|
||||
this.handleUnexpectedExit(`ACP process exited (${signal ?? code ?? "unknown"})`);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -882,6 +890,10 @@ class AcpRuntime {
|
||||
});
|
||||
this.emitConfig();
|
||||
await this.finishSessionOpen(isConnectionClosed);
|
||||
this.canReopen =
|
||||
input.config.persist &&
|
||||
this.agentCapabilities.loadSession === true &&
|
||||
sessionCapabilities.includes("session.persistence");
|
||||
return sessionCapabilities;
|
||||
}
|
||||
|
||||
@@ -2096,11 +2108,13 @@ class AcpRuntime {
|
||||
return result;
|
||||
}
|
||||
|
||||
private handleUnexpectedTransportClose(): void {
|
||||
private handleUnexpectedExit(message: string): void {
|
||||
if (this.closing || this.processFailed) return;
|
||||
const message = "ACP transport closed unexpectedly";
|
||||
this.processFailed = true;
|
||||
this.processFailureMessage = message;
|
||||
const wasIdle = !this.hadWorkAtTransportClose && !this.hasPendingWork();
|
||||
// A clean close lets the host reopen the session on the next prompt.
|
||||
if (this.canReopen && wasIdle && this.options.onRetired?.()) return;
|
||||
this.settlePendingWork(message);
|
||||
if (!this.nativeSessionId) return;
|
||||
this.emit({
|
||||
@@ -2110,6 +2124,10 @@ class AcpRuntime {
|
||||
});
|
||||
}
|
||||
|
||||
private hasPendingWork(): boolean {
|
||||
return this.activePrompt !== null || this.configTransaction || this.permissions.size > 0;
|
||||
}
|
||||
|
||||
private cancelPendingPermissions(): boolean {
|
||||
if (this.permissions.size === 0) return false;
|
||||
for (const permission of this.permissions.values()) {
|
||||
|
||||
@@ -1254,31 +1254,177 @@ lines.on("line", (line) => {
|
||||
expect(harness.instances[1]).toMatchObject({ readsCanceled: true, writesClosed: true });
|
||||
});
|
||||
|
||||
it("publishes runtime failure on unexpected connector EOF", async () => {
|
||||
const harness = connectorHarness();
|
||||
const registration = runAcpProvider({
|
||||
id: "eof-acp",
|
||||
label: "EOF ACP",
|
||||
connector: harness.connector,
|
||||
it.each([
|
||||
{ loadSession: false, offersPersistence: true, persist: true },
|
||||
{ loadSession: true, offersPersistence: false, persist: true },
|
||||
{ loadSession: true, offersPersistence: true, persist: false },
|
||||
])(
|
||||
"reports connector EOF with loadSession=$loadSession, offered persistence=$offersPersistence, persist=$persist",
|
||||
async ({ loadSession, offersPersistence, persist }) => {
|
||||
const probe = connectorHarness({ capabilities: { loadSession: true } });
|
||||
const { connector, instances } = connectorHarness({ capabilities: { loadSession } });
|
||||
const registration = runAcpProvider({
|
||||
id: "eof-acp",
|
||||
label: "EOF ACP",
|
||||
connector: () => (probe.instances.length === 0 ? probe.connector() : connector()),
|
||||
});
|
||||
const connection = await registration.connect({
|
||||
versions: [1],
|
||||
capabilities: offersPersistence
|
||||
? ["prompt.message", "session.persistence"]
|
||||
: ["prompt.message"],
|
||||
});
|
||||
const events: ProviderEvent[] = [];
|
||||
connection.onEvent((event) => events.push(event));
|
||||
try {
|
||||
const input = openInput();
|
||||
await connection.send({ ...input, config: { ...input.config, persist } });
|
||||
await waitForEvent(events, (event) => event.type === "session.ready");
|
||||
instances[0]!.closeFromAgent();
|
||||
await expect(
|
||||
waitForEvent(
|
||||
events,
|
||||
(event) => event.type === "session.closed" || event.type === "session.runtime_failed",
|
||||
),
|
||||
).resolves.toMatchObject({
|
||||
type: "session.runtime_failed",
|
||||
sessionId: "session-1",
|
||||
error: { message: "ACP transport closed unexpectedly" },
|
||||
});
|
||||
} finally {
|
||||
await connection.close();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it("retires an idle resumable session on unexpected connector EOF", async () => {
|
||||
const { connector, instances } = connectorHarness({
|
||||
capabilities: { loadSession: true },
|
||||
});
|
||||
const registration = runAcpProvider({ id: "eof-acp", label: "EOF ACP", connector });
|
||||
const connection = await registration.connect({
|
||||
versions: [1],
|
||||
capabilities: ["prompt.message"],
|
||||
capabilities: ["prompt.message", "session.persistence"],
|
||||
});
|
||||
const events: ProviderEvent[] = [];
|
||||
connection.onEvent((event) => events.push(event));
|
||||
await connection.send(openInput());
|
||||
await waitForEvent(events, (event) => event.type === "session.ready");
|
||||
try {
|
||||
await connection.send(openInput());
|
||||
await waitForEvent(events, (event) => event.type === "session.ready");
|
||||
instances[1]!.closeFromAgent();
|
||||
await expect(
|
||||
waitForEvent(
|
||||
events,
|
||||
(event) => event.type === "session.closed" || event.type === "session.runtime_failed",
|
||||
),
|
||||
).resolves.toEqual({ type: "session.closed", sessionId: "session-1" });
|
||||
expect(events.some((event) => event.type === "session.runtime_failed")).toBe(false);
|
||||
} finally {
|
||||
await connection.close();
|
||||
}
|
||||
expect(instances[1]!.writesClosed).toBe(true);
|
||||
});
|
||||
|
||||
harness.instances[1]!.closeFromAgent();
|
||||
it.each(["configuration", "permission"] as const)(
|
||||
"reports connector EOF while a resumable session is waiting for %s",
|
||||
async (work) => {
|
||||
const { connector, instances } = connectorHarness({
|
||||
capabilities: { loadSession: true },
|
||||
configOptions: [
|
||||
{
|
||||
id: "model",
|
||||
name: "Model",
|
||||
category: "model",
|
||||
type: "select",
|
||||
currentValue: "a",
|
||||
options: [
|
||||
{ name: "A", value: "a" },
|
||||
{ name: "B", value: "b" },
|
||||
],
|
||||
},
|
||||
],
|
||||
handleRequest: (_instance, request) => request.method === "session/set_config_option",
|
||||
});
|
||||
const registration = runAcpProvider({ id: "eof-acp", label: "EOF ACP", connector });
|
||||
const connection = await registration.connect({
|
||||
versions: [1],
|
||||
capabilities: ["prompt.message", "session.persistence", "session.configure", "permission"],
|
||||
});
|
||||
const events: ProviderEvent[] = [];
|
||||
connection.onEvent((event) => events.push(event));
|
||||
try {
|
||||
await connection.send(openInput());
|
||||
await waitForEvent(events, (event) => event.type === "session.ready");
|
||||
const agent = instances[1]!;
|
||||
if (work === "configuration") {
|
||||
await connection.send({
|
||||
type: "session.configure",
|
||||
requestId: "configure-1",
|
||||
sessionId: "session-1",
|
||||
changes: { model: "b" },
|
||||
});
|
||||
await expect.poll(() => countRequests(agent, "session/set_config_option")).toBe(1);
|
||||
} else {
|
||||
void agent.request("session/request_permission", {
|
||||
sessionId: "connector-session",
|
||||
toolCall: { toolCallId: "tool-1", title: "Run tool", status: "pending" },
|
||||
options: [{ optionId: "allow-once", name: "Allow once", kind: "allow_once" }],
|
||||
});
|
||||
await waitForEvent(events, (event) => event.type === "session.permission");
|
||||
}
|
||||
agent.closeFromAgent();
|
||||
await expect(
|
||||
waitForEvent(
|
||||
events,
|
||||
(event) => event.type === "session.closed" || event.type === "session.runtime_failed",
|
||||
),
|
||||
).resolves.toMatchObject({ type: "session.runtime_failed", sessionId: "session-1" });
|
||||
} finally {
|
||||
await connection.close();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
await expect(
|
||||
waitForEvent(events, (event) => event.type === "session.runtime_failed"),
|
||||
).resolves.toMatchObject({
|
||||
sessionId: "session-1",
|
||||
error: { message: expect.stringContaining("closed") },
|
||||
});
|
||||
await connection.close();
|
||||
it("reports a resumable ACP subprocess exit during a prompt", async () => {
|
||||
const executable = await fakeAcp(`
|
||||
const readline = require("node:readline");
|
||||
readline.createInterface({ input: process.stdin }).on("line", (line) => {
|
||||
const { id, method, params } = JSON.parse(line);
|
||||
if (method === "session/prompt") process.exit(2);
|
||||
if (id === undefined) return;
|
||||
const result = method === "initialize"
|
||||
? { protocolVersion: params.protocolVersion, agentCapabilities: { loadSession: true } }
|
||||
: { sessionId: "native-1" };
|
||||
process.stdout.write(JSON.stringify({ jsonrpc: "2.0", id, result }) + "\\n");
|
||||
});`);
|
||||
const { connection, events } = await connect(executable, [
|
||||
"prompt.message",
|
||||
"session.persistence",
|
||||
]);
|
||||
try {
|
||||
await connection.send(openInput());
|
||||
await waitForEvent(events, (event) => event.type === "session.ready");
|
||||
await connection.send({
|
||||
type: "session.prompt",
|
||||
sessionId: "session-1",
|
||||
prompt: {
|
||||
clientMessageId: "prompt-1",
|
||||
delivery: "auto",
|
||||
input: { type: "message", content: [{ type: "text", text: "exit" }] },
|
||||
},
|
||||
});
|
||||
await expect(
|
||||
waitForEvent(
|
||||
events,
|
||||
(event) => event.type === "session.closed" || event.type === "session.runtime_failed",
|
||||
),
|
||||
).resolves.toMatchObject({
|
||||
type: "session.runtime_failed",
|
||||
error: { message: "ACP process exited (2)" },
|
||||
});
|
||||
} finally {
|
||||
await connection.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("settles an active auto prompt before admitting its auto replacement", async () => {
|
||||
@@ -3551,6 +3697,7 @@ describe("deferTurnOnRunningTools", () => {
|
||||
|
||||
it("fails a deferred turn cleanly when the transport closes unexpectedly", async () => {
|
||||
const { connector, instances } = connectorHarness({
|
||||
capabilities: { loadSession: true },
|
||||
handleRequest(instance, request) {
|
||||
if (request.method !== "session/prompt") return false;
|
||||
instance.notify("session/update", {
|
||||
@@ -3577,7 +3724,7 @@ describe("deferTurnOnRunningTools", () => {
|
||||
});
|
||||
const connection = await registration.connect({
|
||||
versions: [1],
|
||||
capabilities: ["prompt.message"],
|
||||
capabilities: ["prompt.message", "session.persistence"],
|
||||
});
|
||||
const events: ProviderEvent[] = [];
|
||||
connection.onEvent((event) => events.push(event));
|
||||
@@ -3610,6 +3757,8 @@ describe("deferTurnOnRunningTools", () => {
|
||||
event.turnId === "acp:crash-turn" &&
|
||||
event.state === "failed",
|
||||
);
|
||||
await waitForEvent(events, (event) => event.type === "session.runtime_failed");
|
||||
expect(events.some((event) => event.type === "session.closed")).toBe(false);
|
||||
} finally {
|
||||
await connection.close();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
DaemonAuthPasswordSetRequestSchema,
|
||||
DaemonAuthPasswordSetResponseSchema,
|
||||
DaemonGetStatusResponseSchema,
|
||||
ServerInfoStatusPayloadSchema,
|
||||
SessionInboundMessageSchema,
|
||||
SessionOutboundMessageSchema,
|
||||
} from "./messages.js";
|
||||
import { validateWSOutboundMessage } from "./validation/ws-outbound.js";
|
||||
|
||||
describe("daemon password management protocol messages", () => {
|
||||
it("parses daemon.auth.password.set.request for set, change, and remove", () => {
|
||||
const setReq = DaemonAuthPasswordSetRequestSchema.parse({
|
||||
type: "daemon.auth.password.set.request",
|
||||
requestId: "req-1",
|
||||
password: "new-password-123",
|
||||
});
|
||||
expect(setReq).toEqual({
|
||||
type: "daemon.auth.password.set.request",
|
||||
requestId: "req-1",
|
||||
password: "new-password-123",
|
||||
});
|
||||
|
||||
const changeReq = SessionInboundMessageSchema.parse({
|
||||
type: "daemon.auth.password.set.request",
|
||||
requestId: "req-2",
|
||||
password: "updated-password-456",
|
||||
currentPassword: "new-password-123",
|
||||
});
|
||||
expect(changeReq).toMatchObject({
|
||||
type: "daemon.auth.password.set.request",
|
||||
currentPassword: "new-password-123",
|
||||
});
|
||||
|
||||
const removeReq = SessionInboundMessageSchema.parse({
|
||||
type: "daemon.auth.password.set.request",
|
||||
requestId: "req-3",
|
||||
password: null,
|
||||
currentPassword: "updated-password-456",
|
||||
});
|
||||
expect(removeReq).toMatchObject({
|
||||
type: "daemon.auth.password.set.request",
|
||||
password: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("parses daemon.auth.password.set.response through Zod and the generated WS outbound validator", () => {
|
||||
const response = {
|
||||
type: "daemon.auth.password.set.response" as const,
|
||||
payload: {
|
||||
requestId: "req-1",
|
||||
passwordConfigured: true,
|
||||
disconnectedSessionCount: 2,
|
||||
},
|
||||
};
|
||||
|
||||
expect(DaemonAuthPasswordSetResponseSchema.parse(response)).toEqual(response);
|
||||
expect(SessionOutboundMessageSchema.parse(response)).toEqual(response);
|
||||
|
||||
const parsed = validateWSOutboundMessage({ type: "session", message: response });
|
||||
expect(parsed.success).toBe(true);
|
||||
if (parsed.success) {
|
||||
expect(parsed.data).toEqual({ type: "session", message: response });
|
||||
}
|
||||
});
|
||||
|
||||
it("accepts optional password status fields on server_info while remaining backward-compatible", () => {
|
||||
const legacy = ServerInfoStatusPayloadSchema.parse({
|
||||
status: "server_info",
|
||||
serverId: "srv-1",
|
||||
});
|
||||
expect(legacy.passwordConfigured).toBeUndefined();
|
||||
expect(legacy.passwordManagedByEnv).toBeUndefined();
|
||||
expect(legacy.localCredentialAuth).toBeUndefined();
|
||||
|
||||
const modern = {
|
||||
status: "server_info" as const,
|
||||
serverId: "srv-1",
|
||||
passwordConfigured: true,
|
||||
passwordManagedByEnv: false,
|
||||
localCredentialAuth: true,
|
||||
features: {
|
||||
daemonPasswordManagement: true,
|
||||
},
|
||||
};
|
||||
const parsedModern = ServerInfoStatusPayloadSchema.parse(modern);
|
||||
expect(parsedModern.passwordConfigured).toBe(true);
|
||||
expect(parsedModern.passwordManagedByEnv).toBe(false);
|
||||
expect(parsedModern.localCredentialAuth).toBe(true);
|
||||
expect(parsedModern.features?.daemonPasswordManagement).toBe(true);
|
||||
|
||||
const outbound = validateWSOutboundMessage({
|
||||
type: "session",
|
||||
message: { type: "status", payload: modern },
|
||||
});
|
||||
expect(outbound.success).toBe(true);
|
||||
});
|
||||
|
||||
it("accepts optional password status fields on daemon.get_status.response", () => {
|
||||
const basePayload = {
|
||||
requestId: "req-status",
|
||||
serverId: "srv-1",
|
||||
pid: 1234,
|
||||
nodePath: "/usr/bin/node",
|
||||
listen: "127.0.0.1:6767",
|
||||
providers: [],
|
||||
};
|
||||
const legacy = DaemonGetStatusResponseSchema.parse({
|
||||
type: "daemon.get_status.response",
|
||||
payload: basePayload,
|
||||
});
|
||||
expect(legacy.payload.passwordConfigured).toBeUndefined();
|
||||
expect(legacy.payload.passwordManagedByEnv).toBeUndefined();
|
||||
|
||||
const modern = DaemonGetStatusResponseSchema.parse({
|
||||
type: "daemon.get_status.response",
|
||||
payload: {
|
||||
...basePayload,
|
||||
passwordConfigured: true,
|
||||
passwordManagedByEnv: true,
|
||||
},
|
||||
});
|
||||
expect(modern.payload.passwordConfigured).toBe(true);
|
||||
expect(modern.payload.passwordManagedByEnv).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -1695,6 +1695,13 @@ export const DaemonConfigReloadRequestSchema = z.object({
|
||||
requestId: z.string(),
|
||||
});
|
||||
|
||||
export const DaemonAuthPasswordSetRequestSchema = z.object({
|
||||
type: z.literal("daemon.auth.password.set.request"),
|
||||
requestId: z.string(),
|
||||
password: z.string().nullable(),
|
||||
currentPassword: z.string().optional(),
|
||||
});
|
||||
|
||||
export const HubManagementDaemonConnectRequestSchema = z.object({
|
||||
type: z.literal("hub.management.daemon.connect.request"),
|
||||
requestId: z.string(),
|
||||
@@ -3891,6 +3898,7 @@ export const SessionInboundMessageSchema = z.discriminatedUnion("type", [
|
||||
DaemonTailscaleSetRequestSchema,
|
||||
DaemonGetPairingOfferRequestSchema,
|
||||
DaemonConfigReloadRequestSchema,
|
||||
DaemonAuthPasswordSetRequestSchema,
|
||||
HubManagementDaemonConnectRequestSchema,
|
||||
HubManagementDaemonGetStatusRequestSchema,
|
||||
HubManagementDaemonDisconnectRequestSchema,
|
||||
@@ -4252,6 +4260,9 @@ export const ServerInfoStatusPayloadSchema = z
|
||||
permissions: z.array(DaemonPermissionSchema).optional(),
|
||||
// COMPAT(desktopManaged): added in v0.1.X, remove optional parsing after 2027-01-16.
|
||||
desktopManaged: z.boolean().optional(),
|
||||
passwordConfigured: z.boolean().optional(),
|
||||
passwordManagedByEnv: z.boolean().optional(),
|
||||
localCredentialAuth: z.boolean().optional(),
|
||||
capabilities: ServerCapabilitiesFromUnknownSchema.optional(),
|
||||
// COMPAT(providersSnapshot): added in v0.1.48, remove gating when all clients use snapshot
|
||||
features: z
|
||||
@@ -4325,6 +4336,8 @@ export const ServerInfoStatusPayloadSchema = z
|
||||
connectedClients: z.boolean().optional(),
|
||||
// COMPAT(daemonConfigReload): added in v0.4.0, remove gate after 2027-02-14.
|
||||
daemonConfigReload: z.boolean().optional(),
|
||||
// COMPAT(daemonPasswordManagement): added in v0.19.x, remove gate after 2027-06-15.
|
||||
daemonPasswordManagement: z.boolean().optional(),
|
||||
// COMPAT(speechSettings): added in v0.12.0, remove gate after 2027-04-18.
|
||||
speechSettings: z.boolean().optional(),
|
||||
// COMPAT(relayConfig): added in v0.2.6, remove gate after 2027-01-31.
|
||||
@@ -6049,10 +6062,21 @@ export const DaemonGetStatusResponseSchema = z.object({
|
||||
// Set when this host's terminals are held by a terminal worker from a newer Paseo, which
|
||||
// this daemon leaves running but cannot drive: why, and what the user can do.
|
||||
terminalsUnavailable: z.string().optional(),
|
||||
passwordConfigured: z.boolean().optional(),
|
||||
passwordManagedByEnv: z.boolean().optional(),
|
||||
})
|
||||
.passthrough(),
|
||||
});
|
||||
|
||||
export const DaemonAuthPasswordSetResponseSchema = z.object({
|
||||
type: z.literal("daemon.auth.password.set.response"),
|
||||
payload: z.object({
|
||||
requestId: z.string(),
|
||||
passwordConfigured: z.boolean(),
|
||||
disconnectedSessionCount: z.number().int().nonnegative(),
|
||||
}),
|
||||
});
|
||||
|
||||
export const HubRelationshipStatusSchema = z.object({
|
||||
state: z.enum([
|
||||
"not_connected",
|
||||
@@ -8330,6 +8354,7 @@ export const SessionOutboundMessageSchema = z.discriminatedUnion("type", [
|
||||
DaemonTailscaleSetResponseSchema,
|
||||
DaemonGetPairingOfferResponseSchema,
|
||||
DaemonConfigReloadResponseSchema,
|
||||
DaemonAuthPasswordSetResponseSchema,
|
||||
HubManagementDaemonConnectResponseSchema,
|
||||
HubManagementDaemonGetStatusResponseSchema,
|
||||
HubManagementDaemonDisconnectResponseSchema,
|
||||
@@ -8612,6 +8637,8 @@ export type ListAvailableProvidersResponse = z.infer<typeof ListAvailableProvide
|
||||
export type DaemonGetStatusResponse = z.infer<typeof DaemonGetStatusResponseSchema>;
|
||||
export type DaemonGetPairingOfferResponse = z.infer<typeof DaemonGetPairingOfferResponseSchema>;
|
||||
export type DaemonConfigReloadResponse = z.infer<typeof DaemonConfigReloadResponseSchema>;
|
||||
export type DaemonAuthPasswordSetRequest = z.infer<typeof DaemonAuthPasswordSetRequestSchema>;
|
||||
export type DaemonAuthPasswordSetResponse = z.infer<typeof DaemonAuthPasswordSetResponseSchema>;
|
||||
export type DiagnosticsResponse = z.infer<typeof DiagnosticsResponseSchema>;
|
||||
export type GetProvidersSnapshotResponseMessage = z.infer<
|
||||
typeof GetProvidersSnapshotResponseMessageSchema
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,397 @@
|
||||
import type { AgentAddress } from "@getpaseo/protocol/addresses";
|
||||
import { getParentAddressFromLabels } from "@getpaseo/protocol/agent-labels";
|
||||
import type { ProviderOptions } from "@getpaseo/protocol/agent-types";
|
||||
|
||||
import type { AgentManager, ManagedAgent } from "./agent-manager.js";
|
||||
import type { AgentMode, AgentOptionControl, AgentProvider } from "./agent-sdk-types.js";
|
||||
import type { AgentStorage, StoredAgentRecord } from "./agent-storage.js";
|
||||
import {
|
||||
checkModeCeiling,
|
||||
formatModePrivilegeLabel,
|
||||
type AgentModePrivilege,
|
||||
} from "./create-agent-mode.js";
|
||||
import { applyProviderOptionsPatch } from "./option-controls.js";
|
||||
import type { ProviderSnapshotManager } from "./provider-snapshot-manager.js";
|
||||
import { PaseoToolInputError } from "./tools/types.js";
|
||||
|
||||
const RESERVED_AGENT_LABEL_PREFIX = "paseo.";
|
||||
|
||||
export type AgentCallerLineage = "self" | "descendant" | "unrelated";
|
||||
export type AgentLineageScope = "descendant" | "self-or-descendant";
|
||||
|
||||
interface AgentRecordSummary {
|
||||
id: string;
|
||||
provider: AgentProvider;
|
||||
cwd: string;
|
||||
labels: Record<string, string>;
|
||||
modeId: string | null;
|
||||
providerOptions: ProviderOptions | undefined;
|
||||
controls: AgentOptionControl[] | undefined;
|
||||
availableModes: readonly AgentMode[] | undefined;
|
||||
}
|
||||
|
||||
export interface LineageTarget {
|
||||
agentId: string;
|
||||
serverId?: string;
|
||||
labels?: Record<string, string>;
|
||||
lookupLabels?: (address: AgentAddress) => Promise<Record<string, string> | undefined>;
|
||||
}
|
||||
|
||||
export type CeilingTarget =
|
||||
| {
|
||||
agentId: string;
|
||||
modeId?: string;
|
||||
featurePatch?: ProviderOptions;
|
||||
}
|
||||
| {
|
||||
provider: AgentProvider;
|
||||
cwd?: string;
|
||||
modeId?: string;
|
||||
inheritedProviderOptions?: ProviderOptions;
|
||||
providerOptions?: ProviderOptions;
|
||||
availableModes?: readonly AgentMode[];
|
||||
/** When true, omitting modeId on the same provider inherits caller's mode. */
|
||||
inheritFromSameProvider?: boolean;
|
||||
/** When true, resolves the target config under `unattended: true` before checking ceiling. */
|
||||
resolveUnattended?: boolean;
|
||||
};
|
||||
|
||||
export interface CreateAgentCallerPolicyInput {
|
||||
callerAgentId?: string;
|
||||
serverId?: string;
|
||||
agentManager: Pick<AgentManager, "getAgent" | "effectiveOptionsFor">;
|
||||
agentStorage: Pick<AgentStorage, "get">;
|
||||
providerSnapshotManager: Pick<ProviderSnapshotManager, "classifyMode" | "resolveCreateConfig">;
|
||||
}
|
||||
|
||||
export interface AgentCallerPolicy {
|
||||
/** Rejects caller-supplied labels in the reserved `paseo.*` namespace. */
|
||||
assertMutableLabels(labels: Record<string, string> | undefined): void;
|
||||
|
||||
/** Returns whether the target agent is a descendant of the caller (excluding self). */
|
||||
isDescendant(target: LineageTarget): Promise<boolean>;
|
||||
|
||||
/** Enforces `descendant` or `self-or-descendant` lineage against a local or remote target. */
|
||||
assertLineage(target: LineageTarget, scope: AgentLineageScope, action: string): Promise<void>;
|
||||
|
||||
/** Enforces the caller's mode and unattended-option ceiling against a target agent or config. */
|
||||
assertWithinCeiling(target: CeilingTarget): Promise<void>;
|
||||
}
|
||||
|
||||
export function isReservedAgentLabel(label: string): boolean {
|
||||
return label.trim().toLowerCase().startsWith(RESERVED_AGENT_LABEL_PREFIX);
|
||||
}
|
||||
|
||||
export async function resolveAgentLineage(input: {
|
||||
caller: AgentAddress;
|
||||
target: AgentAddress;
|
||||
targetLabels?: Record<string, string>;
|
||||
lookupLabels: (address: AgentAddress) => Promise<Record<string, string> | undefined>;
|
||||
}): Promise<AgentCallerLineage> {
|
||||
if (
|
||||
input.target.serverId === input.caller.serverId &&
|
||||
input.target.agentId === input.caller.agentId
|
||||
) {
|
||||
return "self";
|
||||
}
|
||||
const visited = new Set<string>([`${input.target.serverId}:${input.target.agentId}`]);
|
||||
let current = input.target;
|
||||
let labels = input.targetLabels ?? (await input.lookupLabels(current));
|
||||
while (labels) {
|
||||
const parent = getParentAddressFromLabels(labels, current.serverId);
|
||||
if (!parent) return "unrelated";
|
||||
if (parent.serverId === input.caller.serverId && parent.agentId === input.caller.agentId) {
|
||||
return "descendant";
|
||||
}
|
||||
const key = `${parent.serverId}:${parent.agentId}`;
|
||||
if (visited.has(key)) return "unrelated";
|
||||
visited.add(key);
|
||||
current = parent;
|
||||
labels = await input.lookupLabels(current);
|
||||
}
|
||||
return "unrelated";
|
||||
}
|
||||
|
||||
function summarizeLiveAgent(agent: ManagedAgent): AgentRecordSummary {
|
||||
return {
|
||||
id: agent.id,
|
||||
provider: agent.provider,
|
||||
cwd: agent.cwd,
|
||||
labels: agent.labels ?? {},
|
||||
modeId: agent.currentModeId ?? agent.config?.modeId ?? null,
|
||||
providerOptions: agent.effectiveOptions ?? agent.config?.providerOptions,
|
||||
controls: agent.controls,
|
||||
availableModes: agent.availableModes,
|
||||
};
|
||||
}
|
||||
|
||||
function summarizeStoredAgent(
|
||||
record: StoredAgentRecord,
|
||||
providerOptions: ProviderOptions | undefined,
|
||||
): AgentRecordSummary {
|
||||
return {
|
||||
id: record.id,
|
||||
provider: record.provider,
|
||||
cwd: record.cwd,
|
||||
labels: record.labels,
|
||||
modeId: record.lastModeId ?? record.config?.modeId ?? null,
|
||||
providerOptions,
|
||||
controls: record.controls,
|
||||
availableModes: undefined,
|
||||
};
|
||||
}
|
||||
|
||||
const OWNER_POLICY: AgentCallerPolicy = {
|
||||
assertMutableLabels() {},
|
||||
async isDescendant() {
|
||||
return true;
|
||||
},
|
||||
async assertLineage() {},
|
||||
async assertWithinCeiling() {},
|
||||
};
|
||||
|
||||
export function createAgentCallerPolicy(input: CreateAgentCallerPolicyInput): AgentCallerPolicy {
|
||||
const { callerAgentId, agentManager, agentStorage, providerSnapshotManager } = input;
|
||||
if (!callerAgentId) return OWNER_POLICY;
|
||||
|
||||
const localServerId = input.serverId ?? "self";
|
||||
const callerAddress: AgentAddress = { serverId: localServerId, agentId: callerAgentId };
|
||||
|
||||
function effectiveOptions(
|
||||
provider: AgentProvider,
|
||||
own: ProviderOptions | undefined,
|
||||
): ProviderOptions | undefined {
|
||||
const resolved = agentManager.effectiveOptionsFor(provider, own);
|
||||
return Object.keys(resolved).length > 0 ? resolved : undefined;
|
||||
}
|
||||
|
||||
function applyEffectiveOptionPatch(
|
||||
provider: AgentProvider,
|
||||
currentEffective: ProviderOptions | undefined,
|
||||
patch: ProviderOptions | undefined,
|
||||
): ProviderOptions | undefined {
|
||||
if (!patch) return currentEffective;
|
||||
const nonNull = Object.fromEntries(Object.entries(patch).filter(([, value]) => value != null));
|
||||
const resolved = agentManager.effectiveOptionsFor(provider, nonNull);
|
||||
const sent = Object.fromEntries(Object.keys(patch).map((key) => [key, resolved[key] ?? null]));
|
||||
const next = applyProviderOptionsPatch({ options: currentEffective, patch: sent });
|
||||
return Object.keys(next).length > 0 ? next : undefined;
|
||||
}
|
||||
|
||||
async function lookupLocalAgent(agentId: string): Promise<AgentRecordSummary | null> {
|
||||
const live = agentManager.getAgent(agentId);
|
||||
if (live) return summarizeLiveAgent(live);
|
||||
const stored = await agentStorage.get(agentId);
|
||||
if (!stored) return null;
|
||||
return summarizeStoredAgent(
|
||||
stored,
|
||||
effectiveOptions(stored.provider, stored.config?.providerOptions ?? undefined),
|
||||
);
|
||||
}
|
||||
|
||||
function classifyAgent(
|
||||
agent: AgentRecordSummary,
|
||||
overrides: {
|
||||
modeId?: string | null;
|
||||
providerOptions?: ProviderOptions;
|
||||
useDefaultModeFallback?: boolean;
|
||||
} = {},
|
||||
): AgentModePrivilege {
|
||||
return providerSnapshotManager.classifyMode({
|
||||
provider: agent.provider,
|
||||
cwd: agent.cwd,
|
||||
modeId: overrides.modeId !== undefined ? overrides.modeId : agent.modeId,
|
||||
providerOptions:
|
||||
overrides.providerOptions !== undefined ? overrides.providerOptions : agent.providerOptions,
|
||||
controls: agent.controls,
|
||||
availableModes: agent.availableModes,
|
||||
useDefaultModeFallback: overrides.useDefaultModeFallback,
|
||||
});
|
||||
}
|
||||
|
||||
async function requireCaller(): Promise<{
|
||||
agent: AgentRecordSummary;
|
||||
privilege: AgentModePrivilege;
|
||||
}> {
|
||||
const agent = await lookupLocalAgent(callerAgentId!);
|
||||
if (!agent) throw new PaseoToolInputError(`Parent agent ${callerAgentId} not found`);
|
||||
return { agent, privilege: classifyAgent(agent, { useDefaultModeFallback: true }) };
|
||||
}
|
||||
|
||||
async function lineageOf(target: LineageTarget): Promise<AgentCallerLineage> {
|
||||
const targetServerId = target.serverId ?? localServerId;
|
||||
return resolveAgentLineage({
|
||||
caller: callerAddress,
|
||||
target: { serverId: targetServerId, agentId: target.agentId },
|
||||
targetLabels: target.labels,
|
||||
lookupLabels: async (address) =>
|
||||
address.serverId === localServerId
|
||||
? (await lookupLocalAgent(address.agentId))?.labels
|
||||
: target.lookupLabels?.(address),
|
||||
});
|
||||
}
|
||||
|
||||
function assertMutableLabels(labels: Record<string, string> | undefined): void {
|
||||
if (!labels) return;
|
||||
const reserved = Object.keys(labels).filter(isReservedAgentLabel);
|
||||
if (reserved.length > 0) {
|
||||
throw new PaseoToolInputError(
|
||||
`Agent callers cannot write reserved Paseo labels: ${reserved.join(", ")}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async function isDescendant(target: LineageTarget): Promise<boolean> {
|
||||
return (await lineageOf(target)) === "descendant";
|
||||
}
|
||||
|
||||
async function assertLineage(
|
||||
target: LineageTarget,
|
||||
scope: AgentLineageScope,
|
||||
action: string,
|
||||
): Promise<void> {
|
||||
const lineage = await lineageOf(target);
|
||||
if (scope === "descendant") {
|
||||
if (lineage === "self") {
|
||||
throw new PaseoToolInputError(`Agent ${callerAgentId} cannot ${action} itself`);
|
||||
}
|
||||
if (lineage !== "descendant") {
|
||||
throw new PaseoToolInputError(
|
||||
`Agent ${callerAgentId} is not allowed to ${action} agent ${target.agentId}: target must be a descendant agent`,
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (lineage === "unrelated") {
|
||||
throw new PaseoToolInputError(
|
||||
`Agent ${callerAgentId} is not allowed to ${action} agent ${target.agentId}: target must be the caller or a descendant agent`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function assertAllowed(caller: AgentModePrivilege, target: AgentModePrivilege): void {
|
||||
const check = checkModeCeiling(caller, target);
|
||||
if (!check.allowed) throw new PaseoToolInputError(check.reason);
|
||||
}
|
||||
|
||||
async function assertExistingAgentCeiling(
|
||||
target: Extract<CeilingTarget, { agentId: string }>,
|
||||
): Promise<void> {
|
||||
if (target.modeId === undefined && target.featurePatch === undefined) return;
|
||||
const { agent: caller, privilege: callerPrivilege } = await requireCaller();
|
||||
if (callerPrivilege.isUnattended) return;
|
||||
|
||||
const existing = target.agentId === caller.id ? caller : await lookupLocalAgent(target.agentId);
|
||||
if (!existing) throw new PaseoToolInputError(`Agent ${target.agentId} not found`);
|
||||
|
||||
const mergedFeatures = applyEffectiveOptionPatch(
|
||||
existing.provider,
|
||||
existing.providerOptions,
|
||||
target.featurePatch,
|
||||
);
|
||||
if (target.modeId !== undefined) {
|
||||
assertAllowed(
|
||||
callerPrivilege,
|
||||
classifyAgent(existing, { modeId: target.modeId, providerOptions: mergedFeatures }),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (
|
||||
!classifyAgent(existing).isUnattended &&
|
||||
classifyAgent(existing, { providerOptions: mergedFeatures }).isUnattended
|
||||
) {
|
||||
throw new PaseoToolInputError(
|
||||
`Agent caller in mode '${formatModePrivilegeLabel(callerPrivilege)}' (${caller.provider}) cannot enable unattended options on '${existing.provider}'`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async function resolveScheduleConfig(
|
||||
callerPrivilege: AgentModePrivilege,
|
||||
provider: AgentProvider,
|
||||
cwd: string,
|
||||
modeId: string | undefined,
|
||||
providerOptions: ProviderOptions | undefined,
|
||||
): Promise<{ modeId: string; providerOptions: ProviderOptions | undefined }> {
|
||||
let resolvedModeId = modeId;
|
||||
let resolvedOptions = providerOptions;
|
||||
try {
|
||||
const resolved = await providerSnapshotManager.resolveCreateConfig({
|
||||
cwd,
|
||||
provider,
|
||||
requestedMode: modeId,
|
||||
providerOptions,
|
||||
parent: null,
|
||||
unattended: true,
|
||||
});
|
||||
resolvedModeId = resolved.modeId;
|
||||
resolvedOptions = resolved.providerOptions;
|
||||
} catch (error) {
|
||||
throw new PaseoToolInputError(error instanceof Error ? error.message : String(error));
|
||||
}
|
||||
if (resolvedModeId === undefined) {
|
||||
throw new PaseoToolInputError(
|
||||
`Agent caller in constrained mode '${formatModePrivilegeLabel(callerPrivilege)}' (${callerPrivilege.provider}) cannot schedule '${provider}' without a classified mode within its ceiling; this requires the user or an unattended caller`,
|
||||
);
|
||||
}
|
||||
return { modeId: resolvedModeId, providerOptions: resolvedOptions };
|
||||
}
|
||||
|
||||
async function assertWithinCeiling(target: CeilingTarget): Promise<void> {
|
||||
if ("agentId" in target) {
|
||||
await assertExistingAgentCeiling(target);
|
||||
return;
|
||||
}
|
||||
|
||||
const { agent: caller, privilege: callerPrivilege } = await requireCaller();
|
||||
if (callerPrivilege.isUnattended) return;
|
||||
|
||||
const sameProvider = target.provider === caller.provider;
|
||||
const cwd = target.cwd ?? caller.cwd;
|
||||
let modeId = target.modeId;
|
||||
const requestedOwn =
|
||||
target.inheritedProviderOptions || target.providerOptions
|
||||
? applyProviderOptionsPatch({
|
||||
options: target.inheritedProviderOptions,
|
||||
patch: target.providerOptions ?? {},
|
||||
})
|
||||
: undefined;
|
||||
let providerOptions = requestedOwn;
|
||||
|
||||
if (target.resolveUnattended) {
|
||||
({ modeId, providerOptions } = await resolveScheduleConfig(
|
||||
callerPrivilege,
|
||||
target.provider,
|
||||
cwd,
|
||||
modeId,
|
||||
requestedOwn,
|
||||
));
|
||||
} else if (target.inheritFromSameProvider && modeId === undefined) {
|
||||
if (!sameProvider) {
|
||||
throw new PaseoToolInputError(
|
||||
`Pass an explicit mode in settings.modeId within the caller's mode ceiling when creating an agent on provider '${target.provider}' (caller is in '${formatModePrivilegeLabel(callerPrivilege)}' on '${caller.provider}'; providers without modes require the user or an unattended caller)`,
|
||||
);
|
||||
}
|
||||
modeId = caller.modeId ?? undefined;
|
||||
}
|
||||
|
||||
const resolvedOptions =
|
||||
target.inheritFromSameProvider || target.resolveUnattended
|
||||
? effectiveOptions(target.provider, providerOptions)
|
||||
: providerOptions;
|
||||
|
||||
assertAllowed(
|
||||
callerPrivilege,
|
||||
providerSnapshotManager.classifyMode({
|
||||
provider: target.provider,
|
||||
cwd,
|
||||
modeId: modeId ?? null,
|
||||
providerOptions: resolvedOptions,
|
||||
availableModes: target.availableModes,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
return { assertMutableLabels, isDescendant, assertLineage, assertWithinCeiling };
|
||||
}
|
||||
@@ -18408,3 +18408,76 @@ test.each([
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
test("streamAgent throws AgentTurnBusyError and non-replacing steerOrReplaceActiveTurn returns busy without replacing an active turn", async () => {
|
||||
const workdir = mkdtempSync(join(tmpdir(), "agent-non-replacing-steer-"));
|
||||
class RejectingSteerSession extends SteeringTestSession {
|
||||
cancelCalls = 0;
|
||||
override async steerActiveTurn() {
|
||||
return { status: "unavailable" as const };
|
||||
}
|
||||
override async cancelRun() {
|
||||
this.cancelCalls += 1;
|
||||
await super.cancelRun();
|
||||
}
|
||||
}
|
||||
const session = new RejectingSteerSession({ provider: "codex", cwd: workdir });
|
||||
const client = new (class extends TestAgentClient {
|
||||
override async createSession(): Promise<AgentSession> {
|
||||
return session;
|
||||
}
|
||||
})();
|
||||
const storage = new AgentStorage(join(workdir, "agents"), logger);
|
||||
const manager = new AgentManager({ clients: { codex: client }, registry: storage, logger });
|
||||
const agent = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, {
|
||||
workspaceId: undefined,
|
||||
});
|
||||
const providerStarted = new Promise<void>((resolve) => {
|
||||
const unsubscribe = session.subscribe((event) => {
|
||||
if (event.type === "turn_started") {
|
||||
unsubscribe();
|
||||
resolve();
|
||||
}
|
||||
});
|
||||
});
|
||||
try {
|
||||
await startAgentRun(manager, agent.id, "initial turn", logger);
|
||||
await manager.waitForAgentRunStart(agent.id);
|
||||
await providerStarted;
|
||||
|
||||
expect(() => manager.streamAgent(agent.id, "competing turn")).toThrow(AgentTurnBusyError);
|
||||
|
||||
const steerResult = await manager.steerOrReplaceActiveTurn(
|
||||
agent.id,
|
||||
"mid-turn steer",
|
||||
undefined,
|
||||
undefined,
|
||||
false,
|
||||
);
|
||||
expect(steerResult).toEqual({ status: "busy" });
|
||||
expect(session.cancelCalls).toBe(0);
|
||||
expect(session.startPrompts).toEqual(["initial turn"]);
|
||||
|
||||
await expect(
|
||||
sendPreparedPromptToAgent({
|
||||
agentManager: manager,
|
||||
agentStorage: storage,
|
||||
agentId: agent.id,
|
||||
prompt: "mid-turn steer",
|
||||
activeTurnBehavior: "steer",
|
||||
replaceRunning: false,
|
||||
logger,
|
||||
}),
|
||||
).rejects.toBeInstanceOf(AgentTurnBusyError);
|
||||
|
||||
session.pushEvent({ type: "turn_completed", provider: "codex", turnId: "active-turn-1" });
|
||||
await vi.waitFor(() => expect(manager.hasInFlightRun(agent.id)).toBe(false));
|
||||
|
||||
await expect(
|
||||
manager.steerOrReplaceActiveTurn(agent.id, "after settle", undefined, undefined, false),
|
||||
).resolves.toEqual({ status: "inactive" });
|
||||
} finally {
|
||||
await manager.closeAgent(agent.id);
|
||||
rmSync(workdir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -583,7 +583,7 @@ export interface AgentManagerOptions {
|
||||
}
|
||||
|
||||
export type ActiveTurnSteerDispatchResult =
|
||||
| { status: "inactive" | "steered" }
|
||||
| { status: "inactive" | "steered" | "busy" }
|
||||
| { status: "replaced"; iterator: AsyncGenerator<AgentStreamEvent> };
|
||||
|
||||
export interface AgentPromptSubmissionOptions extends AgentRunOptions {
|
||||
@@ -4375,7 +4375,8 @@ export class AgentManager {
|
||||
return;
|
||||
}
|
||||
|
||||
await this.writeStoredMetadata(agentId, updates);
|
||||
const record = await this.writeStoredMetadata(agentId, updates);
|
||||
if (!record.internal) this.dispatchStoredAgentState(record);
|
||||
}
|
||||
|
||||
private async runLifecycleMutation<T>(agentId: string, mutation: () => Promise<T>): Promise<T> {
|
||||
@@ -4877,7 +4878,7 @@ export class AgentManager {
|
||||
},
|
||||
"agent.manager.stream.reject",
|
||||
);
|
||||
throw new Error(`Agent ${agentId} already has an active run`);
|
||||
throw new AgentTurnBusyError(`Agent ${agentId} already has an active run`);
|
||||
}
|
||||
|
||||
const agent = existingAgent;
|
||||
@@ -5129,6 +5130,7 @@ export class AgentManager {
|
||||
prompt: AgentPromptInput,
|
||||
options?: AgentPromptSteerOptions,
|
||||
promptStart?: ForegroundPromptStart,
|
||||
allowReplace = true,
|
||||
): 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.
|
||||
@@ -5168,6 +5170,11 @@ export class AgentManager {
|
||||
return { status: "inactive" };
|
||||
}
|
||||
|
||||
this.assertSteerAdmissionOwnsTurn(agent, expectedTurnId);
|
||||
if (!allowReplace) {
|
||||
return { status: "busy" };
|
||||
}
|
||||
|
||||
await this.beforeSteerUnavailableFallback?.({ agentId, expectedTurnId });
|
||||
this.assertSteerAdmissionOwnsTurn(agent, expectedTurnId);
|
||||
return {
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,7 +1,6 @@
|
||||
import {
|
||||
AgentTurnBusyError,
|
||||
AgentTurnChangedError,
|
||||
AgentTurnStartRejectedError,
|
||||
type PromptDispatchDisposition,
|
||||
type PromptDispatchResult,
|
||||
} from "../agent-prompt.js";
|
||||
@@ -73,6 +72,8 @@ interface Admitted extends QueuedContent {
|
||||
urgency: QueuedMessageUrgency | null;
|
||||
/** A Stop found it in the queue. It waits for a prompt admitted after that Stop. */
|
||||
held: boolean;
|
||||
/** True when explicitly released by Send now (`promote`) and allowed to replace a non-steering turn. */
|
||||
promoted: boolean;
|
||||
outOfBandDeclined: boolean;
|
||||
/** Settles once the store holds it. Nothing dispatches it before that. */
|
||||
saved: Promise<void>;
|
||||
@@ -120,6 +121,8 @@ interface DispatchRequest {
|
||||
uploadedImages: readonly UploadedImage[];
|
||||
activeTurnBehavior: "steer" | "interrupt";
|
||||
idleOnly: boolean;
|
||||
/** True when this batch may interrupt/replace an active turn if steering is unavailable. */
|
||||
replaceRunning: boolean;
|
||||
/**
|
||||
* Claim this exact prompt at provider admission. A withdrawn message or a Stop that reached
|
||||
* the recipient first invalidates it.
|
||||
@@ -210,11 +213,10 @@ export interface AgentMessageDelivery {
|
||||
*/
|
||||
enqueue(message: Message): Promise<AgentMessageReceipt>;
|
||||
/**
|
||||
* Send a prompt that does not wait its turn. Compatible messages admitted before it go ahead
|
||||
* of it in the same provider prompt, so none starts a turn of its own afterwards. When a
|
||||
* boundary (conflicting session mode, queued non-agent command, or provider switch) prevents
|
||||
* coalescing, the prompt is queued behind those messages and releases the first group at once.
|
||||
* A direct command or restart-resume travels alone.
|
||||
* Send a prompt directly without sweeping queued messages. Queued messages remain in the queue
|
||||
* and dispatch once the turn settles. A non-command prompt that starts after a Stop reopens any
|
||||
* Stop-held queue so it drains after this turn. A direct provider switch behind queued messages
|
||||
* for the current provider queues behind them so they run on the current provider first.
|
||||
*/
|
||||
sendDirect<Result extends PromptDispatchResult>(
|
||||
direct: DirectPrompt,
|
||||
@@ -261,6 +263,8 @@ export interface AgentMessageDelivery {
|
||||
const isQueued = (message: Admitted): boolean => message.state === "queued";
|
||||
const isWithdrawn = (message: Admitted): boolean => message.state === "withdrawn";
|
||||
const isUrgent = (message: Admitted): boolean => isQueued(message) && message.urgency !== null;
|
||||
const isHumanQueued = (message: Admitted): boolean =>
|
||||
message.source === null && message.urgency === null;
|
||||
const isOfferable = (message: Admitted): boolean =>
|
||||
isQueued(message) &&
|
||||
!message.outOfBandDeclined &&
|
||||
@@ -376,39 +380,10 @@ function boundaryOfAdmitted(message: Admitted): DispatchBoundary {
|
||||
};
|
||||
}
|
||||
|
||||
function boundaryOfDirect(input: {
|
||||
direct: DirectPrompt;
|
||||
includeProviderSwitch: boolean;
|
||||
}): DispatchBoundary {
|
||||
return {
|
||||
prompt: input.direct.prompt,
|
||||
source: input.direct.source,
|
||||
sessionMode: input.direct.sessionMode,
|
||||
...(input.includeProviderSwitch ? { providerSwitch: input.direct.providerSwitch } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function modeGroups(messages: readonly Admitted[]): Admitted[][] {
|
||||
return dispatchGroups({ entries: messages, boundaryOf: boundaryOfAdmitted });
|
||||
}
|
||||
|
||||
function canCoalesceDirect(input: { ahead: readonly Admitted[]; direct: DirectPrompt }): boolean {
|
||||
// A direct provider switch only carries a Stop-held queue when every held message has no
|
||||
// explicit sessionMode and the switch itself requests no mode override. Any unheld message
|
||||
// or explicit mode belongs to the current provider and must not move across providers.
|
||||
const carriesHeldSwitch =
|
||||
Boolean(input.direct.providerSwitch) &&
|
||||
!input.direct.providerSwitch?.modeId &&
|
||||
input.direct.sessionMode === undefined &&
|
||||
input.ahead.length > 0 &&
|
||||
input.ahead.every((message) => message.held && message.sessionMode === undefined);
|
||||
const entries: DispatchBoundary[] = [
|
||||
...input.ahead.map(boundaryOfAdmitted),
|
||||
boundaryOfDirect({ direct: input.direct, includeProviderSwitch: !carriesHeldSwitch }),
|
||||
];
|
||||
return dispatchGroups({ entries, boundaryOf: (entry) => entry }).length <= 1;
|
||||
}
|
||||
|
||||
function toUploadedImageAttachments(
|
||||
uploadedImages: readonly UploadedImage[] | undefined,
|
||||
): Array<UploadedFileAttachment & { role: "image" }> {
|
||||
@@ -488,6 +463,8 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
|
||||
|
||||
const isRunning = (recipientId: string): boolean =>
|
||||
Boolean(dependencies.isRunning?.(recipientId));
|
||||
const canSteer = (recipientId: string): boolean =>
|
||||
dependencies.canSteer ? dependencies.canSteer(recipientId) : true;
|
||||
const isHeld = (recipientId: string): boolean => inboxes.get(recipientId)?.phase === "held";
|
||||
|
||||
function report(error: unknown, recipientId: string, messageIds: readonly string[] = []): void {
|
||||
@@ -547,8 +524,12 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
|
||||
idleOnly: boolean,
|
||||
stopped: () => boolean,
|
||||
activeTurnBehavior?: QueuedMessageUrgency,
|
||||
allowReplace = false,
|
||||
): DispatchRequest {
|
||||
const messages = messagesOf(batch);
|
||||
const resolvedBehavior =
|
||||
activeTurnBehavior ??
|
||||
(messages.some((message) => message.urgency === "interrupt") ? "interrupt" : "steer");
|
||||
return {
|
||||
recipientId,
|
||||
idleOnly,
|
||||
@@ -561,9 +542,8 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
|
||||
prompt: formatBatch(batch),
|
||||
uploadedImages: uploadedImagesOf(batch),
|
||||
// A batch that waited for the turn to end is dispatched idle-only, so it never steers.
|
||||
activeTurnBehavior:
|
||||
activeTurnBehavior ??
|
||||
(messages.some((message) => message.urgency === "interrupt") ? "interrupt" : "steer"),
|
||||
activeTurnBehavior: resolvedBehavior,
|
||||
replaceRunning: !idleOnly && (resolvedBehavior === "interrupt" || allowReplace),
|
||||
// Every message in a batch belongs to one compatible mode group.
|
||||
sessionMode: messages.findLast((message) => message.sessionMode)?.sessionMode,
|
||||
providerSwitch: messages[0]?.providerSwitch,
|
||||
@@ -713,6 +693,58 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
|
||||
inbox.cancelTimer = schedule(QUIET_MS, () => attempt(recipientId));
|
||||
}
|
||||
|
||||
async function clearUrgency(recipientId: string, messages: Admitted[]): Promise<void> {
|
||||
if (!messages.length) return;
|
||||
for (const message of messages) {
|
||||
message.urgency = null;
|
||||
message.promoted = false;
|
||||
}
|
||||
const ids = idsOf(messages);
|
||||
await write(store.clearUrgency(recipientId, ids), recipientId, ids);
|
||||
}
|
||||
|
||||
/** Return `"retry"` to loop with remaining messages, or `"done"` once handled. */
|
||||
async function handleDispatchError(input: {
|
||||
error: unknown;
|
||||
recipientId: string;
|
||||
messages: Admitted[];
|
||||
request: DispatchRequest;
|
||||
stopped: () => boolean;
|
||||
}): Promise<"retry" | "done"> {
|
||||
const { error, recipientId, messages, request, stopped } = input;
|
||||
// A Stop reached the recipient before the provider admitted the prompt.
|
||||
if (stopped()) {
|
||||
await handBack(recipientId, messages);
|
||||
return "done";
|
||||
}
|
||||
// A withdrawal invalidated this exact prompt, or a steer's turn ended first: try again.
|
||||
if (messages.some(isWithdrawn) || error instanceof AgentTurnChangedError) {
|
||||
await handBack(recipientId, messages);
|
||||
return "retry";
|
||||
}
|
||||
if (error instanceof AgentTurnBusyError) {
|
||||
await handBack(recipientId, messages);
|
||||
// A non-replacing steer that found a busy/non-steering turn drops its urgency so it
|
||||
// waits for turn end rather than spinning immediately.
|
||||
if (!request.idleOnly && !request.replaceRunning && request.activeTurnBehavior === "steer") {
|
||||
await clearUrgency(recipientId, messages);
|
||||
}
|
||||
return "done";
|
||||
}
|
||||
// Shutdown cut this dispatch off. The next start tries it again.
|
||||
if (closed) {
|
||||
await handBack(recipientId, messages);
|
||||
return "done";
|
||||
}
|
||||
// Transient timeouts, non-fatal RPC failures, and rejected turn starts stay queued
|
||||
// and hold until the next user prompt instead of dropping batches.
|
||||
await handBack(recipientId, messages);
|
||||
const inbox = inboxes.get(recipientId);
|
||||
if (inbox) hold(recipientId, inbox);
|
||||
report(error, recipientId, request.messageIds);
|
||||
return "done";
|
||||
}
|
||||
|
||||
/** Dispatch one batch. A batch that finds the recipient stopped, or busy when idle-only, stays queued. */
|
||||
async function deliver(
|
||||
recipientId: string,
|
||||
@@ -720,6 +752,7 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
|
||||
idleOnly: boolean,
|
||||
stopped: () => boolean,
|
||||
activeTurnBehavior?: QueuedMessageUrgency,
|
||||
allowReplace = false,
|
||||
): Promise<void> {
|
||||
for (;;) {
|
||||
const prepared = await prepare(recipientId, batch);
|
||||
@@ -732,35 +765,29 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
|
||||
await handBack(recipientId, messages);
|
||||
continue;
|
||||
}
|
||||
const request = requestFor(recipientId, dispatching, idleOnly, stopped, activeTurnBehavior);
|
||||
let disposition: PromptDispatchDisposition;
|
||||
const request = requestFor(
|
||||
recipientId,
|
||||
dispatching,
|
||||
idleOnly,
|
||||
stopped,
|
||||
activeTurnBehavior,
|
||||
allowReplace,
|
||||
);
|
||||
try {
|
||||
for (const message of messages) message.beforeDispatch?.();
|
||||
disposition = await dependencies.dispatch(request);
|
||||
const disposition = await dependencies.dispatch(request);
|
||||
return complete(recipientId, messages, disposition);
|
||||
} catch (error) {
|
||||
// A Stop reached the recipient before the provider admitted the prompt.
|
||||
if (stopped()) return handBack(recipientId, messages);
|
||||
// A withdrawal invalidated this exact prompt; the rest goes again without it.
|
||||
// A steer whose turn ended first goes again, into the next turn or as a new one.
|
||||
if (messages.some(isWithdrawn) || error instanceof AgentTurnChangedError) {
|
||||
await handBack(recipientId, messages);
|
||||
continue;
|
||||
}
|
||||
if (error instanceof AgentTurnBusyError && request.idleOnly)
|
||||
return handBack(recipientId, messages);
|
||||
// The provider refused to start a turn. Retrying by itself would refuse again and add
|
||||
// the prompt to the history each time, so the queue waits for the next prompt.
|
||||
if (error instanceof AgentTurnStartRejectedError) {
|
||||
await handBack(recipientId, messages);
|
||||
const inbox = inboxes.get(recipientId);
|
||||
if (inbox) hold(recipientId, inbox);
|
||||
return report(error, recipientId, request.messageIds);
|
||||
}
|
||||
// Shutdown cut this dispatch off. The next start tries it again.
|
||||
if (closed) return handBack(recipientId, messages);
|
||||
return discard(recipientId, messages, error);
|
||||
const outcome = await handleDispatchError({
|
||||
error,
|
||||
recipientId,
|
||||
messages,
|
||||
request,
|
||||
stopped,
|
||||
});
|
||||
if (outcome === "retry") continue;
|
||||
return;
|
||||
}
|
||||
return complete(recipientId, messages, disposition);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -818,26 +845,45 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
|
||||
): Promise<boolean> {
|
||||
const last = ahead.findLastIndex(isUrgent);
|
||||
if (last < 0) return false;
|
||||
const released = ahead.slice(0, last + 1).filter(isQueued);
|
||||
const [first] = released;
|
||||
const prefix = ahead.slice(0, last + 1).filter(isQueued);
|
||||
const [first] = prefix;
|
||||
if (!first) return false;
|
||||
// Only releasing the switch itself replaces the running turn with it.
|
||||
if (first.providerSwitch && !isUrgent(first)) return false;
|
||||
const now = first.providerSwitch ? [first] : (modeGroups(released)[0] ?? []);
|
||||
const behavior: QueuedMessageUrgency = released.some(
|
||||
(message) => message.urgency === "interrupt",
|
||||
)
|
||||
// Do not jump over a queued provider switch ahead of urgent items.
|
||||
const segment = first.providerSwitch ? prefix : beforeSwitch(prefix);
|
||||
const behavior: QueuedMessageUrgency = prefix.some((message) => message.urgency === "interrupt")
|
||||
? "interrupt"
|
||||
: "steer";
|
||||
// Agent and finish steers must not sweep human-queued items sitting ahead of them, and wait
|
||||
// until turn end when the provider cannot steer. Explicit interrupts, Send now promotions,
|
||||
// and direct provider switches release the prefix in order and may replace the active turn.
|
||||
const replaceActiveTurn =
|
||||
behavior === "interrupt" ||
|
||||
prefix.some((message) => isUrgent(message) && (message.promoted || message.source === null));
|
||||
const released = replaceActiveTurn
|
||||
? segment
|
||||
: segment.filter((message) => !isHumanQueued(message));
|
||||
const [head] = released;
|
||||
if (!head) return false;
|
||||
const now = head.providerSwitch ? [head] : (modeGroups(released)[0] ?? []);
|
||||
// A non-steering provider keeps agent/finish steer messages queued until turn end rather
|
||||
// than interrupting it. Human promotions ("Send now") and interrupts still replace it.
|
||||
if (
|
||||
isRunning(recipientId) &&
|
||||
behavior === "steer" &&
|
||||
!replaceActiveTurn &&
|
||||
!canSteer(recipientId)
|
||||
) {
|
||||
await clearUrgency(recipientId, released);
|
||||
return false;
|
||||
}
|
||||
// The rest follows when the turn these start ends. Persist the downgrade before dispatching
|
||||
// so a daemon restart while the first group runs does not revive consumed urgency.
|
||||
const deferred = released.slice(now.length);
|
||||
if (deferred.length) {
|
||||
for (const message of deferred) message.urgency = null;
|
||||
const deferredIds = idsOf(deferred);
|
||||
await write(store.clearUrgency(recipientId, deferredIds), recipientId, deferredIds);
|
||||
}
|
||||
await deliver(recipientId, now, false, stopped, behavior);
|
||||
const nowIds = new Set(idsOf(now));
|
||||
const deferred = prefix.filter((message) => isUrgent(message) && !nowIds.has(message.id));
|
||||
await clearUrgency(recipientId, deferred);
|
||||
await deliver(recipientId, now, false, stopped, behavior, replaceActiveTurn);
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -900,8 +946,16 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
|
||||
inbox.phase = "waiting";
|
||||
const running = isRunning(recipientId);
|
||||
if (running) inbox.cancelTimer = schedule(QUIET_MS, () => attempt(recipientId));
|
||||
const nothingToOffer = !dependencies.tryRunOutOfBand || !inbox.messages.some(isOfferable);
|
||||
if (running && nothingToOffer) return;
|
||||
const hasSteerableUrgent = inbox.messages.some(
|
||||
(message) =>
|
||||
isUrgent(message) &&
|
||||
(message.urgency === "interrupt" ||
|
||||
message.promoted ||
|
||||
message.source === null ||
|
||||
canSteer(recipientId)),
|
||||
);
|
||||
const hasOfferable = Boolean(dependencies.tryRunOutOfBand) && inbox.messages.some(isOfferable);
|
||||
if (running && !hasOfferable && !hasSteerableUrgent) return;
|
||||
nudge(recipientId, inbox);
|
||||
}
|
||||
|
||||
@@ -926,7 +980,9 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
|
||||
if (insertIndex >= 0) inbox.messages.splice(insertIndex, 0, item);
|
||||
else inbox.messages.push(item);
|
||||
inbox.cancelTimer();
|
||||
if (item.urgency) {
|
||||
const batchesInQuietWindow =
|
||||
item.source?.kind === "agent-notification" && item.urgency !== "interrupt";
|
||||
if (item.urgency && !batchesInQuietWindow) {
|
||||
// A steer or an interrupt does not wait: it closes the window and takes the queue along. Its place
|
||||
// is reserved now, so a prompt admitted after it cannot take it away.
|
||||
inbox.cancelCap();
|
||||
@@ -968,6 +1024,7 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
|
||||
resolve,
|
||||
reject,
|
||||
state: "queued",
|
||||
promoted: false,
|
||||
outOfBandDeclined: false,
|
||||
saved: Promise.resolve(),
|
||||
persisted: false,
|
||||
@@ -984,7 +1041,7 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
|
||||
guidance: describeAgentMessage({
|
||||
activeTurnBehavior,
|
||||
running: isRunning(recipientId),
|
||||
canSteer: Boolean(dependencies.canSteer?.(recipientId)),
|
||||
canSteer: canSteer(recipientId),
|
||||
immediateWhenIdle: !source,
|
||||
}),
|
||||
};
|
||||
@@ -1043,55 +1100,20 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
|
||||
}
|
||||
}
|
||||
|
||||
function join(riders: Ready[], direct: DirectPrompt): JoinedPrompt {
|
||||
if (!riders.length) {
|
||||
const own = prepareAgentMessage(direct.prompt, direct.source, direct.messageId);
|
||||
return {
|
||||
prompt: own.prompt,
|
||||
uploadedImages: direct.uploadedImages ?? [],
|
||||
messageId: own.messageId,
|
||||
sessionMode: direct.sessionMode,
|
||||
unarchive: direct.unarchive !== false,
|
||||
};
|
||||
}
|
||||
// Sharing a prompt with queued messages, each entry needs its own marker to stay
|
||||
// a separate row with its own identity.
|
||||
const own = envelopeMessage(direct.prompt, direct.source ?? null, direct.messageId);
|
||||
const queued = messagesOf(riders);
|
||||
function prepareDirectPrompt(direct: DirectPrompt): JoinedPrompt {
|
||||
const own = prepareAgentMessage(direct.prompt, direct.source, direct.messageId);
|
||||
return {
|
||||
prompt: combine([...riders.map(envelopeEntry), own.prompt]),
|
||||
uploadedImages: [...uploadedImagesOf(riders), ...(direct.uploadedImages ?? [])],
|
||||
prompt: own.prompt,
|
||||
uploadedImages: direct.uploadedImages ?? [],
|
||||
messageId: own.messageId,
|
||||
sessionMode:
|
||||
direct.sessionMode ?? queued.findLast((message) => message.sessionMode)?.sessionMode,
|
||||
unarchive: direct.unarchive !== false || queued.some((message) => message.unarchive),
|
||||
sessionMode: direct.sessionMode,
|
||||
unarchive: direct.unarchive !== false,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Messages that rode a direct prompt are delivered when the provider admits that prompt.
|
||||
* Until it answers, nothing later may pass them.
|
||||
*/
|
||||
async function ride(
|
||||
recipientId: string,
|
||||
riders: Admitted[],
|
||||
result: PromptDispatchResult,
|
||||
): Promise<void> {
|
||||
if (!riders.length) return;
|
||||
if (result.disposition === "turn_started") {
|
||||
try {
|
||||
await (dependencies.awaitStart?.(recipientId, result.started) ?? result.started);
|
||||
} catch {
|
||||
// The provider rejected the prompt that carried them. They go again, in their place.
|
||||
return handBack(recipientId, riders);
|
||||
}
|
||||
}
|
||||
await complete(recipientId, riders, result.disposition);
|
||||
}
|
||||
|
||||
/**
|
||||
* The stopped recipient stays stopped. Its queue, steers and interrupts included, goes with whatever
|
||||
* prompts it next.
|
||||
* The stopped recipient stays stopped. Its queue, steers and interrupts included, waits until
|
||||
* a later prompt reopens it or a queued item is promoted.
|
||||
*/
|
||||
function hold(recipientId: string, inbox: Inbox): void {
|
||||
inbox.cancelTimer();
|
||||
@@ -1100,17 +1122,26 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
|
||||
inbox.stops++;
|
||||
for (const message of inbox.messages) {
|
||||
message.urgency = null;
|
||||
message.promoted = false;
|
||||
message.held = true;
|
||||
}
|
||||
void write(store.markHeld(recipientId), recipientId);
|
||||
}
|
||||
|
||||
/** A prompt admitted after a Stop releases what it left in the queue. */
|
||||
function reopen(recipientId: string, messages: Admitted[]): void {
|
||||
/** A prompt admitted after a Stop unpauses any held queue so it drains after this turn. */
|
||||
async function reopenHeld(recipientId: string, stopped: () => boolean): Promise<void> {
|
||||
const inbox = inboxes.get(recipientId);
|
||||
if (inbox?.phase !== "held") return;
|
||||
for (const message of messages) message.held = false;
|
||||
if (closed || stopped() || inbox?.phase !== "held") return;
|
||||
for (const message of inbox.messages) message.held = false;
|
||||
inbox.phase = "waiting";
|
||||
if (inbox.messages.length) {
|
||||
await write(store.clearHeld(recipientId), recipientId);
|
||||
} else {
|
||||
changed(recipientId);
|
||||
}
|
||||
if (!closed && !stopped() && !isRunning(recipientId)) {
|
||||
attempt(recipientId);
|
||||
}
|
||||
}
|
||||
|
||||
/** Without a message admitted since the Stop, the queue is held again. */
|
||||
@@ -1219,7 +1250,11 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
|
||||
await queued.saved;
|
||||
return queued.receipt;
|
||||
}
|
||||
const activeTurnBehavior = message.activeTurnBehavior ?? "queue";
|
||||
const requestedBehavior = message.activeTurnBehavior ?? "queue";
|
||||
const activeTurnBehavior: AgentMessageBehavior =
|
||||
requestedBehavior === "steer" && isRunning(recipientId) && !canSteer(recipientId)
|
||||
? "queue"
|
||||
: requestedBehavior;
|
||||
const source = message.source ?? null;
|
||||
const item = createAdmitted(
|
||||
{
|
||||
@@ -1310,7 +1345,7 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
|
||||
): Promise<DirectSendResult<Result>> {
|
||||
const { recipientId } = direct;
|
||||
// A retried direct send whose earlier attempt was queued must return that queued entry
|
||||
// rather than coalescing with itself or interrupting the turn ahead of it.
|
||||
// rather than duplicating or interrupting the turn ahead of it.
|
||||
if (direct.messageId) {
|
||||
const existing = inboxes
|
||||
.get(recipientId)
|
||||
@@ -1322,56 +1357,53 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
|
||||
return { disposition: "queued", receipt: existing.receipt };
|
||||
}
|
||||
}
|
||||
// Its place in line is decided now: what is queued goes with it, what comes later follows.
|
||||
// A queued provider switch, and what follows it, waits for the turn this prompt starts.
|
||||
const takesQueue = !closed && !direct.resumesTurn && !isCommand(direct.prompt);
|
||||
const inbox = inboxes.get(recipientId);
|
||||
const queued = takesQueue ? [...(inbox?.messages ?? [])] : [];
|
||||
const ahead = beforeSwitch(queued);
|
||||
const behind = queued.slice(ahead.length);
|
||||
const stopped = inbox ? watchForStop(inbox) : () => false;
|
||||
|
||||
// When queued messages ahead of this prompt cross a boundary (conflicting sessionMode or
|
||||
// queued non-agent command), insert this prompt immediately after `ahead` with urgency so
|
||||
// the earlier group runs first under its own mode and this prompt follows on its own turn
|
||||
// before any queued provider switch or later arrival.
|
||||
if (takesQueue && !canCoalesceDirect({ ahead: ahead.filter(isQueued), direct })) {
|
||||
const receipt = await enqueueDirect({ direct, insertBeforeId: behind[0]?.id });
|
||||
const stopsBefore = inboxes.get(recipientId)?.stops ?? 0;
|
||||
const stopped = () => (inboxes.get(recipientId)?.stops ?? 0) !== stopsBefore;
|
||||
const queuedBehindCurrentProvider = (): string | null | undefined => {
|
||||
if (closed || !direct.providerSwitch) return null;
|
||||
const current = [...(inboxes.get(recipientId)?.messages ?? [])];
|
||||
const ahead = beforeSwitch(current);
|
||||
return ahead.some(isQueued) ? current[ahead.length]?.id : null;
|
||||
};
|
||||
|
||||
// A direct provider switch must not move queued messages meant for the current provider
|
||||
// onto the target provider, so queue it right after them and release them first.
|
||||
const insertBeforeId = queuedBehindCurrentProvider();
|
||||
if (insertBeforeId !== null) {
|
||||
const receipt = await enqueueDirect({ direct, insertBeforeId });
|
||||
return { disposition: "queued", receipt };
|
||||
}
|
||||
|
||||
return new Promise<DirectSendResult<Result>>((resolve, reject) => {
|
||||
run(recipientId, async () => {
|
||||
let riders: Admitted[] = [];
|
||||
let result: Result;
|
||||
try {
|
||||
const pending = closed ? [] : await prepare(recipientId, ahead);
|
||||
if (
|
||||
!closed &&
|
||||
takesQueue &&
|
||||
!canCoalesceDirect({ ahead: messagesOf(pending), direct })
|
||||
) {
|
||||
const aheadSet = new Set(ahead);
|
||||
const insertBeforeId = inboxes
|
||||
.get(recipientId)
|
||||
?.messages.find((entry) => !aheadSet.has(entry))?.id;
|
||||
const receipt = await enqueueDirect({ direct, insertBeforeId });
|
||||
const deferredInsertBeforeId = queuedBehindCurrentProvider();
|
||||
if (deferredInsertBeforeId !== null) {
|
||||
const receipt = await enqueueDirect({
|
||||
direct,
|
||||
insertBeforeId: deferredInsertBeforeId,
|
||||
});
|
||||
resolve({ disposition: "queued", receipt });
|
||||
return;
|
||||
}
|
||||
const dispatching = await markDispatching(recipientId, pending);
|
||||
riders = messagesOf(dispatching);
|
||||
for (const message of riders) message.state = "claimed";
|
||||
for (const message of riders) message.beforeDispatch?.();
|
||||
result = await send(join(dispatching, direct));
|
||||
result = await send(prepareDirectPrompt(direct));
|
||||
} catch (error) {
|
||||
await handBack(recipientId, riders);
|
||||
reject(error);
|
||||
return;
|
||||
}
|
||||
resolve(result);
|
||||
await ride(recipientId, riders, result);
|
||||
if (behind.length && !stopped()) reopen(recipientId, behind);
|
||||
if (result.disposition === "turn_started") {
|
||||
try {
|
||||
await (dependencies.awaitStart?.(recipientId, result.started) ?? result.started);
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (!direct.resumesTurn && !isCommand(direct.prompt)) {
|
||||
await reopenHeld(recipientId, stopped);
|
||||
}
|
||||
});
|
||||
});
|
||||
},
|
||||
@@ -1412,6 +1444,7 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
|
||||
if (!promoted.has(message.id)) continue;
|
||||
message.urgency = urgency;
|
||||
message.held = false;
|
||||
message.promoted = true;
|
||||
}
|
||||
inbox.cancelTimer();
|
||||
inbox.cancelCap();
|
||||
|
||||
@@ -305,16 +305,16 @@ test("Stop holds the queue across a restart until it is promoted", async () => {
|
||||
await second.delivery.close();
|
||||
});
|
||||
|
||||
test("a prompt sent after a restart carries the held messages", async () => {
|
||||
test("a prompt sent after a restart runs alone, clears the hold, and delivers held messages after the turn ends", async () => {
|
||||
const home = await createHome();
|
||||
const first = openDaemon(home, { running: true });
|
||||
await queue(first.delivery, "held");
|
||||
await first.stop();
|
||||
await first.delivery.close();
|
||||
|
||||
const second = openDaemon(home);
|
||||
await second.delivery.start();
|
||||
let prompt: AgentPromptInput = "";
|
||||
const second = openDaemon(home, { running: true });
|
||||
await second.delivery.start();
|
||||
await second.delivery.sendDirect(
|
||||
{ recipientId: "parent", prompt: "continue", messageId: "next" },
|
||||
async (joined) => {
|
||||
@@ -323,7 +323,12 @@ test("a prompt sent after a restart carries the held messages", async () => {
|
||||
},
|
||||
);
|
||||
await second.settle();
|
||||
expect(String(prompt)).toContain('message-id="held"');
|
||||
expect(prompt).toBe("continue");
|
||||
expect(await second.saved("parent")).toEqual([{ id: "held", state: "queued", held: false }]);
|
||||
expect(second.ids()).toEqual([]);
|
||||
|
||||
await second.endTurn();
|
||||
expect(second.ids()).toEqual([["held"]]);
|
||||
expect(await second.saved("parent")).toEqual([]);
|
||||
await second.delivery.close();
|
||||
});
|
||||
|
||||
@@ -79,6 +79,28 @@ describe("trailing marker", () => {
|
||||
}
|
||||
});
|
||||
|
||||
test("gives each bundled user message its own messageId instead of copying the outer one", () => {
|
||||
const text = [
|
||||
formatAgentMessage({ id: "user-1", source: null, text: "First question" }),
|
||||
formatAgentMessage({ id: "user-2", source: null, text: "Second question" }),
|
||||
].join("\n\n");
|
||||
|
||||
expect(project(text, "provider-echo")).toEqual([
|
||||
{
|
||||
type: "user_message",
|
||||
text: "First question",
|
||||
clientMessageId: "user-1",
|
||||
messageId: "user-1",
|
||||
},
|
||||
{
|
||||
type: "user_message",
|
||||
text: "Second question",
|
||||
clientMessageId: "user-2",
|
||||
messageId: "user-2",
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
test("a body with leading whitespace replays the same after a provider trims the prompt", () => {
|
||||
const source = { kind: "agent-message" as const, agentId: "lead", title: "Lead" };
|
||||
for (const text of ["\n indented code", " - list"]) {
|
||||
|
||||
@@ -277,7 +277,9 @@ export function envelopeMessage(
|
||||
export function projectAgentMessages(item: AgentTimelineItem): AgentTimelineItem[] {
|
||||
if (item.type !== "user_message") return [item];
|
||||
const messages = parseAgentMessages(item.text);
|
||||
return messages ? messages.map((message) => projectAgentMessage(item, message)) : [item];
|
||||
if (!messages) return [item];
|
||||
const bundled = messages.length > 1;
|
||||
return messages.map((message) => projectAgentMessage(item, message, bundled));
|
||||
}
|
||||
|
||||
const AGENT_MESSAGE_CALL = "paseo-agent-message:";
|
||||
@@ -300,9 +302,18 @@ export function projectedMessageIds(item: AgentTimelineItem): string[] {
|
||||
function projectAgentMessage(
|
||||
item: Extract<AgentTimelineItem, { type: "user_message" }>,
|
||||
message: AgentMessage,
|
||||
bundled: boolean,
|
||||
): AgentTimelineItem {
|
||||
const { source } = message;
|
||||
if (!source) return { ...item, text: message.text, clientMessageId: message.id };
|
||||
if (!source) {
|
||||
return {
|
||||
...item,
|
||||
text: message.text,
|
||||
clientMessageId: message.id,
|
||||
// Keep each bundled human row uniquely identified instead of cloning the outer messageId.
|
||||
...(bundled && item.messageId !== undefined ? { messageId: message.id } : {}),
|
||||
};
|
||||
}
|
||||
switch (source.kind) {
|
||||
case "schedule":
|
||||
return {
|
||||
|
||||
@@ -32,7 +32,7 @@ export function describeAgentMessage(admission: Admission): string {
|
||||
"Queued, not delivered yet. The agent is working and reads your message when its current turn ends.";
|
||||
const followUp = canSteer
|
||||
? 'If the message cannot wait, send a short follow-up with activeTurnBehavior "steer" (it joins the running turn) or "interrupt" (it stops the turn and starts a new one).'
|
||||
: 'If the message cannot wait, send a short follow-up with activeTurnBehavior "interrupt" (it stops the turn and starts a new one). This agent\'s provider cannot steer, so "steer" also stops the turn.';
|
||||
: 'If the message cannot wait, send a short follow-up with activeTurnBehavior "interrupt" (it stops the turn and starts a new one). This agent\'s provider cannot steer, so "steer" also waits until the current turn ends.';
|
||||
return `${waiting} ${followUp} ${DO_NOT_REPEAT}`;
|
||||
}
|
||||
if (!running) return "The agent is idle, so your message starts a turn now.";
|
||||
@@ -40,5 +40,5 @@ export function describeAgentMessage(admission: Admission): string {
|
||||
return "Interrupting the running turn. A new turn starts with your message.";
|
||||
return canSteer
|
||||
? "Steering the running turn. The agent reads your message at its next step and keeps working."
|
||||
: "This agent's provider cannot steer, so your message interrupts the running turn. A new turn starts with your message.";
|
||||
: "This agent's provider cannot steer, so your message is queued until the running turn ends.";
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { AgentMessageQueueStore, PersistedQueuedMessage } from "../store.js";
|
||||
import {
|
||||
assertValidRecipientId,
|
||||
clearHeldInQueue,
|
||||
clearQueue,
|
||||
clearUrgencyInQueue,
|
||||
cloneQueuedMessage,
|
||||
@@ -62,6 +63,7 @@ export function createMemoryAgentMessageQueueStore(): AgentMessageQueueStore {
|
||||
revertDispatching: (recipientId, ids) =>
|
||||
mutate(recipientId, (current) => revertDispatchingInQueue(current, ids)),
|
||||
markHeld: (recipientId) => mutate(recipientId, (current) => markHeldInQueue(current)),
|
||||
clearHeld: (recipientId) => mutate(recipientId, (current) => clearHeldInQueue(current)),
|
||||
clearUrgency: (recipientId, ids) =>
|
||||
mutate(recipientId, (current) => clearUrgencyInQueue(current, ids)),
|
||||
promote: (recipientId, targetId, urgency) =>
|
||||
|
||||
@@ -322,6 +322,32 @@ export function markHeldInQueue(
|
||||
};
|
||||
}
|
||||
|
||||
export function clearHeldInQueue(current: RecipientQueueState): TransitionOutcome<void> {
|
||||
if (current.items.length === 0) {
|
||||
return { nextState: current, changed: false, result: undefined };
|
||||
}
|
||||
|
||||
let changed = false;
|
||||
const nextItems = current.items.map((item) => {
|
||||
const copy = cloneQueuedMessage(item);
|
||||
if (copy.held) {
|
||||
copy.held = false;
|
||||
changed = true;
|
||||
}
|
||||
return copy;
|
||||
});
|
||||
|
||||
if (!changed) {
|
||||
return { nextState: current, changed: false, result: undefined };
|
||||
}
|
||||
|
||||
return {
|
||||
nextState: { nextSeq: current.nextSeq, items: nextItems },
|
||||
changed: true,
|
||||
result: undefined,
|
||||
};
|
||||
}
|
||||
|
||||
export function promoteInQueue(
|
||||
current: RecipientQueueState,
|
||||
targetId: string,
|
||||
|
||||
@@ -391,6 +391,16 @@ export function createSqliteAgentMessageQueueStore(
|
||||
});
|
||||
},
|
||||
|
||||
async clearHeld(recipientId: string): Promise<void> {
|
||||
assertValidRecipientId(recipientId);
|
||||
database.write((sql) => {
|
||||
sql.run(
|
||||
"UPDATE agent_message_queue_items SET held = 0 WHERE recipient_id = ? AND held = 1",
|
||||
recipientId,
|
||||
);
|
||||
});
|
||||
},
|
||||
|
||||
async clearUrgency(recipientId: string, ids: readonly string[]): Promise<void> {
|
||||
assertValidRecipientId(recipientId);
|
||||
if (ids.length === 0) {
|
||||
|
||||
@@ -562,6 +562,19 @@ describe.each(adapters)("AgentMessageQueueStore contract ($name)", (adapter) =>
|
||||
state: "queued",
|
||||
}),
|
||||
]);
|
||||
|
||||
await store.clearHeld("agent-1");
|
||||
expect(
|
||||
(await store.listByRecipient("agent-1")).map((item) => ({
|
||||
id: item.id,
|
||||
held: item.held,
|
||||
urgency: item.urgency,
|
||||
state: item.state,
|
||||
})),
|
||||
).toEqual([
|
||||
{ id: "m1", held: false, urgency: null, state: "dispatching" },
|
||||
{ id: "m2", held: false, urgency: null, state: "queued" },
|
||||
]);
|
||||
});
|
||||
|
||||
test("promote promotes FIFO prefix 0..k, clears held, and reports not_found / already_dispatching", async () => {
|
||||
|
||||
@@ -73,6 +73,7 @@ export interface AgentMessageQueueStore {
|
||||
): Promise<PersistedQueuedMessage[]>;
|
||||
revertDispatching(recipientId: string, ids: readonly string[]): Promise<void>;
|
||||
markHeld(recipientId: string): Promise<PersistedQueuedMessage[]>;
|
||||
clearHeld(recipientId: string): Promise<void>;
|
||||
clearUrgency(recipientId: string, ids: readonly string[]): Promise<void>;
|
||||
promote(
|
||||
recipientId: string,
|
||||
|
||||
@@ -99,10 +99,14 @@ async function steerOrReplaceActiveRun(
|
||||
prompt,
|
||||
steerOptions,
|
||||
promptStart,
|
||||
options.replaceRunning,
|
||||
);
|
||||
if (result.status === "steered") {
|
||||
return { disposition: "steered" };
|
||||
}
|
||||
if (result.status === "busy") {
|
||||
throw new AgentTurnBusyError(`Agent ${agentId} is running`);
|
||||
}
|
||||
if (result.status === "replaced") {
|
||||
return { disposition: "turn_started", iterator: result.iterator };
|
||||
}
|
||||
@@ -325,6 +329,8 @@ export interface SendPromptToAgentParams {
|
||||
source?: AgentPromptSource;
|
||||
messageId?: string;
|
||||
activeTurnBehavior?: ActiveTurnBehavior;
|
||||
/** Override whether an active turn that cannot steer may be interrupted/replaced. */
|
||||
replaceRunning?: boolean;
|
||||
runOptions?: AgentRunOptions;
|
||||
/** Optional mode to set on the agent before the run starts. */
|
||||
sessionMode?: string;
|
||||
@@ -452,8 +458,8 @@ async function resolvePromptSource(
|
||||
* chat mentions, notify-on-finish) MUST go through this so behavior can never
|
||||
* drift between them.
|
||||
*
|
||||
* The prompt does not wait in the agent's message queue, and it does not jump it either:
|
||||
* messages already queued for the agent are delivered ahead of it in the same provider prompt.
|
||||
* The prompt does not wait in the agent's message queue and does not sweep queued messages:
|
||||
* existing queued items stay in the queue until the turn settles or are explicitly promoted.
|
||||
*
|
||||
* When `unarchive` is false and the agent is archived, the call is a silent
|
||||
* no-op (returns the normal turn-start disposition) — the agent is not run.
|
||||
@@ -548,7 +554,7 @@ export async function sendPreparedPromptToAgent(
|
||||
throw new Error("Queued agent message was withdrawn");
|
||||
}
|
||||
return await startAgentRun(params.agentManager, params.agentId, params.prompt, params.logger, {
|
||||
replaceRunning: !params.idleOnly,
|
||||
replaceRunning: params.replaceRunning ?? !params.idleOnly,
|
||||
idleOnly: params.idleOnly,
|
||||
admit: params.admit,
|
||||
onDispatch: params.onDispatch,
|
||||
|
||||
@@ -107,6 +107,140 @@ export function isDefaultAgentCreateConfigUnattended(
|
||||
return input.availableModes.some((mode) => mode.id === input.modeId && isUnattendedMode(mode));
|
||||
}
|
||||
|
||||
/**
|
||||
* Combines runtime/session modes with definition/catalog modes so runtime entries
|
||||
* keep their dynamic fields while inheriting static metadata (`icon`, `colorTier`,
|
||||
* `isUnattended`) from provider definitions.
|
||||
*/
|
||||
export function mergeAgentModeMetadata(
|
||||
primary: readonly AgentMode[] | undefined,
|
||||
secondary: readonly AgentMode[] | undefined,
|
||||
): AgentMode[] {
|
||||
const byId = new Map<string, AgentMode>();
|
||||
for (const mode of secondary ?? []) {
|
||||
byId.set(mode.id, mode);
|
||||
}
|
||||
const merged: AgentMode[] = [];
|
||||
for (const mode of primary ?? []) {
|
||||
const fallback = byId.get(mode.id);
|
||||
merged.push(
|
||||
fallback
|
||||
? {
|
||||
...mode,
|
||||
...(mode.icon !== undefined || fallback.icon !== undefined
|
||||
? { icon: mode.icon ?? fallback.icon }
|
||||
: {}),
|
||||
...(mode.colorTier !== undefined || fallback.colorTier !== undefined
|
||||
? { colorTier: mode.colorTier ?? fallback.colorTier }
|
||||
: {}),
|
||||
...(mode.isUnattended !== undefined || fallback.isUnattended !== undefined
|
||||
? { isUnattended: mode.isUnattended ?? fallback.isUnattended }
|
||||
: {}),
|
||||
}
|
||||
: mode,
|
||||
);
|
||||
byId.delete(mode.id);
|
||||
}
|
||||
for (const remaining of byId.values()) {
|
||||
merged.push(remaining);
|
||||
}
|
||||
return merged;
|
||||
}
|
||||
|
||||
const MODE_COLOR_TIER_RANK = {
|
||||
planning: 1,
|
||||
safe: 2,
|
||||
moderate: 3,
|
||||
dangerous: 4,
|
||||
} as const;
|
||||
|
||||
export type AgentModeRank = (typeof MODE_COLOR_TIER_RANK)[keyof typeof MODE_COLOR_TIER_RANK];
|
||||
|
||||
export interface AgentModePrivilege {
|
||||
provider: AgentProvider;
|
||||
explicitModeId: string | null;
|
||||
modeId: string | null;
|
||||
isUnattended: boolean;
|
||||
rank: AgentModeRank | null;
|
||||
}
|
||||
|
||||
export function classifyModePrivilege(input: {
|
||||
provider: AgentProvider;
|
||||
modeId: string | null;
|
||||
isUnattended: boolean;
|
||||
availableModes: readonly AgentMode[];
|
||||
defaultModeId?: string | null;
|
||||
}): AgentModePrivilege {
|
||||
if (input.isUnattended) {
|
||||
return {
|
||||
provider: input.provider,
|
||||
explicitModeId: input.modeId,
|
||||
modeId: input.modeId,
|
||||
isUnattended: true,
|
||||
rank: MODE_COLOR_TIER_RANK.dangerous,
|
||||
};
|
||||
}
|
||||
let effectiveModeId = input.modeId;
|
||||
if (effectiveModeId === null && input.defaultModeId) {
|
||||
const defaultMode = input.availableModes.find((mode) => mode.id === input.defaultModeId);
|
||||
// Never infer unattended status from an unset mode; only inherit a constrained baseline.
|
||||
if (defaultMode && defaultMode.isUnattended !== true) {
|
||||
effectiveModeId = defaultMode.id;
|
||||
}
|
||||
}
|
||||
const matched = effectiveModeId
|
||||
? input.availableModes.find((mode) => mode.id === effectiveModeId)
|
||||
: undefined;
|
||||
const rank =
|
||||
matched?.colorTier && Object.hasOwn(MODE_COLOR_TIER_RANK, matched.colorTier)
|
||||
? MODE_COLOR_TIER_RANK[matched.colorTier as keyof typeof MODE_COLOR_TIER_RANK]
|
||||
: null;
|
||||
return {
|
||||
provider: input.provider,
|
||||
explicitModeId: input.modeId,
|
||||
modeId: effectiveModeId,
|
||||
isUnattended: false,
|
||||
rank,
|
||||
};
|
||||
}
|
||||
|
||||
export function formatModePrivilegeLabel(privilege: AgentModePrivilege): string {
|
||||
return privilege.modeId ?? privilege.explicitModeId ?? "<default>";
|
||||
}
|
||||
|
||||
export function checkModeCeiling(
|
||||
caller: AgentModePrivilege,
|
||||
target: AgentModePrivilege,
|
||||
): { allowed: true } | { allowed: false; reason: string } {
|
||||
if (caller.isUnattended) return { allowed: true };
|
||||
if (target.isUnattended) {
|
||||
return {
|
||||
allowed: false,
|
||||
reason: `Agent caller in mode '${formatModePrivilegeLabel(caller)}' (${caller.provider}) cannot set unattended mode or options for '${target.provider}'`,
|
||||
};
|
||||
}
|
||||
if (target.modeId === null) return { allowed: true };
|
||||
if (
|
||||
caller.provider === target.provider &&
|
||||
caller.explicitModeId !== null &&
|
||||
caller.explicitModeId === target.modeId
|
||||
) {
|
||||
return { allowed: true };
|
||||
}
|
||||
if (caller.rank !== null && target.rank !== null) {
|
||||
return target.rank <= caller.rank
|
||||
? { allowed: true }
|
||||
: {
|
||||
allowed: false,
|
||||
reason: `Agent caller in mode '${formatModePrivilegeLabel(caller)}' (${caller.provider}) cannot set more permissive mode '${target.modeId}' (${target.provider})`,
|
||||
};
|
||||
}
|
||||
return {
|
||||
allowed: false,
|
||||
reason: `Agent caller in constrained mode '${formatModePrivilegeLabel(caller)}' (${caller.provider}) cannot switch to unclassified mode '${target.modeId}' (${target.provider})`,
|
||||
};
|
||||
}
|
||||
|
||||
function isUnattendedMode(mode: AgentMode): boolean {
|
||||
return mode.isUnattended === true;
|
||||
}
|
||||
|
||||
@@ -74,12 +74,14 @@ class Observation implements FinishObservation {
|
||||
}
|
||||
class Delivery implements FinishMessages {
|
||||
prompts: string[] = [];
|
||||
behaviors: Array<string | undefined> = [];
|
||||
/** Prompts as the recipient's provider receives them, inside their envelope. */
|
||||
enqueued: string[] = [];
|
||||
acknowledgments: Array<ReturnType<typeof deferred<"steered">>> = [];
|
||||
enqueuedListeners = new Set<Parameters<FinishMessages["onEnqueued"]>[0]>();
|
||||
async enqueue(message: Parameters<FinishMessages["enqueue"]>[0]) {
|
||||
this.prompts.push(message.text);
|
||||
this.behaviors.push(message.activeTurnBehavior);
|
||||
this.enqueued.push(
|
||||
formatAgentMessage({
|
||||
id: "notification",
|
||||
@@ -1067,4 +1069,14 @@ describe("suppressing redundant finished notices after an explicit child report"
|
||||
await until(() => state.delivery.prompts.length === 2);
|
||||
expect(state.delivery.prompts[1]).toContain("Done after bash");
|
||||
});
|
||||
|
||||
test("finish notifications default to activeTurnBehavior steer", async () => {
|
||||
const state = await scenario();
|
||||
await state.service.register(intent);
|
||||
await until(() => state.observation.waits.length === 1);
|
||||
|
||||
state.observation.waits[0]!.result.resolve(outcome("idle", "child", "All tests passed"));
|
||||
await until(() => state.delivery.prompts.length === 1);
|
||||
expect(state.delivery.behaviors).toEqual(["steer"]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -337,8 +337,8 @@ export function createFinishSubscriptions(deps: Dependencies): FinishSubscriptio
|
||||
title,
|
||||
event: finishNotificationEvents[reason],
|
||||
},
|
||||
// A finish report never enters a running turn.
|
||||
activeTurnBehavior: "queue",
|
||||
// A finish report steers when the provider supports it and queues until turn end otherwise.
|
||||
activeTurnBehavior: "steer",
|
||||
unarchive: false,
|
||||
});
|
||||
const acknowledge = () => {
|
||||
|
||||
@@ -124,6 +124,11 @@ function resolverFor(client: DaemonClient, caller: Caller | null) {
|
||||
serverId: "origin",
|
||||
callerAgentId: caller ? "caller" : undefined,
|
||||
caller: () => caller,
|
||||
callerPolicy: {
|
||||
assertMutableLabels() {},
|
||||
async assertLineage() {},
|
||||
async assertWithinCeiling() {},
|
||||
},
|
||||
local: {} as HostOperations,
|
||||
hosts: () => ({
|
||||
directory: async () => ({ self: { serverId: "origin", label: "Origin" }, hosts: [] }),
|
||||
|
||||
@@ -29,6 +29,7 @@ import {
|
||||
type PaseoToolExecutionContext,
|
||||
type PaseoToolResult,
|
||||
} from "../tools/types.js";
|
||||
import type { AgentCallerPolicy } from "../agent-caller-policy.js";
|
||||
|
||||
export class HostOperationRejectedError extends Error {
|
||||
readonly code: unknown;
|
||||
@@ -212,6 +213,10 @@ export function createHostResolver(input: {
|
||||
callerAgentId?: string;
|
||||
/** The destination can't see the caller, so its background and mode defaults resolve before routing. */
|
||||
caller: () => (BackgroundCaller & { provider: string; currentModeId: string | null }) | null;
|
||||
callerPolicy: Pick<
|
||||
AgentCallerPolicy,
|
||||
"assertMutableLabels" | "assertLineage" | "assertWithinCeiling"
|
||||
>;
|
||||
lockedCwd?: string;
|
||||
}) {
|
||||
return {
|
||||
@@ -229,6 +234,13 @@ export function createHostResolver(input: {
|
||||
async createAgent(args) {
|
||||
const parsed = remoteCreate.parse(args);
|
||||
const { provider, model } = resolveRequiredProviderModel(parsed.provider);
|
||||
input.callerPolicy.assertMutableLabels(parsed.labels);
|
||||
await input.callerPolicy.assertWithinCeiling({
|
||||
provider,
|
||||
modeId: parsed.settings?.modeId,
|
||||
providerOptions: parsed.settings?.features,
|
||||
inheritFromSameProvider: true,
|
||||
});
|
||||
const caller = input.caller();
|
||||
// Same-provider children inherit the caller's mode, as they would on the same host.
|
||||
const modeId =
|
||||
@@ -284,6 +296,35 @@ export function createHostResolver(input: {
|
||||
)?.agent;
|
||||
if (!agent)
|
||||
throw new HostOperationRejectedError(new Error(`Agent ${agentId} not found`));
|
||||
if (input.callerAgentId && args.sessionMode !== undefined) {
|
||||
await input.callerPolicy.assertLineage(
|
||||
{
|
||||
agentId: agent.id,
|
||||
serverId: destination,
|
||||
labels: agent.labels,
|
||||
lookupLabels: async ({ serverId: parentServerId, agentId: id }) => {
|
||||
if (parentServerId === destination) {
|
||||
return (await client.fetchAgent(id))?.agent.labels;
|
||||
}
|
||||
return input
|
||||
.hosts()
|
||||
.use(
|
||||
parentServerId,
|
||||
async (other) => (await other.fetchAgent(id))?.agent.labels,
|
||||
)
|
||||
.catch(() => undefined);
|
||||
},
|
||||
},
|
||||
"descendant",
|
||||
"change the mode of",
|
||||
);
|
||||
await input.callerPolicy.assertWithinCeiling({
|
||||
provider: agent.provider,
|
||||
cwd: agent.cwd,
|
||||
modeId: args.sessionMode as string,
|
||||
availableModes: agent.availableModes,
|
||||
});
|
||||
}
|
||||
const receipt = await client
|
||||
.sendMessage(agentId, args.prompt as string, {
|
||||
sessionMode: input.callerAgentId
|
||||
|
||||
@@ -3254,7 +3254,7 @@ describe("create_agent MCP tool", () => {
|
||||
|
||||
try {
|
||||
const parent = await agentManager.createAgent(
|
||||
{ provider: "claude", cwd: existingCwd },
|
||||
{ provider: "claude", cwd: existingCwd, modeId: "bypassPermissions" },
|
||||
undefined,
|
||||
{ workspaceId: "wks_parent" },
|
||||
);
|
||||
@@ -3313,13 +3313,25 @@ describe("create_agent MCP tool", () => {
|
||||
});
|
||||
|
||||
const tool = registeredTool(server, "create_agent");
|
||||
await expect(
|
||||
tool.handler({
|
||||
...detachedCurrentWorkspace(),
|
||||
title: "Detached",
|
||||
provider: "codex/gpt-5.4",
|
||||
initialPrompt: "Take over",
|
||||
labels: {
|
||||
[PARENT_AGENT_ID_LABEL]: "spoofed-parent",
|
||||
source: "handoff",
|
||||
},
|
||||
}),
|
||||
).rejects.toThrow(/reserved Paseo labels/);
|
||||
|
||||
await tool.handler({
|
||||
...detachedCurrentWorkspace(),
|
||||
title: "Detached",
|
||||
provider: "codex/gpt-5.4",
|
||||
initialPrompt: "Take over",
|
||||
labels: {
|
||||
[PARENT_AGENT_ID_LABEL]: "spoofed-parent",
|
||||
source: "handoff",
|
||||
},
|
||||
});
|
||||
@@ -4071,9 +4083,9 @@ describe("send_agent_prompt MCP tool", () => {
|
||||
agentScoped: true,
|
||||
behavior: undefined,
|
||||
steering: "accepted",
|
||||
applied: "queue",
|
||||
outcome: "queued",
|
||||
guidance: 'or "interrupt" (it stops the turn and starts a new one). The follow-up carries',
|
||||
applied: "steer",
|
||||
outcome: "steered",
|
||||
guidance: "Steering the running turn.",
|
||||
},
|
||||
{
|
||||
agentScoped: true,
|
||||
@@ -4081,7 +4093,23 @@ describe("send_agent_prompt MCP tool", () => {
|
||||
steering: "none",
|
||||
applied: "queue",
|
||||
outcome: "queued",
|
||||
guidance: 'provider cannot steer, so "steer" also stops the turn',
|
||||
guidance: 'provider cannot steer, so "steer" also waits until the current turn ends',
|
||||
},
|
||||
{
|
||||
agentScoped: true,
|
||||
behavior: "queue",
|
||||
steering: "accepted",
|
||||
applied: "queue",
|
||||
outcome: "queued",
|
||||
guidance: 'or "interrupt" (it stops the turn and starts a new one). The follow-up carries',
|
||||
},
|
||||
{
|
||||
agentScoped: true,
|
||||
behavior: "queue",
|
||||
steering: "none",
|
||||
applied: "queue",
|
||||
outcome: "queued",
|
||||
guidance: 'provider cannot steer, so "steer" also waits until the current turn ends',
|
||||
},
|
||||
{
|
||||
agentScoped: true,
|
||||
@@ -4095,17 +4123,18 @@ describe("send_agent_prompt MCP tool", () => {
|
||||
agentScoped: true,
|
||||
behavior: "steer",
|
||||
steering: "none",
|
||||
applied: "steer",
|
||||
outcome: "replaced",
|
||||
guidance: "This agent's provider cannot steer, so your message interrupts the running turn.",
|
||||
applied: "queue",
|
||||
outcome: "queued",
|
||||
guidance: 'provider cannot steer, so "steer" also waits until the current turn ends',
|
||||
},
|
||||
// A provider that can steer may refuse one steer; the turn is replaced all the same.
|
||||
// A provider that can steer may refuse one steer mid-turn; keep the message queued instead of
|
||||
// replacing the running turn.
|
||||
{
|
||||
agentScoped: true,
|
||||
behavior: "steer",
|
||||
steering: "unavailable",
|
||||
applied: "steer",
|
||||
outcome: "replaced",
|
||||
outcome: "queued",
|
||||
guidance: "Steering the running turn.",
|
||||
},
|
||||
{
|
||||
@@ -4306,10 +4335,10 @@ describe("send_agent_prompt MCP tool", () => {
|
||||
);
|
||||
expect(response.structuredContent).toMatchObject({
|
||||
deliveryStatus: "queued",
|
||||
activeTurnBehavior: "queue",
|
||||
activeTurnBehavior: "steer",
|
||||
});
|
||||
expect(response.structuredContent.guidance).toContain(
|
||||
"Queued. The agent is idle, so your message starts a turn in about 2 seconds.",
|
||||
"The agent is idle, so your message starts a turn now.",
|
||||
);
|
||||
expect(client.sessions[1]!.prompts).toHaveLength(1);
|
||||
} finally {
|
||||
@@ -4361,7 +4390,12 @@ describe("send_agent_prompt MCP tool", () => {
|
||||
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 },
|
||||
arguments: {
|
||||
agentId: child.id,
|
||||
prompt: "New message",
|
||||
activeTurnBehavior: "queue",
|
||||
notifyOnFinish: true,
|
||||
},
|
||||
});
|
||||
expect(response.structuredContent).toMatchObject({
|
||||
success: true,
|
||||
@@ -4870,7 +4904,7 @@ describe("send_agent_prompt MCP tool", () => {
|
||||
|
||||
try {
|
||||
const parent = await agentManager.createAgent(
|
||||
{ provider: "claude", cwd: existingCwd },
|
||||
{ provider: "claude", cwd: existingCwd, modeId: "bypassPermissions" },
|
||||
undefined,
|
||||
{ workspaceId: "wks_parent" },
|
||||
);
|
||||
@@ -5229,7 +5263,7 @@ describe("message order for one recipient", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("a person's prompt takes the queued message into its own turn", async () => {
|
||||
it("a person's prompt runs alone without sweeping the queued message, which dispatches after the turn settles", async () => {
|
||||
const recipient = await setupRecipient();
|
||||
try {
|
||||
await recipient.agentSends("Go ahead and cut the release");
|
||||
@@ -5237,10 +5271,8 @@ describe("message order for one recipient", () => {
|
||||
|
||||
await recipient.personSends("Pause the release");
|
||||
|
||||
expect(recipient.prompt(1)).toEqual([
|
||||
{ from: recipient.senderId, text: "Go ahead and cut the release" },
|
||||
{ from: "person", text: "Pause the release" },
|
||||
]);
|
||||
expect(recipient.session.prompts).toHaveLength(2);
|
||||
expect(recipient.session.prompts[1]).toBe("Pause the release");
|
||||
const rows = await recipient.agentManager.getTimeline(recipient.recipientId);
|
||||
expect(rows.flatMap((row) => (row.type === "user_message" ? [row.text] : []))).toEqual([
|
||||
"Pause the release",
|
||||
@@ -5248,13 +5280,16 @@ describe("message order for one recipient", () => {
|
||||
recipient.session.finishTurn();
|
||||
recipient.advance(10 * 60_000);
|
||||
await recipient.settled();
|
||||
expect(recipient.session.prompts).toHaveLength(2);
|
||||
expect(recipient.session.prompts).toHaveLength(3);
|
||||
expect(recipient.prompt(2)).toEqual([
|
||||
{ from: recipient.senderId, text: "Go ahead and cut the release" },
|
||||
]);
|
||||
} finally {
|
||||
await recipient.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("Stop holds the queued steer for the recipient's next prompt", async () => {
|
||||
it("Stop holds the queued steer until a later prompt reopens the queue without sweeping it", async () => {
|
||||
const recipient = await setupRecipient();
|
||||
try {
|
||||
await recipient.agentSends("Go ahead and cut the release");
|
||||
@@ -5268,9 +5303,14 @@ describe("message order for one recipient", () => {
|
||||
expect(recipient.agentManager.getAgent(recipient.recipientId)?.lifecycle).toBe("idle");
|
||||
|
||||
await recipient.personSends("Carry on");
|
||||
expect(recipient.prompt(1)).toEqual([
|
||||
expect(recipient.session.prompts).toHaveLength(2);
|
||||
expect(recipient.session.prompts[1]).toBe("Carry on");
|
||||
recipient.session.finishTurn();
|
||||
recipient.advance(2000);
|
||||
await recipient.settled();
|
||||
expect(recipient.session.prompts).toHaveLength(3);
|
||||
expect(recipient.prompt(2)).toEqual([
|
||||
{ from: recipient.senderId, text: "Go ahead and cut the release" },
|
||||
{ from: "person", text: "Carry on" },
|
||||
]);
|
||||
} finally {
|
||||
await recipient.cleanup();
|
||||
@@ -5300,7 +5340,7 @@ describe("message order for one recipient", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("prompts sent while the provider is still starting a turn reach it in the order sent", async () => {
|
||||
it("a person's direct prompt does not sweep queued prompts while queued agent messages keep their order", async () => {
|
||||
const recipient = await setupRecipient();
|
||||
try {
|
||||
const acknowledgeStart = recipient.session.holdTurnStart();
|
||||
@@ -5315,15 +5355,15 @@ describe("message order for one recipient", () => {
|
||||
acknowledgeStart();
|
||||
await Promise.all([interrupt, person]);
|
||||
|
||||
expect(recipient.prompt(2)).toEqual([
|
||||
{ from: recipient.senderId, text: "Go ahead and cut the release" },
|
||||
{ from: "person", text: "Pause the release" },
|
||||
]);
|
||||
expect(recipient.session.prompts[2]).toBe("Pause the release");
|
||||
recipient.session.finishTurn();
|
||||
recipient.advance(2000);
|
||||
await recipient.settled();
|
||||
expect(recipient.session.prompts).toHaveLength(4);
|
||||
expect(recipient.prompt(3)).toEqual([{ from: recipient.senderId, text: "Tests passed" }]);
|
||||
expect(recipient.prompt(3)).toEqual([
|
||||
{ from: recipient.senderId, text: "Go ahead and cut the release" },
|
||||
{ from: recipient.senderId, text: "Tests passed" },
|
||||
]);
|
||||
} finally {
|
||||
await recipient.cleanup();
|
||||
}
|
||||
@@ -5341,14 +5381,16 @@ describe("message order for one recipient", () => {
|
||||
await recipient.stop();
|
||||
await person;
|
||||
|
||||
// The next prompt is sent after the interrupt's dispatch has ended, so a turn the
|
||||
// interrupt started on its own would show up as a prompt between the two.
|
||||
// The next prompt is sent after the interrupt's dispatch has ended, so it runs alone and
|
||||
// reopens the held interrupt to run after this turn finishes.
|
||||
await recipient.personSends("Carry on");
|
||||
expect(recipient.session.prompts).toHaveLength(3);
|
||||
expect(recipient.prompt(2)).toEqual([
|
||||
{ from: recipient.senderId, text: "Skip the backup" },
|
||||
{ from: "person", text: "Carry on" },
|
||||
]);
|
||||
expect(recipient.session.prompts[2]).toBe("Carry on");
|
||||
recipient.session.finishTurn();
|
||||
recipient.advance(2000);
|
||||
await recipient.settled();
|
||||
expect(recipient.session.prompts).toHaveLength(4);
|
||||
expect(recipient.prompt(3)).toEqual([{ from: recipient.senderId, text: "Skip the backup" }]);
|
||||
} finally {
|
||||
await recipient.cleanup();
|
||||
}
|
||||
@@ -5415,7 +5457,7 @@ describe("message order for one recipient", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("a queued message returns to the queue when the provider rejects the person's turn", async () => {
|
||||
it("a queued message stays in the queue when the provider rejects the person's turn", async () => {
|
||||
const recipient = await setupRecipient();
|
||||
try {
|
||||
await recipient.agentSends("Go ahead and cut the release");
|
||||
@@ -5425,12 +5467,9 @@ describe("message order for one recipient", () => {
|
||||
await expect(recipient.personSends("Pause the release")).rejects.toThrow(
|
||||
"Provider is overloaded",
|
||||
);
|
||||
expect(recipient.prompt(1)).toEqual([
|
||||
{ from: recipient.senderId, text: "Go ahead and cut the release" },
|
||||
{ from: "person", text: "Pause the release" },
|
||||
]);
|
||||
expect(recipient.session.prompts[1]).toBe("Pause the release");
|
||||
|
||||
// The provider never took that prompt, so the steer is delivered on its own.
|
||||
// The provider rejected the person's prompt; the queued steer still dispatches on its own.
|
||||
recipient.advance(2000);
|
||||
await recipient.settled();
|
||||
expect(recipient.session.prompts).toHaveLength(3);
|
||||
@@ -5458,7 +5497,7 @@ describe("finish notifications for a child that ends its turn with work pending"
|
||||
logger,
|
||||
});
|
||||
const parent = await agentManager.createAgent(
|
||||
{ provider: "claude", cwd: existingCwd },
|
||||
{ provider: "claude", cwd: existingCwd, modeId: "bypassPermissions" },
|
||||
undefined,
|
||||
{ workspaceId: "wks_parent" },
|
||||
);
|
||||
@@ -8512,7 +8551,7 @@ describe("local durable finish subscription MCP wiring", () => {
|
||||
const child = await manager.createAgent(
|
||||
{ provider: "codex", cwd: existingCwd },
|
||||
undefined,
|
||||
{ workspaceId: "wks_parent" },
|
||||
{ workspaceId: "wks_parent", labels: { [PARENT_AGENT_ID_LABEL]: parent.id } },
|
||||
);
|
||||
const server = await createAgentMcpServer({
|
||||
agentManager: manager,
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user