mirror of
https://github.com/getpaseo/paseo.git
synced 2026-11-27 10:45:29 +00:00
Compare commits
40
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e6390a85d1 | ||
|
|
d4fd6dcafd | ||
|
|
518e58cd63 | ||
|
|
82dcf7821e | ||
|
|
5d003d9613 | ||
|
|
9868ebc11c | ||
|
|
965e28e3d6 | ||
|
|
690f6970c3 | ||
|
|
bcb0097344 | ||
|
|
9eab3b278f | ||
|
|
fcfcdf156a | ||
|
|
15390b7168 | ||
|
|
539f4af006 | ||
|
|
fbda126f42 | ||
|
|
6d2db423d8 | ||
|
|
4fd21252af | ||
|
|
63eb8c0dec | ||
|
|
294093e8b9 | ||
|
|
bb0588ecb0 | ||
|
|
c7ad1dae52 | ||
|
|
39410ae7d0 | ||
|
|
e6f0ad272d | ||
|
|
02e4b8e3e9 | ||
|
|
203398fa44 | ||
|
|
21c2e55dd1 | ||
|
|
74c33b03d3 | ||
|
|
e4dc119df8 | ||
|
|
903b71180f | ||
|
|
4201a4de35 | ||
|
|
3c0553d9db | ||
|
|
2be71aedcb | ||
|
|
a27f0819c8 | ||
|
|
46eb98d604 | ||
|
|
7d3e045ff8 | ||
|
|
20b70e37e7 | ||
|
|
fcac35d3b9 | ||
|
|
2636c4384f | ||
|
|
17c08edccf | ||
|
|
0687c370ec | ||
|
|
a7dbeadd5f |
@@ -1,5 +1,24 @@
|
||||
# Changelog
|
||||
|
||||
## 0.18.0 - 2026-11-27
|
||||
|
||||
- **Remote workspace browser proxy:** Desktop browser tabs in remote workspaces now route through the workspace daemon, so remote `localhost` servers open directly in Paseo. ([#10944](https://github.com/getpaseo/paseo/pull/10944) by [@airon-assustadus](https://github.com/airon-assustadus))
|
||||
- **Per-device notification preferences:** Each device can choose which agent, terminal, and plugin events send notifications, and plugins can send notifications and handle taps. ([#10888](https://github.com/getpaseo/paseo/pull/10888))
|
||||
- **Agent profile system prompts:** Save an optional system prompt on an agent profile to apply it to new agents started from that profile. ([#10996](https://github.com/getpaseo/paseo/pull/10996))
|
||||
- **More syntax highlighting:** Syntax highlighting now covers diff and patch files along with Ruby, Kotlin, TOML, SQL, Lua, Protobuf, PowerShell, Groovy, Gradle, Scala, CMake, Properties, INI, R, Perl, and LaTeX. ([#11026](https://github.com/getpaseo/paseo/pull/11026) by [@hmalaspina](https://github.com/hmalaspina), [@kukicola](https://github.com/kukicola), [@MaximeConan](https://github.com/MaximeConan), [@singleton11](https://github.com/singleton11), [@chandlerok](https://github.com/chandlerok))
|
||||
|
||||
### Changed
|
||||
|
||||
- Changed ACP providers to cache model catalogs across daemon restarts instead of probing in the background, and cleaned up Antigravity ACP flags and metadata. Requires [Antigravity CLI 1.5.1 or later](https://paseo.sh/docs/supported-providers/antigravity) ([#10992](https://github.com/getpaseo/paseo/pull/10992))
|
||||
|
||||
### Fixed
|
||||
|
||||
- Fixed Paseo iOS crashing shortly after connecting when an enabled client plugin imports `react-native` ([#11011](https://github.com/getpaseo/paseo/pull/11011))
|
||||
- Fixed OpenCode v2 agents staying stuck in running after Stop when stream events were missed or chat history was large ([#10955](https://github.com/getpaseo/paseo/pull/10955))
|
||||
- Fixed steering a Pi agent during a run it started on its own aborting the run instead of steering it ([#10977](https://github.com/getpaseo/paseo/pull/10977) by [@viiqswim](https://github.com/viiqswim))
|
||||
- Fixed creating a workspace from a pull request in a fork clone checking out the fork's pull request with the same number ([#10987](https://github.com/getpaseo/paseo/pull/10987))
|
||||
- Fixed dropping images or files onto the composer leaving the input unfocused ([#11022](https://github.com/getpaseo/paseo/pull/11022))
|
||||
|
||||
## 0.17.6 - 2026-11-27
|
||||
|
||||
### Improved
|
||||
|
||||
@@ -1,5 +1,24 @@
|
||||
# Changelog
|
||||
|
||||
## 0.18.0 - 2026-11-27
|
||||
|
||||
- **远程工作区浏览器代理**:远程工作区中的桌面端浏览器标签页现在会通过该工作区的 daemon 转发流量,远程 `localhost` 服务可以直接在 Paseo 中打开。([#10944](https://github.com/getpaseo/paseo/pull/10944),贡献者:[@airon-assustadus](https://github.com/airon-assustadus))
|
||||
- **按设备配置通知偏好**:每台设备都可以分别选择哪些 Agent、终端和插件事件发送通知,插件现在也可以发送通知并处理点击。([#10888](https://github.com/getpaseo/paseo/pull/10888))
|
||||
- **智能体配置文件系统提示词**:在智能体配置文件中保存可选的系统提示词,以便在通过该配置启动新 Agent 时应用。([#10996](https://github.com/getpaseo/paseo/pull/10996))
|
||||
- **更多语法高亮语言**:语法高亮现已支持 diff 和 patch 文件,以及 Ruby、Kotlin、TOML、SQL、Lua、Protobuf、PowerShell、Groovy、Gradle、Scala、CMake、Properties、INI、R、Perl 和 LaTeX。([#11026](https://github.com/getpaseo/paseo/pull/11026),贡献者:[@hmalaspina](https://github.com/hmalaspina), [@kukicola](https://github.com/kukicola), [@MaximeConan](https://github.com/MaximeConan), [@singleton11](https://github.com/singleton11), [@chandlerok](https://github.com/chandlerok))
|
||||
|
||||
### 变更
|
||||
|
||||
- ACP Provider 现在会在 daemon 重启间将已发现的模型目录缓存到磁盘,不再在后台轮询,同时清理了多余的 Antigravity ACP 参数和元数据。需要 [Antigravity CLI 1.5.1 或更高版本](https://paseo.sh/zh-CN/docs/supported-providers/antigravity) ([#10992](https://github.com/getpaseo/paseo/pull/10992))
|
||||
|
||||
### 修复
|
||||
|
||||
- 修复已启用的客户端插件导入 `react-native` 时,Paseo iOS 在连接后不久崩溃的问题 ([#11011](https://github.com/getpaseo/paseo/pull/11011))
|
||||
- 修复流事件丢失或对话历史较大时,OpenCode v2 Agent 在点击停止后仍停留在运行中的问题 ([#10955](https://github.com/getpaseo/paseo/pull/10955))
|
||||
- 修复在 Pi Agent 运行其自行启动的轮次时发送引导消息会中止该轮次而不是引导它的问题 ([#10977](https://github.com/getpaseo/paseo/pull/10977),贡献者:[@viiqswim](https://github.com/viiqswim))
|
||||
- 修复在 fork 克隆中根据 PR 创建工作区时,检出到 fork 中同编号 PR 的问题 ([#10987](https://github.com/getpaseo/paseo/pull/10987))
|
||||
- 修复向 Composer 拖放图片或文件后输入框未获得焦点的问题 ([#11022](https://github.com/getpaseo/paseo/pull/11022))
|
||||
|
||||
## 0.17.6 - 2026-11-27
|
||||
|
||||
### 改进
|
||||
|
||||
+2
-2
@@ -57,9 +57,9 @@
|
||||
|
||||
<!-- Sponsors: one cell per sponsor in the order of packages/website/src/data/sponsors.ts, then "become a sponsor" cells up to three. -->
|
||||
<table>
|
||||
<tr>
|
||||
<tr valign="top">
|
||||
<td align="center" width="33%"><a href="https://hoplite.sh/?utm_source=paseo&utm_medium=readme&utm_campaign=sponsor"><picture><source media="(prefers-color-scheme: dark)" srcset="packages/website/public/sponsors/hoplite-on-dark.svg"><img src="packages/website/public/sponsors/hoplite-on-light.svg" alt="Hoplite" height="40"></picture></a><br><sub>Cloud coding agents</sub></td>
|
||||
<td align="center" width="33%"><a href="https://paseo.sh/sponsor">Paseo のスポンサーになる</a></td>
|
||||
<td align="center" width="33%"><a href="https://encore.dev/?utm_source=paseo&utm_medium=readme&utm_campaign=sponsor"><picture><source media="(prefers-color-scheme: dark)" srcset="packages/website/public/sponsors/encore-on-dark.svg"><img src="packages/website/public/sponsors/encore-on-light.svg" alt="Encore" height="40"></picture></a><br><sub>Encore lets AI agents ship to production safely, at scale, in your own cloud.</sub></td>
|
||||
<td align="center" width="33%"><a href="https://paseo.sh/sponsor">Paseo のスポンサーになる</a></td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
+2
-2
@@ -51,9 +51,9 @@
|
||||
|
||||
<!-- Sponsors: one cell per sponsor in the order of packages/website/src/data/sponsors.ts, then "become a sponsor" cells up to three. -->
|
||||
<table>
|
||||
<tr>
|
||||
<tr valign="top">
|
||||
<td align="center" width="33%"><a href="https://hoplite.sh/?utm_source=paseo&utm_medium=readme&utm_campaign=sponsor"><picture><source media="(prefers-color-scheme: dark)" srcset="packages/website/public/sponsors/hoplite-on-dark.svg"><img src="packages/website/public/sponsors/hoplite-on-light.svg" alt="Hoplite" height="40"></picture></a><br><sub>Cloud coding agents</sub></td>
|
||||
<td align="center" width="33%"><a href="https://paseo.sh/sponsor">Paseo 스폰서 되기</a></td>
|
||||
<td align="center" width="33%"><a href="https://encore.dev/?utm_source=paseo&utm_medium=readme&utm_campaign=sponsor"><picture><source media="(prefers-color-scheme: dark)" srcset="packages/website/public/sponsors/encore-on-dark.svg"><img src="packages/website/public/sponsors/encore-on-light.svg" alt="Encore" height="40"></picture></a><br><sub>Encore lets AI agents ship to production safely, at scale, in your own cloud.</sub></td>
|
||||
<td align="center" width="33%"><a href="https://paseo.sh/sponsor">Paseo 스폰서 되기</a></td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
@@ -56,9 +56,9 @@ Paseo is an open source agentic development environment for desktop, mobile, web
|
||||
|
||||
<!-- Sponsors: one cell per sponsor in the order of packages/website/src/data/sponsors.ts, then "become a sponsor" cells up to three. -->
|
||||
<table>
|
||||
<tr>
|
||||
<tr valign="top">
|
||||
<td align="center" width="33%"><a href="https://hoplite.sh/?utm_source=paseo&utm_medium=readme&utm_campaign=sponsor"><picture><source media="(prefers-color-scheme: dark)" srcset="packages/website/public/sponsors/hoplite-on-dark.svg"><img src="packages/website/public/sponsors/hoplite-on-light.svg" alt="Hoplite" height="56"></picture></a><br><sub>Cloud coding agents</sub></td>
|
||||
<td align="center" width="33%"><a href="https://paseo.sh/sponsor">Become a sponsor</a></td>
|
||||
<td align="center" width="33%"><a href="https://encore.dev/?utm_source=paseo&utm_medium=readme&utm_campaign=sponsor"><picture><source media="(prefers-color-scheme: dark)" srcset="packages/website/public/sponsors/encore-on-dark.svg"><img src="packages/website/public/sponsors/encore-on-light.svg" alt="Encore" height="56"></picture></a><br><sub>Encore lets AI agents ship to production safely, at scale, in your own cloud.</sub></td>
|
||||
<td align="center" width="33%"><a href="https://paseo.sh/sponsor">Become a sponsor</a></td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
+2
-2
@@ -57,9 +57,9 @@
|
||||
|
||||
<!-- Sponsors: one cell per sponsor in the order of packages/website/src/data/sponsors.ts, then "become a sponsor" cells up to three. -->
|
||||
<table>
|
||||
<tr>
|
||||
<tr valign="top">
|
||||
<td align="center" width="33%"><a href="https://hoplite.sh/?utm_source=paseo&utm_medium=readme&utm_campaign=sponsor"><picture><source media="(prefers-color-scheme: dark)" srcset="packages/website/public/sponsors/hoplite-on-dark.svg"><img src="packages/website/public/sponsors/hoplite-on-light.svg" alt="Hoplite" height="40"></picture></a><br><sub>Cloud coding agents</sub></td>
|
||||
<td align="center" width="33%"><a href="https://paseo.sh/zh-CN/sponsor">成为 Paseo 赞助商</a></td>
|
||||
<td align="center" width="33%"><a href="https://encore.dev/?utm_source=paseo&utm_medium=readme&utm_campaign=sponsor"><picture><source media="(prefers-color-scheme: dark)" srcset="packages/website/public/sponsors/encore-on-dark.svg"><img src="packages/website/public/sponsors/encore-on-light.svg" alt="Encore" height="40"></picture></a><br><sub>Encore lets AI agents ship to production safely, at scale, in your own cloud.</sub></td>
|
||||
<td align="center" width="33%"><a href="https://paseo.sh/zh-CN/sponsor">成为 Paseo 赞助商</a></td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
@@ -80,7 +80,9 @@ Provider checks follow the signals their runtimes expose:
|
||||
- Codex queries background terminals for loaded threads, including native children, and protects
|
||||
pending provider requests. App servers without the terminal-list RPC stay resident.
|
||||
- OpenCode checks active executions and descendants. V1 checks PTYs; v2 also checks shell and
|
||||
inbox inventories. The shared server remains leased while a session vetoes collection.
|
||||
inbox inventories. The shared server remains leased while a session vetoes collection. V2 lets
|
||||
another session's execution veto only when releasing the lease would stop the server; the shared
|
||||
server stays up after its last lease goes.
|
||||
- Pi checks streaming, compaction, pending replies, and adapter-owned operations. Known native
|
||||
subagent signals also protect their parent through the daemon's subagent store.
|
||||
- OMP additionally requires `get_state.isSettled: true` and `hasPendingAsyncWork: false`.
|
||||
|
||||
+1
-1
@@ -34,7 +34,7 @@ Authoritative terminology. UI label wins. Don't invent synonyms; use what's here
|
||||
- **Agent session** — One running instance of an agent inside a workspace (one provider, one model, one cwd, one timeline). The conceptual unit; in the UI this opens as a tab. Moving toward this as the canonical term over "Agent". Code: `AgentSnapshotPayload` (`packages/protocol/src/messages.ts:608`).
|
||||
- **Session** — Two senses: (a) per-client connection to a daemon, internal; (b) user-facing agent session, see **Agent session**. Code: `Session` (`packages/server/src/server/session.ts`) for (a). Don't confuse with: provider-side agent session log.
|
||||
- **Profile** — Internal name for the persisted shape of a host. Code: `HostProfile` (`packages/app/src/types/host-connection.ts:37`). Never user-facing. Three other things are called "profile" in this codebase, so always qualify: **Agent profile**, **Terminal profile**, and the provider aliases in [custom-providers.md](custom-providers.md). Bare "profile" is forbidden in UI copy.
|
||||
- **Agent profile** — A named launch bundle: provider, model, mode, thinking option, feature values, and free-text notes. Applying one writes those values into the **Agent controls** and is then forgotten — there is no selected profile, no default profile, and no drift tracking. The notes are written for orchestrating agents and are what the `list_profiles` MCP tool surfaces. Stored host-wide in daemon config as `agentProfiles`. UI: "Agent profiles". Code: `AgentProfile` (`packages/protocol/src/messages.ts:161`). Carries no system prompt, because a per-agent system prompt can only be set at creation. Forbidden: "Favourite", which this replaced.
|
||||
- **Agent profile** — A named launch bundle: provider, model, mode, thinking option, feature values, optional system prompt, and free-text notes. Applying one writes those values into the **Agent controls** and is then forgotten — there is no selected profile, no default profile, and no drift tracking. The system prompt applies only when creating a new agent and is ignored when applying the profile to a running one. The notes are written for orchestrating agents and are what the `list_profiles` MCP tool surfaces. Stored host-wide in daemon config as `agentProfiles`. UI: "Agent profiles". Code: `AgentProfile` (`packages/protocol/src/agent-profile.ts`). Forbidden: "Favourite", which this replaced.
|
||||
- **Terminal profile** — A named shell command a terminal can launch. Stored host-wide in daemon config as `terminalProfiles`. UI: "Terminal profiles". Code: `TerminalProfile` (`packages/protocol/src/messages.ts:135`), `resolveTerminalProfiles` (`packages/protocol/src/terminal-profiles.ts`). Also selectable as a New Workspace launch target, where the alternative is the chat agent.
|
||||
- **Provider** — Agent backend (Claude Code, Codex, Copilot, OpenCode, Pi, Oh My Pi). UI: "Provider". Code: `ProviderSnapshotEntry` (`packages/protocol/src/messages.ts:198`).
|
||||
- **Hook** — A plugin lifecycle handler registered with `server.addHook`, named `subject.operation.position` with `before` or `after`; each hook declares whether Paseo waits. See [hooks](../public-docs/plugins/hooks.md).
|
||||
|
||||
+12
-2
@@ -10,10 +10,20 @@ Agent payloads name a host and agent. Ignore their workspace hint when opening:
|
||||
the agent can move after a notification is sent. Use `navigateToAgent`, which
|
||||
uses the current store record or the agent route to resolve the workspace from
|
||||
the host. Terminal payloads name their workspace and use `navigateToWorkspace`.
|
||||
Plugin payloads carry `kind: "plugin"`, `serverId`, `pluginId`, `notificationId`,
|
||||
and optional `open` and `data`; `openPluginNotification` in
|
||||
`packages/app/src/plugins/notification-open.ts` waits up to 8 seconds for the
|
||||
target host's plugin catalog to settle on cold launch, runs registered
|
||||
`client.onNotificationOpen` handlers with caught error isolation, and falls back
|
||||
to declarative `open` (`agent`, `workspace`, `screen`) or the host root route.
|
||||
|
||||
See [agent targets and deferred opens](expo-router.md#agent-targets) for route
|
||||
ownership and workspace recovery. Notification generation, presence, and push
|
||||
eligibility remain daemon concerns.
|
||||
ownership and workspace recovery. Per-device two-knob notification preferences
|
||||
(`@getpaseo/protocol/notification-preferences`) sync with mobile push tokens via
|
||||
`register_push_token` (gated on `server_info.features.pushNotificationPreferences`)
|
||||
so the daemon filters Expo pushes per token, while desktop and web clients filter
|
||||
in-app OS notifications locally before calling `sendOsNotification`. Notification
|
||||
generation and presence remain daemon concerns.
|
||||
|
||||
## Native delivery
|
||||
|
||||
|
||||
+21
-1
@@ -1,7 +1,7 @@
|
||||
# Plugins
|
||||
|
||||
Local plugins contribute daemon RPCs, native app surfaces, workspace panels, Command Center items,
|
||||
client slash commands, timeline items, header buttons, composer pills, app themes, composer attachment sources, and settings screens.
|
||||
client slash commands, timeline items, notifications, header buttons, composer pills, app themes, composer attachment sources, and settings screens.
|
||||
Paseo executes `index.server.ts` in a subprocess and `index.client.tsx` in every connected app.
|
||||
|
||||
> **Trust every plugin you add.** `paseo plugin add` and `paseo plugin install` mean “I trust this codebase.” Plugins are unsandboxed: server code and preparation commands run with the daemon user's access on the daemon host, and client contributions run inside Paseo. The repository's dependencies and future updates are part of that trust decision. With `--host`, preparation runs on that remote daemon host.
|
||||
@@ -549,6 +549,26 @@ The same holds for a hook that runs inside an agent's lifecycle lane: an `agent.
|
||||
an option, model, thinking or mode change) waits on the open, which waits on the hook. The hooks
|
||||
reference tells plugin authors to start such a write without awaiting it.
|
||||
|
||||
## Send notifications
|
||||
|
||||
Server plugins call `server.notifications.send(input)` over the `notification.send` /
|
||||
`notification.result` / `notification.error` IPC messages. `PluginNotificationDispatcher` in
|
||||
`packages/server/src/server/plugins/notifications.ts` trims and truncates `title` (<= 160 chars)
|
||||
and `body` (<= 500 chars), validates `key` (<= 128 chars), `open` (IDs <= 256 chars, serialized
|
||||
<= 1,024 UTF-8 bytes), and `data` (<= 1,024 UTF-8 bytes so APNs and FCM envelopes stay within
|
||||
4 KiB), drops duplicate `(pluginId, key)` pairs for 60 seconds, and enforces a per-plugin token
|
||||
bucket (burst 10, refill 1 per 6 seconds). Stopping a plugin clears its deduplication and
|
||||
rate-limit state.
|
||||
|
||||
`WebSocketServer.sendPluginNotification` stamps the runtime `pluginId`, `serverId`, and
|
||||
`notificationId`, runs `computeNotificationPlan` (using `open.agentId` as the focus target when
|
||||
`open.type === "agent"`), filters Expo pushes per token with `{ kind: "plugin", pluginId }`, and
|
||||
publishes `plugin.notification` to sessions subscribed to that event category. Clients gate their
|
||||
`"plugin.notification"` subscription on `server_info.features.pluginNotifications` (`COMPAT(pluginNotifications)`).
|
||||
See [notifications.md](notifications.md) for tap routing and cold-launch catalog readiness, and the
|
||||
[public notifications reference](../public-docs/plugins/reference.md#notifications) for the author
|
||||
contract.
|
||||
|
||||
## Contribute a provider
|
||||
|
||||
Register a provider from `index.server.ts`. The provider connection is callback-based and owns all
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
- Remote workspace browser proxy: Desktop browser tabs in remote workspaces now route through the workspace daemon, so remote localhost servers open directly in Paseo.
|
||||
- Per-device notification preferences: Each device can choose which agent, terminal, and plugin events send notifications, and plugins can send notifications and handle taps.
|
||||
|
||||
Full notes: https://paseo.sh/changelog
|
||||
@@ -0,0 +1,4 @@
|
||||
- Remote workspace browser proxy: Desktop browser tabs in remote workspaces now route through the workspace daemon, so remote localhost servers open directly in Paseo.
|
||||
- Per-device notification preferences: Each device can choose which agent, terminal, and plugin events send notifications, and plugins can send notifications and handle taps.
|
||||
|
||||
Full notes: https://paseo.sh/changelog
|
||||
@@ -0,0 +1,4 @@
|
||||
- Remote workspace browser proxy: Desktop browser tabs in remote workspaces now route through the workspace daemon, so remote localhost servers open directly in Paseo.
|
||||
- Per-device notification preferences: Each device can choose which agent, terminal, and plugin events send notifications, and plugins can send notifications and handle taps.
|
||||
|
||||
Full notes: https://paseo.sh/changelog
|
||||
@@ -0,0 +1,4 @@
|
||||
- Remote workspace browser proxy: Desktop browser tabs in remote workspaces now route through the workspace daemon, so remote localhost servers open directly in Paseo.
|
||||
- Per-device notification preferences: Each device can choose which agent, terminal, and plugin events send notifications, and plugins can send notifications and handle taps.
|
||||
|
||||
Full notes: https://paseo.sh/changelog
|
||||
+1
-1
@@ -1 +1 @@
|
||||
sha256-6XXAVBTH6rIdg5eQ9cUeUwV22ikVqTtdWo7i9DYO+/M=
|
||||
sha256-SZV3WTKLb+JhxWNo/jWyx+2sipzfL93YbbqQSihd3Wo=
|
||||
|
||||
Generated
+29
-29
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "paseo",
|
||||
"version": "0.17.6",
|
||||
"version": "0.18.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "paseo",
|
||||
"version": "0.17.6",
|
||||
"version": "0.18.0",
|
||||
"hasInstallScript": true,
|
||||
"license": "Apache-2.0",
|
||||
"workspaces": [
|
||||
@@ -37541,7 +37541,7 @@
|
||||
},
|
||||
"packages/app": {
|
||||
"name": "@getpaseo/app",
|
||||
"version": "0.17.6",
|
||||
"version": "0.18.0",
|
||||
"dependencies": {
|
||||
"@codemirror/commands": "6.10.4",
|
||||
"@codemirror/language": "6.12.4",
|
||||
@@ -39694,13 +39694,13 @@
|
||||
},
|
||||
"packages/cli": {
|
||||
"name": "@getpaseo/cli",
|
||||
"version": "0.17.6",
|
||||
"version": "0.18.0",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@clack/prompts": "^1.0.0",
|
||||
"@getpaseo/client": "0.17.6",
|
||||
"@getpaseo/protocol": "0.17.6",
|
||||
"@getpaseo/server": "0.17.6",
|
||||
"@getpaseo/client": "0.18.0",
|
||||
"@getpaseo/protocol": "0.18.0",
|
||||
"@getpaseo/server": "0.18.0",
|
||||
"chalk": "^5.3.0",
|
||||
"commander": "^12.0.0",
|
||||
"mime-types": "^2.1.35",
|
||||
@@ -39947,11 +39947,11 @@
|
||||
},
|
||||
"packages/client": {
|
||||
"name": "@getpaseo/client",
|
||||
"version": "0.17.6",
|
||||
"version": "0.18.0",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@getpaseo/protocol": "0.17.6",
|
||||
"@getpaseo/relay": "0.17.6",
|
||||
"@getpaseo/protocol": "0.18.0",
|
||||
"@getpaseo/relay": "0.18.0",
|
||||
"ws": "^8.20.0",
|
||||
"zod": "^4.4.3"
|
||||
},
|
||||
@@ -39963,7 +39963,7 @@
|
||||
},
|
||||
"packages/desktop": {
|
||||
"name": "@getpaseo/desktop",
|
||||
"version": "0.17.6",
|
||||
"version": "0.18.0",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@getpaseo/cli": "*",
|
||||
@@ -40206,7 +40206,7 @@
|
||||
},
|
||||
"packages/expo-two-way-audio": {
|
||||
"name": "@getpaseo/expo-two-way-audio",
|
||||
"version": "0.17.6",
|
||||
"version": "0.18.0",
|
||||
"license": "MIT",
|
||||
"devDependencies": {
|
||||
"@types/jest": "^29.5.14",
|
||||
@@ -40252,7 +40252,7 @@
|
||||
},
|
||||
"packages/highlight": {
|
||||
"name": "@getpaseo/highlight",
|
||||
"version": "0.17.6",
|
||||
"version": "0.18.0",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@codemirror/language": "6.12.4",
|
||||
@@ -40282,7 +40282,7 @@
|
||||
},
|
||||
"packages/plugin": {
|
||||
"name": "@getpaseo/plugin",
|
||||
"version": "0.17.6",
|
||||
"version": "0.18.0",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@agentclientprotocol/sdk": "^1.4.0",
|
||||
@@ -40290,8 +40290,8 @@
|
||||
"use-sync-external-store": "^1.6.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@getpaseo/client": "0.17.6",
|
||||
"@getpaseo/protocol": "0.17.6",
|
||||
"@getpaseo/client": "0.18.0",
|
||||
"@getpaseo/protocol": "0.18.0",
|
||||
"@types/node": "^20.9.0",
|
||||
"@types/react": "~19.2.0",
|
||||
"react": "19.2.3",
|
||||
@@ -40301,8 +40301,8 @@
|
||||
"zod": "^4.4.3"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@getpaseo/client": "0.17.6",
|
||||
"@getpaseo/protocol": "0.17.6",
|
||||
"@getpaseo/client": "0.18.0",
|
||||
"@getpaseo/protocol": "0.18.0",
|
||||
"react": ">=19.1.0 <20",
|
||||
"react-native": ">=0.81.5",
|
||||
"zod": "^4.4.3"
|
||||
@@ -40324,7 +40324,7 @@
|
||||
},
|
||||
"packages/protocol": {
|
||||
"name": "@getpaseo/protocol",
|
||||
"version": "0.17.6",
|
||||
"version": "0.18.0",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"semver": "^7.8.5",
|
||||
@@ -40351,7 +40351,7 @@
|
||||
}
|
||||
},
|
||||
"packages/react-native-enriched-markdown": {
|
||||
"version": "0.17.6",
|
||||
"version": "0.18.0",
|
||||
"hasInstallScript": true,
|
||||
"license": "MIT",
|
||||
"peerDependencies": {
|
||||
@@ -40367,7 +40367,7 @@
|
||||
},
|
||||
"packages/relay": {
|
||||
"name": "@getpaseo/relay",
|
||||
"version": "0.17.6",
|
||||
"version": "0.18.0",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@noble/ciphers": "^2.4.0",
|
||||
@@ -40589,17 +40589,17 @@
|
||||
},
|
||||
"packages/server": {
|
||||
"name": "@getpaseo/server",
|
||||
"version": "0.17.6",
|
||||
"version": "0.18.0",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@agentclientprotocol/sdk": "^0.17.1",
|
||||
"@anthropic-ai/claude-agent-sdk": "0.3.326",
|
||||
"@anthropic-ai/sdk": "^0.104.2",
|
||||
"@getpaseo/client": "0.17.6",
|
||||
"@getpaseo/highlight": "0.17.6",
|
||||
"@getpaseo/plugin": "0.17.6",
|
||||
"@getpaseo/protocol": "0.17.6",
|
||||
"@getpaseo/relay": "0.17.6",
|
||||
"@getpaseo/client": "0.18.0",
|
||||
"@getpaseo/highlight": "0.18.0",
|
||||
"@getpaseo/plugin": "0.18.0",
|
||||
"@getpaseo/protocol": "0.18.0",
|
||||
"@getpaseo/relay": "0.18.0",
|
||||
"@isaacs/ttlcache": "^2.1.4",
|
||||
"@modelcontextprotocol/node": "2.1.2",
|
||||
"@modelcontextprotocol/sdk": "1.29.0",
|
||||
@@ -41550,7 +41550,7 @@
|
||||
},
|
||||
"packages/website": {
|
||||
"name": "@getpaseo/website",
|
||||
"version": "0.17.6",
|
||||
"version": "0.18.0",
|
||||
"dependencies": {
|
||||
"@cloudflare/vite-plugin": "^1.29.1",
|
||||
"@cloudflare/workers-types": "^4.20260317.1",
|
||||
@@ -43161,7 +43161,7 @@
|
||||
},
|
||||
"plugins": {
|
||||
"name": "@getpaseo/builtin-plugins",
|
||||
"version": "0.17.6",
|
||||
"version": "0.18.0",
|
||||
"dependencies": {
|
||||
"@getpaseo/plugin": "*",
|
||||
"zod": "^4.4.3"
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "paseo",
|
||||
"version": "0.17.6",
|
||||
"version": "0.18.0",
|
||||
"private": true,
|
||||
"description": "Paseo: voice-controlled development environment for local AI coding agents",
|
||||
"keywords": [
|
||||
|
||||
@@ -67,6 +67,9 @@ test.describe("Agent profiles settings", () => {
|
||||
try {
|
||||
await test.step("the section starts empty", async () => {
|
||||
await openAgentProfileSettings(page);
|
||||
await expect(page.getByTestId("agent-profiles-description")).toHaveText(
|
||||
"Save agent settings that you can pick quickly and that agents can use to delegate work",
|
||||
);
|
||||
await expectNoAgentProfiles(page);
|
||||
});
|
||||
|
||||
@@ -77,11 +80,18 @@ test.describe("Agent profiles settings", () => {
|
||||
model: "Ten second stream",
|
||||
thinking: "High",
|
||||
mode: "Approval test",
|
||||
systemPrompt: "Focus on layout, accessibility, and design tokens.",
|
||||
notes: "Use for UI work — components, layout and design tokens.",
|
||||
});
|
||||
await expectAgentProfile(page, {
|
||||
name: "UI work",
|
||||
tags: [MOCK_PROVIDER_LABEL, "Ten second stream", "Approval test", "High"],
|
||||
tags: [
|
||||
MOCK_PROVIDER_LABEL,
|
||||
"Ten second stream",
|
||||
"Approval test",
|
||||
"High",
|
||||
"System prompt",
|
||||
],
|
||||
notes: "Use for UI work — components, layout and design tokens.",
|
||||
});
|
||||
});
|
||||
@@ -89,11 +99,12 @@ test.describe("Agent profiles settings", () => {
|
||||
await test.step("editing to a model without thinking levels drops the level", async () => {
|
||||
await editAgentProfile(page, "UI work", {
|
||||
model: "One minute stream",
|
||||
systemPrompt: "Keep replies concise.",
|
||||
notes: "Now for quick checks.",
|
||||
});
|
||||
await expectAgentProfile(page, {
|
||||
name: "UI work",
|
||||
tags: [MOCK_PROVIDER_LABEL, "One minute stream", "Approval test"],
|
||||
tags: [MOCK_PROVIDER_LABEL, "One minute stream", "Approval test", "System prompt"],
|
||||
notes: "Now for quick checks.",
|
||||
});
|
||||
await expectAgentProfileTagsGone(page, {
|
||||
@@ -107,6 +118,7 @@ test.describe("Agent profiles settings", () => {
|
||||
provider: MOCK_PROVIDER_LABEL,
|
||||
model: "One minute stream",
|
||||
mode: "Approval test",
|
||||
systemPrompt: "Keep replies concise.",
|
||||
notes: "Now for quick checks.",
|
||||
});
|
||||
});
|
||||
|
||||
@@ -12,9 +12,12 @@ import {
|
||||
openImageLightbox,
|
||||
closeImageLightbox,
|
||||
pressInterruptShortcut,
|
||||
blurComposerInput,
|
||||
expectComposerDraft,
|
||||
expectComposerDisabled,
|
||||
expectComposerEditable,
|
||||
expectComposerFocused,
|
||||
expectComposerNotFocused,
|
||||
expectAttachButtonDisabled,
|
||||
fillComposerDraft,
|
||||
dropFileOnComposer,
|
||||
@@ -175,8 +178,19 @@ test.describe("Composer attachments", () => {
|
||||
await test.step("remove the image and attach a dropped file", async () => {
|
||||
await removeAttachmentPill(page, "composer-image-attachment-pill", "Remove image attachment");
|
||||
await expect(page.getByTestId("composer-image-attachment-pill")).toHaveCount(0);
|
||||
await blurComposerInput(page);
|
||||
await expectComposerNotFocused(page);
|
||||
await dropFileOnComposer(page, TEST_JSON);
|
||||
await expectAttachmentPill(page, "composer-file-attachment-pill");
|
||||
await expectComposerFocused(page);
|
||||
});
|
||||
|
||||
await test.step("dropping an image focuses the composer", async () => {
|
||||
await blurComposerInput(page);
|
||||
await expectComposerNotFocused(page);
|
||||
await dropFileOnComposer(page, TEST_IMAGE);
|
||||
await expectAttachmentPill(page, "composer-image-attachment-pill");
|
||||
await expectComposerFocused(page);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -198,9 +212,12 @@ test.describe("Composer attachments", () => {
|
||||
projectDisplayName: workspace.projectDisplayName,
|
||||
});
|
||||
|
||||
await blurComposerInput(page);
|
||||
await expectComposerNotFocused(page);
|
||||
await dropFileOnComposer(page, TEST_JSON);
|
||||
|
||||
await expectAttachmentPill(page, "composer-file-attachment-pill");
|
||||
await expectComposerFocused(page);
|
||||
} finally {
|
||||
await workspace.cleanup();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,235 @@
|
||||
import { mkdir, writeFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { expect, test, type Page } from "../support/fixtures";
|
||||
import {
|
||||
openFileExplorer,
|
||||
openFileFromExplorer,
|
||||
expectFileTabOpen,
|
||||
} from "../support/helpers/file-explorer";
|
||||
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
|
||||
|
||||
const APP_SETTINGS_KEY = "@paseo:app-settings";
|
||||
|
||||
const DIFF_FIXTURE = [
|
||||
"Here is a diff block:",
|
||||
"",
|
||||
"```diff",
|
||||
"diff --git a/src/greet.ts b/src/greet.ts",
|
||||
"--- a/src/greet.ts",
|
||||
"+++ b/src/greet.ts",
|
||||
"@@ -1,3 +1,4 @@ export function greet(name: string) {",
|
||||
" const prefix = 'Hello';",
|
||||
"- return `${prefix}, ${name}`;",
|
||||
"+ const trimmed = name.trim();",
|
||||
"+ return `${prefix}, ${trimmed}!`;",
|
||||
"```",
|
||||
"",
|
||||
"And a patch block:",
|
||||
"",
|
||||
"```patch",
|
||||
"--- a/README.md",
|
||||
"+++ b/README.md",
|
||||
"@@ -1,2 +1,2 @@",
|
||||
" # Paseo",
|
||||
"-Old description",
|
||||
"+New description",
|
||||
"```",
|
||||
"",
|
||||
"Plus Ruby, Kotlin, TOML, and SQL:",
|
||||
"",
|
||||
"```ruby",
|
||||
"class Greeter",
|
||||
' def hi(name) = "Hello #{name}"',
|
||||
"end",
|
||||
"```",
|
||||
"",
|
||||
"```kotlin",
|
||||
'val message: String = "Kotlin ready"',
|
||||
"```",
|
||||
"",
|
||||
"```toml",
|
||||
"[server]",
|
||||
'host = "localhost"',
|
||||
"```",
|
||||
"",
|
||||
"```sql",
|
||||
"SELECT id, name FROM users WHERE active = TRUE;",
|
||||
"```",
|
||||
].join("\n");
|
||||
|
||||
const FILE_DIFF_CONTENT = [
|
||||
"diff --git a/app.py b/app.py",
|
||||
"index 1111111..2222222 100644",
|
||||
"--- a/app.py",
|
||||
"+++ b/app.py",
|
||||
"@@ -1,3 +1,3 @@ def greet():",
|
||||
" print('hello')",
|
||||
"-old_value = 1",
|
||||
"+new_value = 2",
|
||||
].join("\n");
|
||||
|
||||
async function saveScreenshot(page: Page, name: string): Promise<void> {
|
||||
const dir = process.env.PASEO_QA_SCREENSHOT_DIR;
|
||||
if (!dir) return;
|
||||
await mkdir(dir, { recursive: true });
|
||||
await page.screenshot({ path: path.join(dir, name), fullPage: true });
|
||||
}
|
||||
|
||||
function assistantMessages(page: Page) {
|
||||
return page.locator("[data-message-id]").filter({ has: page.getByTestId("assistant-message") });
|
||||
}
|
||||
|
||||
test.describe("diff and patch syntax highlighting", () => {
|
||||
for (const theme of ["dark", "light"] as const) {
|
||||
test(`highlights diff and patch fences in chat (${theme} theme)`, async ({ page }) => {
|
||||
await page.addInitScript(
|
||||
({ key, mode }) => {
|
||||
localStorage.setItem(key, JSON.stringify({ theme: mode }));
|
||||
},
|
||||
{ key: APP_SETTINGS_KEY, mode: theme },
|
||||
);
|
||||
|
||||
const agent = await seedMockAgentWorkspace({
|
||||
repoPrefix: `diff-chat-${theme}-`,
|
||||
title: `Diff highlight (${theme})`,
|
||||
initialPrompt: "Show me the diff and patch.",
|
||||
featureValues: { mockAssistantResponse: DIFF_FIXTURE },
|
||||
});
|
||||
|
||||
try {
|
||||
await agent.client.waitForAgentUpsert(
|
||||
agent.agentId,
|
||||
(snapshot) => snapshot.status === "idle",
|
||||
30_000,
|
||||
);
|
||||
await openAgentRoute(page, agent);
|
||||
|
||||
const message = assistantMessages(page);
|
||||
const expectedColors =
|
||||
theme === "dark"
|
||||
? {
|
||||
addition: "rgb(152, 195, 121)",
|
||||
deletion: "rgb(224, 108, 117)",
|
||||
meta: "rgb(92, 99, 112)",
|
||||
}
|
||||
: {
|
||||
addition: "rgb(52, 130, 51)",
|
||||
deletion: "rgb(214, 59, 47)",
|
||||
meta: "rgb(160, 161, 167)",
|
||||
};
|
||||
|
||||
const diffAdd = message.getByText("+ const trimmed = name.trim();", { exact: true });
|
||||
const diffDel = message.getByText("- return `${prefix}, ${name}`;", { exact: true });
|
||||
const diffMeta = message.getByText(
|
||||
"@@ -1,3 +1,4 @@ export function greet(name: string) {",
|
||||
{
|
||||
exact: true,
|
||||
},
|
||||
);
|
||||
const patchAdd = message.getByText("+New description", { exact: true });
|
||||
const patchDel = message.getByText("-Old description", { exact: true });
|
||||
|
||||
await expect(diffAdd).toBeVisible({ timeout: 30_000 });
|
||||
await expect(diffAdd).toHaveCSS("color", expectedColors.addition);
|
||||
await expect(diffDel).toHaveCSS("color", expectedColors.deletion);
|
||||
await expect(diffMeta).toHaveCSS("color", expectedColors.meta);
|
||||
await expect(patchAdd).toHaveCSS("color", expectedColors.addition);
|
||||
await expect(patchDel).toHaveCSS("color", expectedColors.deletion);
|
||||
|
||||
const rubyDef = message.getByText("def", { exact: true });
|
||||
const kotlinVal = message.getByText("val", { exact: true });
|
||||
const tomlHost = message.getByText("host", { exact: true });
|
||||
const sqlSelect = message.getByText("SELECT", { exact: true });
|
||||
const expectedKeyword = theme === "dark" ? "rgb(198, 120, 221)" : "rgb(166, 38, 164)";
|
||||
const expectedProperty = theme === "dark" ? "rgb(209, 154, 102)" : "rgb(152, 104, 1)";
|
||||
await expect(rubyDef).toHaveCSS("color", expectedKeyword);
|
||||
await expect(kotlinVal).toHaveCSS("color", expectedKeyword);
|
||||
await expect(tomlHost).toHaveCSS("color", expectedProperty);
|
||||
await expect(sqlSelect).toHaveCSS("color", expectedKeyword);
|
||||
|
||||
await saveScreenshot(page, `chat-diff-patch-${theme}.png`);
|
||||
} finally {
|
||||
await agent.cleanup();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
test("highlights a .diff file in the Files viewer", async ({ page, withWorkspace }) => {
|
||||
await page.addInitScript(
|
||||
({ key }) => {
|
||||
localStorage.setItem(key, JSON.stringify({ theme: "dark" }));
|
||||
},
|
||||
{ key: APP_SETTINGS_KEY },
|
||||
);
|
||||
const workspace = await withWorkspace({ prefix: "diff-file-viewer-" });
|
||||
await writeFile(path.join(workspace.repoPath, "changes.diff"), FILE_DIFF_CONTENT);
|
||||
|
||||
await workspace.navigateTo();
|
||||
await openFileExplorer(page);
|
||||
await openFileFromExplorer(page, "changes.diff");
|
||||
await expectFileTabOpen(page, "changes.diff");
|
||||
|
||||
const editor = page.getByTestId("file-source-editor").filter({ visible: true });
|
||||
await expect(editor).toBeVisible({ timeout: 30_000 });
|
||||
|
||||
const addLine = editor
|
||||
.locator(".cm-line", { hasText: "+new_value = 2" })
|
||||
.locator("span")
|
||||
.first();
|
||||
const delLine = editor
|
||||
.locator(".cm-line", { hasText: "-old_value = 1" })
|
||||
.locator("span")
|
||||
.first();
|
||||
const metaLine = editor
|
||||
.locator(".cm-line", { hasText: "@@ -1,3 +1,3 @@ def greet():" })
|
||||
.locator("span")
|
||||
.first();
|
||||
|
||||
await expect(addLine).toHaveCSS("color", "rgb(152, 195, 121)");
|
||||
await expect(delLine).toHaveCSS("color", "rgb(224, 108, 117)");
|
||||
await expect(metaLine).toHaveCSS("color", "rgb(92, 99, 112)");
|
||||
|
||||
await saveScreenshot(page, "files-viewer-diff-dark.png");
|
||||
});
|
||||
|
||||
test("highlights a .patch file in the Files viewer (light theme)", async ({
|
||||
page,
|
||||
withWorkspace,
|
||||
}) => {
|
||||
await page.addInitScript(
|
||||
({ key }) => {
|
||||
localStorage.setItem(key, JSON.stringify({ theme: "light" }));
|
||||
},
|
||||
{ key: APP_SETTINGS_KEY },
|
||||
);
|
||||
const workspace = await withWorkspace({ prefix: "patch-file-viewer-" });
|
||||
await writeFile(path.join(workspace.repoPath, "fix.patch"), FILE_DIFF_CONTENT);
|
||||
|
||||
await workspace.navigateTo();
|
||||
await openFileExplorer(page);
|
||||
await openFileFromExplorer(page, "fix.patch");
|
||||
await expectFileTabOpen(page, "fix.patch");
|
||||
|
||||
const editor = page.getByTestId("file-source-editor").filter({ visible: true });
|
||||
await expect(editor).toBeVisible({ timeout: 30_000 });
|
||||
|
||||
const addLine = editor
|
||||
.locator(".cm-line", { hasText: "+new_value = 2" })
|
||||
.locator("span")
|
||||
.first();
|
||||
const delLine = editor
|
||||
.locator(".cm-line", { hasText: "-old_value = 1" })
|
||||
.locator("span")
|
||||
.first();
|
||||
const metaLine = editor
|
||||
.locator(".cm-line", { hasText: "@@ -1,3 +1,3 @@ def greet():" })
|
||||
.locator("span")
|
||||
.first();
|
||||
|
||||
await expect(addLine).toHaveCSS("color", "rgb(52, 130, 51)");
|
||||
await expect(delLine).toHaveCSS("color", "rgb(214, 59, 47)");
|
||||
await expect(metaLine).toHaveCSS("color", "rgb(160, 161, 167)");
|
||||
|
||||
await saveScreenshot(page, "files-viewer-patch-light.png");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,245 @@
|
||||
import { expect, test } from "../support/fixtures";
|
||||
import { gotoAppShell, openSettings } from "../support/helpers/app";
|
||||
import {
|
||||
clearRecordedBrowserNotifications,
|
||||
clickRecordedBrowserNotification,
|
||||
expectDefaultNotificationSettings,
|
||||
expectNotificationSubControlsDisabled,
|
||||
expectNotificationSwitchState,
|
||||
expectRecordedAgentNotifications,
|
||||
expectRecordedPluginNotifications,
|
||||
installBrowserNotificationRecorder,
|
||||
openNotificationSettings,
|
||||
readRecordedBrowserNotifications,
|
||||
setNotificationSwitch,
|
||||
setPluginNotificationSwitch,
|
||||
} from "../support/helpers/notification-settings";
|
||||
import { copyPluginExample } from "../support/helpers/plugin-fixture";
|
||||
import { seedWorkspace, type SeedDaemonClient } from "../support/helpers/seed-client";
|
||||
|
||||
const FAST_FINISHED_PROMPT =
|
||||
"emit settled assistant image markdown: ";
|
||||
const PERMISSION_PROMPT = "emit a synthetic plan approval";
|
||||
const ERROR_PROMPT = "emit a synthetic turn failure";
|
||||
|
||||
async function runMockAgentTurn(
|
||||
client: SeedDaemonClient,
|
||||
input: {
|
||||
cwd: string;
|
||||
workspaceId: string;
|
||||
title: string;
|
||||
prompt: string;
|
||||
waitForStatus: "idle" | "error" | "running";
|
||||
},
|
||||
): Promise<string> {
|
||||
const agent = await client.createAgent({
|
||||
provider: "mock",
|
||||
cwd: input.cwd,
|
||||
workspaceId: input.workspaceId,
|
||||
title: input.title,
|
||||
modeId: "load-test",
|
||||
model: "e2e-fast-stream",
|
||||
initialPrompt: input.prompt,
|
||||
});
|
||||
await client.waitForAgentUpsert(
|
||||
agent.id,
|
||||
(snapshot) => snapshot.status === input.waitForStatus,
|
||||
15_000,
|
||||
);
|
||||
return agent.id;
|
||||
}
|
||||
|
||||
test.describe("Settings → Notifications and OS notification filtering", () => {
|
||||
test("displays defaults, persists switch changes across reload, disables sub-controls when paused, and filters OS notifications", async ({
|
||||
page,
|
||||
}) => {
|
||||
await installBrowserNotificationRecorder(page);
|
||||
const seeded = await seedWorkspace({ repoPrefix: "notification-settings-" });
|
||||
const pluginExample = await copyPluginExample("notifications");
|
||||
let installedPlugin = false;
|
||||
|
||||
try {
|
||||
await gotoAppShell(page);
|
||||
await openSettings(page);
|
||||
await openNotificationSettings(page);
|
||||
|
||||
await test.step("renders Settings → Notifications with expected out-of-the-box defaults", async () => {
|
||||
await expectDefaultNotificationSettings(page);
|
||||
await expect(
|
||||
page.getByText("Installed plugins appear here so you can mute them individually", {
|
||||
exact: true,
|
||||
}),
|
||||
).toBeVisible();
|
||||
});
|
||||
|
||||
await test.step("default preferences suppress finished turn notifications while delivering permission and error notifications", async () => {
|
||||
await clearRecordedBrowserNotifications(page);
|
||||
|
||||
await runMockAgentTurn(seeded.client, {
|
||||
cwd: seeded.repoPath,
|
||||
workspaceId: seeded.workspaceId,
|
||||
title: "Default finished agent",
|
||||
prompt: FAST_FINISHED_PROMPT,
|
||||
waitForStatus: "idle",
|
||||
});
|
||||
|
||||
const permissionAgentId = await runMockAgentTurn(seeded.client, {
|
||||
cwd: seeded.repoPath,
|
||||
workspaceId: seeded.workspaceId,
|
||||
title: "Default permission agent",
|
||||
prompt: PERMISSION_PROMPT,
|
||||
waitForStatus: "running",
|
||||
});
|
||||
|
||||
const errorAgentId = await runMockAgentTurn(seeded.client, {
|
||||
cwd: seeded.repoPath,
|
||||
workspaceId: seeded.workspaceId,
|
||||
title: "Default error agent",
|
||||
prompt: ERROR_PROMPT,
|
||||
waitForStatus: "error",
|
||||
});
|
||||
|
||||
await expectRecordedAgentNotifications(page, [
|
||||
{ agentId: permissionAgentId, reason: "permission" },
|
||||
{ agentId: errorAgentId, reason: "error" },
|
||||
]);
|
||||
});
|
||||
|
||||
await test.step("enabling Agent finished persists across page reload and allows finished notifications", async () => {
|
||||
await setNotificationSwitch(page, "Agent finished", true);
|
||||
await page.reload();
|
||||
await expectNotificationSwitchState(page, "Agent finished", {
|
||||
checked: true,
|
||||
disabled: false,
|
||||
});
|
||||
|
||||
await clearRecordedBrowserNotifications(page);
|
||||
|
||||
const finishedAgentId = await runMockAgentTurn(seeded.client, {
|
||||
cwd: seeded.repoPath,
|
||||
workspaceId: seeded.workspaceId,
|
||||
title: "Enabled finished agent",
|
||||
prompt: FAST_FINISHED_PROMPT,
|
||||
waitForStatus: "idle",
|
||||
});
|
||||
|
||||
await expectRecordedAgentNotifications(page, [
|
||||
{ agentId: finishedAgentId, reason: "finished" },
|
||||
]);
|
||||
});
|
||||
|
||||
await test.step("toggling Enable notifications off disables sub-controls, persists across reload, and suppresses all notifications", async () => {
|
||||
await setNotificationSwitch(page, "Enable notifications", false);
|
||||
await expect(
|
||||
page.getByText("All notifications, including plugins, are paused on this device", {
|
||||
exact: true,
|
||||
}),
|
||||
).toBeVisible();
|
||||
await expectNotificationSubControlsDisabled(page, true);
|
||||
|
||||
await page.reload();
|
||||
await expectNotificationSwitchState(page, "Enable notifications", {
|
||||
checked: false,
|
||||
disabled: false,
|
||||
});
|
||||
await expectNotificationSubControlsDisabled(page, true);
|
||||
|
||||
await clearRecordedBrowserNotifications(page);
|
||||
|
||||
await runMockAgentTurn(seeded.client, {
|
||||
cwd: seeded.repoPath,
|
||||
workspaceId: seeded.workspaceId,
|
||||
title: "Paused error agent",
|
||||
prompt: ERROR_PROMPT,
|
||||
waitForStatus: "error",
|
||||
});
|
||||
|
||||
await runMockAgentTurn(seeded.client, {
|
||||
cwd: seeded.repoPath,
|
||||
workspaceId: seeded.workspaceId,
|
||||
title: "Paused finished agent",
|
||||
prompt: FAST_FINISHED_PROMPT,
|
||||
waitForStatus: "idle",
|
||||
});
|
||||
|
||||
// Give any in-flight event delivery a chance to settle and verify none fired.
|
||||
await page.waitForTimeout(300);
|
||||
expect(await readRecordedBrowserNotifications(page)).toEqual([]);
|
||||
});
|
||||
|
||||
await test.step("delivers plugin notifications, routes OS notification taps through client.onNotificationOpen, and suppresses notifications when the plugin is muted", async () => {
|
||||
await setNotificationSwitch(page, "Enable notifications", true);
|
||||
await seeded.client.patchDaemonConfig({ pluginsEnabled: true });
|
||||
await seeded.client.installDirectoryPlugin(pluginExample.directory);
|
||||
installedPlugin = true;
|
||||
|
||||
const pluginToggle = page.getByRole("switch", { name: "Build alerts", exact: true });
|
||||
await expect(pluginToggle).toBeVisible();
|
||||
await expect(pluginToggle).toHaveAttribute("aria-checked", "true");
|
||||
|
||||
await clearRecordedBrowserNotifications(page);
|
||||
|
||||
const sent = (await seeded.client.invokePluginRpc("notifications-example", "alerts.send", {
|
||||
buildId: "204",
|
||||
title: "Build #204 failed",
|
||||
body: "Playwright suite failed on main",
|
||||
})) as { status: string; notificationId: string };
|
||||
expect(sent.status).toBe("sent");
|
||||
|
||||
await expectRecordedPluginNotifications(page, [
|
||||
{
|
||||
pluginId: "notifications-example",
|
||||
title: "Build #204 failed",
|
||||
body: "Playwright suite failed on main",
|
||||
notificationId: sent.notificationId,
|
||||
},
|
||||
]);
|
||||
|
||||
await clickRecordedBrowserNotification(page, 0);
|
||||
await expect(page.getByText("Build alert #204", { exact: true })).toBeVisible();
|
||||
await expect(
|
||||
page.getByText("Playwright suite failed on main", { exact: true }),
|
||||
).toBeVisible();
|
||||
await expect(
|
||||
page.getByText(`Notification ID: ${sent.notificationId}`, { exact: true }),
|
||||
).toBeVisible();
|
||||
|
||||
await openSettings(page);
|
||||
await openNotificationSettings(page);
|
||||
await setPluginNotificationSwitch(page, "Build alerts", false);
|
||||
await clearRecordedBrowserNotifications(page);
|
||||
|
||||
const mutedResult = (await seeded.client.invokePluginRpc(
|
||||
"notifications-example",
|
||||
"alerts.send",
|
||||
{
|
||||
buildId: "205",
|
||||
title: "Build #205 failed",
|
||||
body: "Muted build alert",
|
||||
},
|
||||
)) as { status: string };
|
||||
expect(mutedResult.status).toBe("sent");
|
||||
|
||||
// Trigger an unmuted agent error notification so we prove delivery settled and only
|
||||
// the unmuted notification arrived (Build #205 was suppressed).
|
||||
const sentinelErrorAgentId = await runMockAgentTurn(seeded.client, {
|
||||
cwd: seeded.repoPath,
|
||||
workspaceId: seeded.workspaceId,
|
||||
title: "Sentinel unmuted error agent",
|
||||
prompt: ERROR_PROMPT,
|
||||
waitForStatus: "error",
|
||||
});
|
||||
|
||||
await expectRecordedAgentNotifications(page, [
|
||||
{ agentId: sentinelErrorAgentId, reason: "error" },
|
||||
]);
|
||||
});
|
||||
} finally {
|
||||
if (installedPlugin) {
|
||||
await seeded.client.removePlugin("notifications-example").catch(() => undefined);
|
||||
}
|
||||
await pluginExample.cleanup().catch(() => undefined);
|
||||
await seeded.cleanup();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -257,6 +257,7 @@ export interface AgentProfileDraft {
|
||||
model?: string;
|
||||
thinking?: string;
|
||||
mode?: string;
|
||||
systemPrompt?: string;
|
||||
notes?: string;
|
||||
}
|
||||
|
||||
@@ -319,7 +320,12 @@ async function fillAgentProfileForm(page: Page, draft: AgentProfileDraft): Promi
|
||||
if (draft.name !== undefined) {
|
||||
await surface.getByRole("textbox", { name: "Name", exact: true }).fill(draft.name);
|
||||
}
|
||||
if (draft.thinking !== undefined || draft.mode !== undefined || draft.notes !== undefined) {
|
||||
if (
|
||||
draft.thinking !== undefined ||
|
||||
draft.mode !== undefined ||
|
||||
draft.systemPrompt !== undefined ||
|
||||
draft.notes !== undefined
|
||||
) {
|
||||
await ensureCustomizeExpanded(surface);
|
||||
}
|
||||
if (draft.mode !== undefined) {
|
||||
@@ -337,6 +343,11 @@ async function fillAgentProfileForm(page: Page, draft: AgentProfileDraft): Promi
|
||||
await chooseSelectFieldOption(page, { field: "thinking", option: draft.thinking });
|
||||
}
|
||||
}
|
||||
if (draft.systemPrompt !== undefined) {
|
||||
await surface
|
||||
.getByRole("textbox", { name: "System prompt", exact: true })
|
||||
.fill(draft.systemPrompt);
|
||||
}
|
||||
if (draft.notes !== undefined) {
|
||||
await surface.getByRole("textbox", { name: "When to use", exact: true }).fill(draft.notes);
|
||||
}
|
||||
@@ -518,12 +529,20 @@ export async function browserHistoryJumpWithConfirm(
|
||||
export async function expectAgentProfileForm(
|
||||
page: Page,
|
||||
name: string,
|
||||
expected: { provider?: string; model?: string; mode?: string; notes?: string },
|
||||
expected: {
|
||||
provider?: string;
|
||||
model?: string;
|
||||
mode?: string;
|
||||
systemPrompt?: string;
|
||||
notes?: string;
|
||||
},
|
||||
): Promise<void> {
|
||||
await agentProfileRow(page, name).click();
|
||||
const surface = editSurface(page);
|
||||
await expect(surface).toBeVisible({ timeout: 30_000 });
|
||||
await expect(surface.getByRole("textbox", { name: "Name", exact: true })).toHaveValue(name);
|
||||
const systemPromptHint = surface.getByTestId("agent-profile-system-prompt-field-hint");
|
||||
await expect(systemPromptHint).toHaveText("Applies to new agents only");
|
||||
const notesHint = surface.getByTestId("agent-profile-notes-field-hint");
|
||||
await expect(notesHint).toHaveText("Tells agents when to pick this profile");
|
||||
expect(await notesHint.evaluate((element) => getComputedStyle(element).webkitLineClamp)).not.toBe(
|
||||
@@ -542,6 +561,11 @@ export async function expectAgentProfileForm(
|
||||
if (expected.mode) {
|
||||
await expect(surface.getByTestId("agent-profile-mode-trigger")).toContainText(expected.mode);
|
||||
}
|
||||
if (expected.systemPrompt !== undefined) {
|
||||
await expect(surface.getByRole("textbox", { name: "System prompt", exact: true })).toHaveValue(
|
||||
expected.systemPrompt,
|
||||
);
|
||||
}
|
||||
if (expected.notes !== undefined) {
|
||||
await expect(surface.getByRole("textbox", { name: "When to use", exact: true })).toHaveValue(
|
||||
expected.notes,
|
||||
|
||||
@@ -0,0 +1,269 @@
|
||||
import { expect, type Page } from "@playwright/test";
|
||||
import { openSettingsSection } from "./settings";
|
||||
|
||||
export interface RecordedBrowserNotification {
|
||||
title: string;
|
||||
body: string | null;
|
||||
data: Record<string, unknown> | null;
|
||||
}
|
||||
|
||||
type NotificationSwitchName =
|
||||
| "Enable notifications"
|
||||
| "Agent needs permission"
|
||||
| "Agent errored"
|
||||
| "Agent finished"
|
||||
| "Terminal needs input"
|
||||
| "Terminal finished"
|
||||
| "Plugin notifications";
|
||||
|
||||
export async function installBrowserNotificationRecorder(page: Page): Promise<void> {
|
||||
await page.addInitScript(() => {
|
||||
const recorded: RecordedBrowserNotification[] = [];
|
||||
const instances: Array<{ triggerClick: () => void }> = [];
|
||||
const win = window as unknown as {
|
||||
__paseoRecordedNotifications?: RecordedBrowserNotification[];
|
||||
__paseoNotificationInstances?: Array<{ triggerClick: () => void }>;
|
||||
};
|
||||
win.__paseoRecordedNotifications = recorded;
|
||||
win.__paseoNotificationInstances = instances;
|
||||
|
||||
class StubBrowserNotification {
|
||||
static permission: NotificationPermission = "granted";
|
||||
static async requestPermission(): Promise<NotificationPermission> {
|
||||
return "granted";
|
||||
}
|
||||
|
||||
title: string;
|
||||
body: string | null;
|
||||
data: Record<string, unknown> | null;
|
||||
private readonly clickListeners: Array<() => void> = [];
|
||||
|
||||
constructor(
|
||||
title: string,
|
||||
options?: { body?: string; data?: Record<string, unknown>; icon?: string },
|
||||
) {
|
||||
this.title = title;
|
||||
this.body = options?.body ?? null;
|
||||
this.data = options?.data ?? null;
|
||||
recorded.push({
|
||||
title: this.title,
|
||||
body: this.body,
|
||||
data: this.data,
|
||||
});
|
||||
instances.push({
|
||||
triggerClick: () => {
|
||||
for (const listener of this.clickListeners) {
|
||||
listener();
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
addEventListener(type: string, listener: () => void): void {
|
||||
if (type === "click" && typeof listener === "function") {
|
||||
this.clickListeners.push(listener);
|
||||
}
|
||||
}
|
||||
close(): void {}
|
||||
}
|
||||
|
||||
Object.defineProperty(window, "Notification", {
|
||||
configurable: true,
|
||||
writable: true,
|
||||
value: StubBrowserNotification,
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export async function readRecordedBrowserNotifications(
|
||||
page: Page,
|
||||
): Promise<RecordedBrowserNotification[]> {
|
||||
return page.evaluate(() => {
|
||||
const win = window as unknown as {
|
||||
__paseoRecordedNotifications?: RecordedBrowserNotification[];
|
||||
};
|
||||
return [...(win.__paseoRecordedNotifications ?? [])];
|
||||
});
|
||||
}
|
||||
|
||||
export async function clearRecordedBrowserNotifications(page: Page): Promise<void> {
|
||||
await page.evaluate(() => {
|
||||
const win = window as unknown as {
|
||||
__paseoRecordedNotifications?: RecordedBrowserNotification[];
|
||||
__paseoNotificationInstances?: Array<{ triggerClick: () => void }>;
|
||||
};
|
||||
if (win.__paseoRecordedNotifications) {
|
||||
win.__paseoRecordedNotifications.length = 0;
|
||||
}
|
||||
if (win.__paseoNotificationInstances) {
|
||||
win.__paseoNotificationInstances.length = 0;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
export async function clickRecordedBrowserNotification(page: Page, index = 0): Promise<void> {
|
||||
await page.evaluate((targetIndex) => {
|
||||
const win = window as unknown as {
|
||||
__paseoNotificationInstances?: Array<{ triggerClick: () => void }>;
|
||||
};
|
||||
const instance = win.__paseoNotificationInstances?.[targetIndex];
|
||||
if (!instance) {
|
||||
throw new Error(`No recorded browser notification at index ${targetIndex}`);
|
||||
}
|
||||
instance.triggerClick();
|
||||
}, index);
|
||||
}
|
||||
|
||||
export async function expectRecordedPluginNotifications(
|
||||
page: Page,
|
||||
expected: ReadonlyArray<{
|
||||
pluginId: string;
|
||||
title: string;
|
||||
body: string;
|
||||
notificationId?: string;
|
||||
}>,
|
||||
): Promise<void> {
|
||||
await expect
|
||||
.poll(async () => (await readRecordedBrowserNotifications(page)).length)
|
||||
.toBe(expected.length);
|
||||
|
||||
const notifications = await readRecordedBrowserNotifications(page);
|
||||
const includeId = expected.some((item) => item.notificationId !== undefined);
|
||||
expect(
|
||||
notifications.map((entry) =>
|
||||
includeId
|
||||
? {
|
||||
pluginId: entry.data?.pluginId,
|
||||
title: entry.title,
|
||||
body: entry.body,
|
||||
notificationId: entry.data?.notificationId,
|
||||
}
|
||||
: {
|
||||
pluginId: entry.data?.pluginId,
|
||||
title: entry.title,
|
||||
body: entry.body,
|
||||
},
|
||||
),
|
||||
).toEqual(expected);
|
||||
}
|
||||
|
||||
export async function setPluginNotificationSwitch(
|
||||
page: Page,
|
||||
pluginLabel: string,
|
||||
checked: boolean,
|
||||
): Promise<void> {
|
||||
const toggle = page.getByRole("switch", { name: pluginLabel, exact: true });
|
||||
await expect(toggle).toBeVisible();
|
||||
await expect(toggle).toBeEnabled();
|
||||
await expect(toggle).toHaveAttribute("aria-checked", String(!checked));
|
||||
await toggle.click();
|
||||
await expect(toggle).toHaveAttribute("aria-checked", String(checked));
|
||||
}
|
||||
|
||||
export async function expectRecordedAgentNotifications(
|
||||
page: Page,
|
||||
expected: ReadonlyArray<{ agentId: string; reason: string }>,
|
||||
): Promise<void> {
|
||||
await expect
|
||||
.poll(async () => (await readRecordedBrowserNotifications(page)).length)
|
||||
.toBe(expected.length);
|
||||
|
||||
const notifications = await readRecordedBrowserNotifications(page);
|
||||
expect(
|
||||
notifications.map((entry) => ({
|
||||
agentId: entry.data?.agentId,
|
||||
reason: entry.data?.reason,
|
||||
})),
|
||||
).toEqual(expected);
|
||||
}
|
||||
|
||||
export async function openNotificationSettings(page: Page): Promise<void> {
|
||||
await openSettingsSection(page, "notifications");
|
||||
await expect(
|
||||
page.getByRole("switch", { name: "Enable notifications", exact: true }),
|
||||
).toBeVisible();
|
||||
}
|
||||
|
||||
export function notificationSwitch(page: Page, name: NotificationSwitchName) {
|
||||
return page.getByRole("switch", { name, exact: true });
|
||||
}
|
||||
|
||||
export async function expectNotificationSwitchState(
|
||||
page: Page,
|
||||
name: NotificationSwitchName,
|
||||
expected: { checked: boolean; disabled?: boolean },
|
||||
): Promise<void> {
|
||||
const toggle = notificationSwitch(page, name);
|
||||
await expect(toggle).toBeVisible();
|
||||
await expect(toggle).toHaveAttribute("aria-checked", String(expected.checked));
|
||||
if (expected.disabled) {
|
||||
await expect(toggle).toBeDisabled();
|
||||
} else {
|
||||
await expect(toggle).toBeEnabled();
|
||||
}
|
||||
}
|
||||
|
||||
export async function expectDefaultNotificationSettings(page: Page): Promise<void> {
|
||||
await expectNotificationSwitchState(page, "Enable notifications", {
|
||||
checked: true,
|
||||
disabled: false,
|
||||
});
|
||||
await expectNotificationSwitchState(page, "Agent needs permission", {
|
||||
checked: true,
|
||||
disabled: false,
|
||||
});
|
||||
await expectNotificationSwitchState(page, "Agent errored", {
|
||||
checked: true,
|
||||
disabled: false,
|
||||
});
|
||||
await expectNotificationSwitchState(page, "Agent finished", {
|
||||
checked: false,
|
||||
disabled: false,
|
||||
});
|
||||
await expectNotificationSwitchState(page, "Terminal needs input", {
|
||||
checked: true,
|
||||
disabled: false,
|
||||
});
|
||||
await expectNotificationSwitchState(page, "Terminal finished", {
|
||||
checked: false,
|
||||
disabled: false,
|
||||
});
|
||||
await expectNotificationSwitchState(page, "Plugin notifications", {
|
||||
checked: true,
|
||||
disabled: false,
|
||||
});
|
||||
}
|
||||
|
||||
export async function setNotificationSwitch(
|
||||
page: Page,
|
||||
name: NotificationSwitchName,
|
||||
checked: boolean,
|
||||
): Promise<void> {
|
||||
const toggle = notificationSwitch(page, name);
|
||||
await expect(toggle).toBeEnabled();
|
||||
await expect(toggle).toHaveAttribute("aria-checked", String(!checked));
|
||||
await toggle.click();
|
||||
await expect(toggle).toHaveAttribute("aria-checked", String(checked));
|
||||
}
|
||||
|
||||
export async function expectNotificationSubControlsDisabled(
|
||||
page: Page,
|
||||
disabled: boolean,
|
||||
): Promise<void> {
|
||||
const subSwitches: NotificationSwitchName[] = [
|
||||
"Agent needs permission",
|
||||
"Agent errored",
|
||||
"Agent finished",
|
||||
"Terminal needs input",
|
||||
"Terminal finished",
|
||||
"Plugin notifications",
|
||||
];
|
||||
for (const name of subSwitches) {
|
||||
const toggle = notificationSwitch(page, name);
|
||||
if (disabled) {
|
||||
await expect(toggle).toBeDisabled();
|
||||
} else {
|
||||
await expect(toggle).toBeEnabled();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -32,6 +32,12 @@ export interface SeedDaemonClient {
|
||||
config: import("@getpaseo/protocol/messages").MutableDaemonConfigPatch,
|
||||
): Promise<{ config: import("@getpaseo/protocol/messages").MutableDaemonConfig }>;
|
||||
getDaemonConfig(): Promise<{ config: import("@getpaseo/protocol/messages").MutableDaemonConfig }>;
|
||||
installDirectoryPlugin(
|
||||
directoryPath: string,
|
||||
id?: string,
|
||||
): Promise<import("@getpaseo/protocol/messages").PluginListItem>;
|
||||
removePlugin(pluginId: string): Promise<void>;
|
||||
invokePluginRpc(pluginId: string, method: string, input: unknown): Promise<unknown>;
|
||||
connect(): Promise<void>;
|
||||
close(): Promise<void>;
|
||||
addProject(cwd: string): Promise<{
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@getpaseo/app",
|
||||
"version": "0.17.6",
|
||||
"version": "0.18.0",
|
||||
"private": true,
|
||||
"main": "index.ts",
|
||||
"scripts": {
|
||||
|
||||
@@ -24,6 +24,7 @@ describe("materializeAgentProfile", () => {
|
||||
modeId: "plan",
|
||||
thinkingOptionId: "think-hard",
|
||||
options: { web_search: true },
|
||||
systemPrompt: " Focus on UI tokens. ",
|
||||
}),
|
||||
),
|
||||
).toEqual({
|
||||
@@ -32,16 +33,20 @@ describe("materializeAgentProfile", () => {
|
||||
modeId: "plan",
|
||||
thinkingOptionId: "think-hard",
|
||||
options: { web_search: true },
|
||||
systemPrompt: "Focus on UI tokens.",
|
||||
});
|
||||
});
|
||||
|
||||
it("treats omitted and blank fields the same", () => {
|
||||
expect(materializeAgentProfile(profile({ model: " ", modeId: "" }))).toEqual({
|
||||
expect(
|
||||
materializeAgentProfile(profile({ model: " ", modeId: "", systemPrompt: " " })),
|
||||
).toEqual({
|
||||
provider: "claude",
|
||||
modelId: "",
|
||||
modeId: "",
|
||||
thinkingOptionId: "",
|
||||
options: {},
|
||||
systemPrompt: "",
|
||||
});
|
||||
});
|
||||
|
||||
@@ -85,10 +90,14 @@ describe("toAgentConfigApply", () => {
|
||||
).not.toHaveProperty("options");
|
||||
});
|
||||
|
||||
it("never carries a provider, which a running agent cannot change", () => {
|
||||
expect(
|
||||
toAgentConfigApply(materializeAgentProfile(profile({ model: "claude-opus-5" }))),
|
||||
).not.toHaveProperty("provider");
|
||||
it("never carries provider or systemPrompt, which a running agent cannot change", () => {
|
||||
const applied = toAgentConfigApply(
|
||||
materializeAgentProfile(
|
||||
profile({ model: "claude-opus-5", systemPrompt: "Focus on UI tokens." }),
|
||||
),
|
||||
);
|
||||
expect(applied).not.toHaveProperty("provider");
|
||||
expect(applied).not.toHaveProperty("systemPrompt");
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -13,6 +13,8 @@ export interface MaterializedAgentProfile {
|
||||
modeId: string;
|
||||
thinkingOptionId: string;
|
||||
options: Record<string, unknown>;
|
||||
/** Creation-only; empty when unset. Ignored when applying to a running agent. */
|
||||
systemPrompt: string;
|
||||
}
|
||||
|
||||
function trimmed(value: string | undefined): string {
|
||||
@@ -26,6 +28,7 @@ export function materializeAgentProfile(profile: AgentProfile): MaterializedAgen
|
||||
modeId: trimmed(profile.modeId),
|
||||
thinkingOptionId: trimmed(profile.thinkingOptionId),
|
||||
options: profile.options ?? {},
|
||||
systemPrompt: trimmed(profile.systemPrompt),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -44,8 +47,8 @@ export function reconcileMaterializedProfileMode(
|
||||
|
||||
/**
|
||||
* The payload for a running agent. Omitted fields are left alone by the daemon,
|
||||
* so a profile that names no mode does not reset the agent's mode. Provider is
|
||||
* absent because a running agent cannot change the process it is.
|
||||
* so a profile that names no mode does not reset the agent's mode. Provider and
|
||||
* systemPrompt are absent because a running agent cannot change either.
|
||||
*/
|
||||
export function toAgentConfigApply(profile: MaterializedAgentProfile): AgentConfigApply {
|
||||
return {
|
||||
|
||||
@@ -170,19 +170,46 @@ describe("openAgentProfileForm", () => {
|
||||
const model = openWithCatalog({ mode: "create" });
|
||||
model.setName(" Cheap grunt ");
|
||||
model.setProvider("codex", { label: "Codex" });
|
||||
model.setSystemPrompt(" ");
|
||||
model.setNotes(" ");
|
||||
|
||||
// Codex declares no thinking options, so that key is genuinely absent —
|
||||
// model and mode are seeded, never left for the host to decide.
|
||||
// `options` and `systemPrompt` stay present when empty so the daemon can
|
||||
// distinguish an intentional clear from an older app that predates them.
|
||||
expect(model.getState().submitValue).toEqual({
|
||||
name: "Cheap grunt",
|
||||
provider: "codex",
|
||||
model: "gpt-5.2-codex",
|
||||
modeId: "read-only",
|
||||
options: {},
|
||||
systemPrompt: "",
|
||||
});
|
||||
});
|
||||
|
||||
it("seeds, tracks dirty state, preserves across provider switches, and submits systemPrompt", () => {
|
||||
const model = openWithCatalog({
|
||||
mode: "edit",
|
||||
profile: {
|
||||
id: "p1",
|
||||
name: "UI work",
|
||||
provider: "claude",
|
||||
model: "claude-opus-5",
|
||||
systemPrompt: "Focus on layout.",
|
||||
},
|
||||
});
|
||||
expect(model.getState().systemPrompt).toBe("Focus on layout.");
|
||||
expect(model.getState().isDirty).toBe(false);
|
||||
|
||||
model.setSystemPrompt(" Focus on layout and tokens. ");
|
||||
expect(model.getState().isDirty).toBe(true);
|
||||
expect(model.getState().submitValue?.systemPrompt).toBe("Focus on layout and tokens.");
|
||||
|
||||
model.setProvider("codex", { label: "Codex" });
|
||||
expect(model.getState().systemPrompt).toBe(" Focus on layout and tokens. ");
|
||||
expect(model.getState().submitValue?.systemPrompt).toBe("Focus on layout and tokens.");
|
||||
});
|
||||
|
||||
it("seeds edit mode from the stored profile before the catalog lands", () => {
|
||||
const model = openAgentProfileForm({
|
||||
mode: "edit",
|
||||
|
||||
@@ -98,6 +98,7 @@ export interface AgentProfileFormState {
|
||||
name: string;
|
||||
icon: string;
|
||||
color: string;
|
||||
systemPrompt: string;
|
||||
notes: string;
|
||||
provider: string;
|
||||
modelId: string;
|
||||
@@ -157,6 +158,7 @@ export interface AgentProfileFormModel {
|
||||
applyControlsUnavailable: (requestKey: string) => void;
|
||||
setName: (value: string) => void;
|
||||
setAppearance: (value: { icon: string; color: string }) => void;
|
||||
setSystemPrompt: (value: string) => void;
|
||||
setNotes: (value: string) => void;
|
||||
setProvider: (providerId: string, display: AgentProfileFormDisplay) => void;
|
||||
setProviderModel: (
|
||||
@@ -471,6 +473,7 @@ function formDraftFingerprint(state: AgentProfileFormState): string {
|
||||
state.modelId,
|
||||
state.modeId,
|
||||
state.thinkingOptionId,
|
||||
state.systemPrompt.trim(),
|
||||
state.notes.trim(),
|
||||
stableOptionsKey(ownOptionsOf(state)),
|
||||
]);
|
||||
@@ -478,6 +481,7 @@ function formDraftFingerprint(state: AgentProfileFormState): string {
|
||||
|
||||
function buildSubmitValue(state: AgentProfileFormState): AgentProfileValue | null {
|
||||
const name = state.name.trim();
|
||||
const systemPrompt = state.systemPrompt.trim();
|
||||
const notes = state.notes.trim();
|
||||
if (!name || !state.provider) {
|
||||
return null;
|
||||
@@ -493,6 +497,10 @@ function buildSubmitValue(state: AgentProfileFormState): AgentProfileValue | nul
|
||||
// Always sent, empty included: the daemon reads a write without `options` as one from an
|
||||
// app that predates them and keeps the profile's stored options.
|
||||
options: ownOptionsOf(state),
|
||||
// COMPAT(agentProfileSystemPrompt): added in v0.17.6, remove after 2027-06-01.
|
||||
// Always sent, empty included: the daemon treats an omitted `systemPrompt` as a write from
|
||||
// an older app and preserves the stored prompt; `""` explicitly clears it.
|
||||
systemPrompt,
|
||||
...(notes ? { notes } : {}),
|
||||
};
|
||||
}
|
||||
@@ -529,6 +537,7 @@ function buildInitialState(snapshot: AgentProfileFormSnapshot): AgentProfileForm
|
||||
name,
|
||||
icon: profile.icon ?? "",
|
||||
color: profile.color ?? "",
|
||||
systemPrompt: profile.systemPrompt ?? "",
|
||||
notes: profile.notes ?? "",
|
||||
provider,
|
||||
modelId,
|
||||
@@ -854,6 +863,8 @@ export function openAgentProfileForm(snapshot: AgentProfileFormSnapshot): AgentP
|
||||
publish((current) => ({ ...current, icon: value.icon, color: value.color }), {
|
||||
userEdit: true,
|
||||
}),
|
||||
setSystemPrompt: (value) =>
|
||||
publish((current) => ({ ...current, systemPrompt: value }), { userEdit: true }),
|
||||
setNotes: (value) => publish((current) => ({ ...current, notes: value }), { userEdit: true }),
|
||||
setProvider: (providerId, display) =>
|
||||
publish(
|
||||
|
||||
@@ -63,6 +63,25 @@ describe("buildAgentProfileRosterSummary", () => {
|
||||
expect(summary.runtimeDetails).toEqual(["OpenCode", "Build", "High", "1 option"]);
|
||||
});
|
||||
|
||||
it("includes a system prompt tag when configured", () => {
|
||||
const profile: AgentProfile = {
|
||||
id: "p3",
|
||||
name: "UI specialist",
|
||||
provider: "opencode",
|
||||
model: "openrouter/moonshotai/kimi-k3.1-pro",
|
||||
systemPrompt: "Focus on layout and tokens.",
|
||||
};
|
||||
|
||||
const summary = buildAgentProfileRosterSummary({
|
||||
profile,
|
||||
entries,
|
||||
formatFeatureCount,
|
||||
systemPromptLabel: "System prompt",
|
||||
});
|
||||
|
||||
expect(summary.runtimeDetails).toEqual(["OpenCode", "System prompt"]);
|
||||
});
|
||||
|
||||
it("falls back to stored provider id when catalog is unavailable", () => {
|
||||
const profile: AgentProfile = {
|
||||
id: "p2",
|
||||
|
||||
@@ -40,6 +40,7 @@ export function buildAgentProfileRosterSummary(input: {
|
||||
profile: AgentProfile;
|
||||
entries: readonly ProviderSnapshotEntry[] | undefined;
|
||||
formatFeatureCount: (count: number) => string;
|
||||
systemPromptLabel?: string;
|
||||
}): AgentProfileRosterSummary {
|
||||
const allTags = buildAgentProfileTags(input);
|
||||
const providerLabel =
|
||||
@@ -63,6 +64,26 @@ function findEntry(
|
||||
return entries.find((entry) => entry.provider === provider) ?? null;
|
||||
}
|
||||
|
||||
function resolveModelTag(
|
||||
profile: AgentProfile,
|
||||
entry: ProviderSnapshotEntry | null,
|
||||
): AgentProfileTag | null {
|
||||
const modelId = profile.model?.trim();
|
||||
if (!modelId) return null;
|
||||
const model = entry?.models?.find((candidate) => candidate.id === modelId);
|
||||
return { id: "model", label: model?.label ?? modelId };
|
||||
}
|
||||
|
||||
function resolveModeTag(
|
||||
profile: AgentProfile,
|
||||
entry: ProviderSnapshotEntry | null,
|
||||
): AgentProfileTag | null {
|
||||
const modeId = profile.modeId?.trim();
|
||||
if (!modeId) return null;
|
||||
const mode = entry?.modes?.find((candidate) => candidate.id === modeId);
|
||||
return { id: "mode", label: mode ? formatAgentModeLabel(mode) : modeId };
|
||||
}
|
||||
|
||||
/**
|
||||
* The one-line résumé of a profile in the settings list. Every label falls back
|
||||
* to the stored id: a row must stay readable on a host whose provider catalog
|
||||
@@ -72,24 +93,16 @@ export function buildAgentProfileTags(input: {
|
||||
profile: AgentProfile;
|
||||
entries: readonly ProviderSnapshotEntry[] | undefined;
|
||||
formatFeatureCount: (count: number) => string;
|
||||
systemPromptLabel?: string;
|
||||
}): AgentProfileTag[] {
|
||||
const entries = input.entries ?? [];
|
||||
const entry = findEntry(entries, input.profile.provider);
|
||||
const entry = findEntry(input.entries ?? [], input.profile.provider);
|
||||
const tags: AgentProfileTag[] = [
|
||||
{ id: "provider", label: entry?.label ?? input.profile.provider },
|
||||
];
|
||||
|
||||
const modelId = input.profile.model?.trim();
|
||||
if (modelId) {
|
||||
const model = entry?.models?.find((candidate) => candidate.id === modelId);
|
||||
tags.push({ id: "model", label: model?.label ?? modelId });
|
||||
}
|
||||
|
||||
const modeId = input.profile.modeId?.trim();
|
||||
if (modeId) {
|
||||
const mode = entry?.modes?.find((candidate) => candidate.id === modeId);
|
||||
tags.push({ id: "mode", label: mode ? formatAgentModeLabel(mode) : modeId });
|
||||
}
|
||||
const modelTag = resolveModelTag(input.profile, entry);
|
||||
if (modelTag) tags.push(modelTag);
|
||||
const modeTag = resolveModeTag(input.profile, entry);
|
||||
if (modeTag) tags.push(modeTag);
|
||||
|
||||
const thinkingOptionId = input.profile.thinkingOptionId?.trim();
|
||||
if (thinkingOptionId) {
|
||||
@@ -101,5 +114,9 @@ export function buildAgentProfileTags(input: {
|
||||
tags.push({ id: "features", label: input.formatFeatureCount(featureCount) });
|
||||
}
|
||||
|
||||
if (input.profile.systemPrompt?.trim() && input.systemPromptLabel) {
|
||||
tags.push({ id: "systemPrompt", label: input.systemPromptLabel });
|
||||
}
|
||||
|
||||
return tags;
|
||||
}
|
||||
|
||||
@@ -92,6 +92,8 @@ export function useAgentProfilePicker(
|
||||
[t],
|
||||
);
|
||||
|
||||
const systemPromptLabel = t("settings.host.agentProfiles.systemPromptLabel");
|
||||
|
||||
const rows = useMemo<AgentProfilePickerRow[]>(
|
||||
() =>
|
||||
applicableProfiles.map((profile) => ({
|
||||
@@ -101,11 +103,16 @@ export function useAgentProfilePicker(
|
||||
icon: profile.icon ?? "",
|
||||
color: profile.color ?? "",
|
||||
name: profile.name,
|
||||
summary: buildAgentProfileTags({ profile, entries, formatFeatureCount })
|
||||
summary: buildAgentProfileTags({
|
||||
profile,
|
||||
entries,
|
||||
formatFeatureCount,
|
||||
systemPromptLabel,
|
||||
})
|
||||
.map((tag) => tag.label)
|
||||
.join(" · "),
|
||||
})),
|
||||
[applicableProfiles, entries, formatFeatureCount],
|
||||
[applicableProfiles, entries, formatFeatureCount, systemPromptLabel],
|
||||
);
|
||||
|
||||
const persistSelection = useCallback(
|
||||
|
||||
@@ -246,6 +246,25 @@ function AgentProfileAdvancedFields({
|
||||
onSegmentChange={onThinkingSegmentChange}
|
||||
/>
|
||||
|
||||
<Field
|
||||
label={t("settings.host.agentProfiles.systemPromptLabel")}
|
||||
hint={t("settings.host.agentProfiles.systemPromptHint")}
|
||||
testID="agent-profile-system-prompt-field"
|
||||
>
|
||||
<FormTextInput
|
||||
initialValue={state.systemPrompt}
|
||||
onChangeText={model.setSystemPrompt}
|
||||
placeholder={t("settings.host.agentProfiles.systemPromptPlaceholder")}
|
||||
multiline
|
||||
numberOfLines={3}
|
||||
style={styles.multilineInput}
|
||||
editable={!state.isSubmitting}
|
||||
size={controlSize}
|
||||
accessibilityLabel={t("settings.host.agentProfiles.systemPromptLabel")}
|
||||
testID="agent-profile-system-prompt-input"
|
||||
/>
|
||||
</Field>
|
||||
|
||||
<Field
|
||||
label={t("settings.host.agentProfiles.notesLabel")}
|
||||
hint={t("settings.host.agentProfiles.notesHint")}
|
||||
@@ -257,7 +276,7 @@ function AgentProfileAdvancedFields({
|
||||
placeholder={t("settings.host.agentProfiles.notesPlaceholder")}
|
||||
multiline
|
||||
numberOfLines={3}
|
||||
style={styles.notesInput}
|
||||
style={styles.multilineInput}
|
||||
editable={!state.isSubmitting}
|
||||
size={controlSize}
|
||||
accessibilityLabel={t("settings.host.agentProfiles.notesLabel")}
|
||||
@@ -435,7 +454,10 @@ export function AgentProfileFormFields({
|
||||
: t("settings.host.agentProfiles.featureCount", { count: state.controls.length }),
|
||||
);
|
||||
}
|
||||
if (!state.notes.trim() && hasRuntimeDefaults) {
|
||||
if (state.systemPrompt.trim()) {
|
||||
parts.push(t("settings.host.agentProfiles.systemPromptLabel"));
|
||||
}
|
||||
if (!state.notes.trim() && !state.systemPrompt.trim() && hasRuntimeDefaults) {
|
||||
parts.push(t("settings.host.agentProfiles.addRoutingNoteShort"));
|
||||
}
|
||||
return parts.join(" · ");
|
||||
@@ -444,13 +466,12 @@ export function AgentProfileFormFields({
|
||||
state.controls.length,
|
||||
state.modeDisplay?.label,
|
||||
state.notes,
|
||||
state.systemPrompt,
|
||||
state.thinkingDisplay?.label,
|
||||
t,
|
||||
]);
|
||||
|
||||
const collapsibleLabel = hasRuntimeDefaults
|
||||
? t("settings.host.agentProfiles.customizeSettings")
|
||||
: t("settings.host.agentProfiles.addRoutingNoteShort");
|
||||
const collapsibleLabel = t("settings.host.agentProfiles.customizeSettings");
|
||||
|
||||
const advancedFields = (
|
||||
<AgentProfileAdvancedFields
|
||||
@@ -556,7 +577,7 @@ const styles = StyleSheet.create((theme) => ({
|
||||
featureCardPending: {
|
||||
opacity: theme.opacity[50],
|
||||
},
|
||||
notesInput: {
|
||||
multilineInput: {
|
||||
minHeight: theme.spacing[20],
|
||||
textAlignVertical: "top",
|
||||
},
|
||||
|
||||
@@ -349,9 +349,17 @@ export function AgentProfileRow({
|
||||
[t],
|
||||
);
|
||||
|
||||
const systemPromptLabel = t("settings.host.agentProfiles.systemPromptLabel");
|
||||
|
||||
const rosterSummary = useMemo(
|
||||
() => buildAgentProfileRosterSummary({ profile, entries, formatFeatureCount }),
|
||||
[entries, formatFeatureCount, profile],
|
||||
() =>
|
||||
buildAgentProfileRosterSummary({
|
||||
profile,
|
||||
entries,
|
||||
formatFeatureCount,
|
||||
systemPromptLabel,
|
||||
}),
|
||||
[entries, formatFeatureCount, profile, systemPromptLabel],
|
||||
);
|
||||
const fullSummary = useMemo(
|
||||
() => rosterSummary.allTags.map((tag) => tag.label).join(" · "),
|
||||
|
||||
@@ -72,16 +72,23 @@ function matchesProfileQuery(
|
||||
normalizedQuery: string,
|
||||
entries: readonly ProviderSnapshotEntry[] | undefined,
|
||||
formatFeatureCount: (count: number) => string,
|
||||
systemPromptLabel: string,
|
||||
): boolean {
|
||||
if (
|
||||
profile.name.toLowerCase().includes(normalizedQuery) ||
|
||||
profile.systemPrompt?.toLowerCase().includes(normalizedQuery) ||
|
||||
profile.notes?.toLowerCase().includes(normalizedQuery) ||
|
||||
profile.model?.toLowerCase().includes(normalizedQuery) ||
|
||||
profile.provider.toLowerCase().includes(normalizedQuery)
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
const tags = buildAgentProfileTags({ profile, entries, formatFeatureCount });
|
||||
const tags = buildAgentProfileTags({
|
||||
profile,
|
||||
entries,
|
||||
formatFeatureCount,
|
||||
systemPromptLabel,
|
||||
});
|
||||
return tags.some((tag) => tag.label.toLowerCase().includes(normalizedQuery));
|
||||
}
|
||||
|
||||
@@ -857,6 +864,7 @@ export function AgentProfilesPage({
|
||||
[t],
|
||||
);
|
||||
|
||||
const systemPromptLabel = t("settings.host.agentProfiles.systemPromptLabel");
|
||||
const normalizedQuery = searchQuery.trim().toLowerCase();
|
||||
const isFiltering = normalizedQuery.length > 0;
|
||||
|
||||
@@ -868,9 +876,9 @@ export function AgentProfilesPage({
|
||||
return profiles;
|
||||
}
|
||||
return profiles.filter((profile) =>
|
||||
matchesProfileQuery(profile, normalizedQuery, entries, formatFeatureCount),
|
||||
matchesProfileQuery(profile, normalizedQuery, entries, formatFeatureCount, systemPromptLabel),
|
||||
);
|
||||
}, [entries, formatFeatureCount, normalizedQuery, profiles]);
|
||||
}, [entries, formatFeatureCount, normalizedQuery, profiles, systemPromptLabel]);
|
||||
|
||||
const totalCount = profiles?.length ?? 0;
|
||||
const selectedProfileId = activeProfile?.id ?? null;
|
||||
@@ -940,10 +948,12 @@ export function AgentProfilesPage({
|
||||
<View style={styles.rosterPane}>
|
||||
<PageLayout
|
||||
title={t("settings.host.agentProfiles.sectionTitle")}
|
||||
description={t("settings.host.agentProfiles.sectionDescription")}
|
||||
onBack={onBack}
|
||||
actions={headerActions}
|
||||
width="wide"
|
||||
titleTestID="settings-detail-header-title"
|
||||
descriptionTestID="agent-profiles-description"
|
||||
testID="settings-detail-scroll-body"
|
||||
>
|
||||
<RosterBody
|
||||
|
||||
@@ -24,6 +24,7 @@ export interface AssistantFileLinkResolverConfig {
|
||||
workspaceRoot?: string;
|
||||
relativePathBase?: string;
|
||||
onOpenWorkspaceFile?: (target: InlinePathTarget, disposition: OpenFileDisposition) => void;
|
||||
onOpenBrowserUrl?: (url: string) => void;
|
||||
toast?: ToastApi | null;
|
||||
}
|
||||
|
||||
@@ -57,6 +58,7 @@ export function AssistantFileLinkResolverProvider({
|
||||
workspaceRoot,
|
||||
relativePathBase,
|
||||
onOpenWorkspaceFile,
|
||||
onOpenBrowserUrl,
|
||||
toast,
|
||||
children,
|
||||
}: AssistantFileLinkResolverProviderProps) {
|
||||
@@ -66,6 +68,7 @@ export function AssistantFileLinkResolverProvider({
|
||||
workspaceRoot,
|
||||
relativePathBase,
|
||||
onOpenWorkspaceFile,
|
||||
onOpenBrowserUrl,
|
||||
toast,
|
||||
});
|
||||
configRef.current = {
|
||||
@@ -74,6 +77,7 @@ export function AssistantFileLinkResolverProvider({
|
||||
workspaceRoot,
|
||||
relativePathBase,
|
||||
onOpenWorkspaceFile,
|
||||
onOpenBrowserUrl,
|
||||
toast,
|
||||
};
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@ import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useStableEvent } from "@/hooks/use-stable-event";
|
||||
import type { OpenFileDisposition } from "@/workspace/file-open";
|
||||
import { shouldRouteWorkspaceUrlToProxiedBrowser } from "@/desktop/browser/proxy";
|
||||
import { openExternalUrl } from "@/utils/open-external-url";
|
||||
import { formatFileLinkTooltipPath } from "./tooltip-path";
|
||||
import type { InlinePathTarget } from "./parse";
|
||||
@@ -335,6 +336,14 @@ async function dispatchExternalUrl(input: {
|
||||
) {
|
||||
return;
|
||||
}
|
||||
if (
|
||||
current.onOpenBrowserUrl &&
|
||||
current.serverId &&
|
||||
shouldRouteWorkspaceUrlToProxiedBrowser({ serverId: current.serverId, url: input.url })
|
||||
) {
|
||||
current.onOpenBrowserUrl(input.url);
|
||||
return;
|
||||
}
|
||||
await openExternalUrl(input.url);
|
||||
}
|
||||
|
||||
|
||||
@@ -61,6 +61,8 @@ export function appearanceStyleBoundaryKey(theme: Theme): string {
|
||||
theme.colors.syntax.meta,
|
||||
theme.colors.syntax.heading,
|
||||
theme.colors.syntax.link,
|
||||
theme.colors.syntax.diffAddition,
|
||||
theme.colors.syntax.diffDeletion,
|
||||
].join("\u0000");
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { tokenizeToLines } from "@/utils/highlight-cache";
|
||||
import { fenceLanguageToExtension } from "./highlighted-code-block";
|
||||
|
||||
describe("fenceLanguageToExtension", () => {
|
||||
it.each([
|
||||
["shell", "sh"],
|
||||
["ruby", "rb"],
|
||||
["kotlin", "kt"],
|
||||
["powershell", "ps1"],
|
||||
["pwsh", "ps1"],
|
||||
["protobuf", "proto"],
|
||||
["latex", "tex"],
|
||||
["stex", "tex"],
|
||||
["diff", "diff"],
|
||||
["patch", "patch"],
|
||||
["sql", "sql"],
|
||||
["lua", "lua"],
|
||||
["proto", "proto"],
|
||||
["groovy", "groovy"],
|
||||
["gradle", "gradle"],
|
||||
["scala", "scala"],
|
||||
["cmake", "cmake"],
|
||||
["properties", "properties"],
|
||||
["ini", "ini"],
|
||||
["conf", "conf"],
|
||||
["r", "r"],
|
||||
["perl", "pl"],
|
||||
["toml", "toml"],
|
||||
])("maps fence info %s to %s", (info, expected) => {
|
||||
expect(fenceLanguageToExtension(info)).toBe(expected);
|
||||
});
|
||||
|
||||
it("produces syntax tokens for every mapped fence alias", () => {
|
||||
const samples: Array<[string, string]> = [
|
||||
["shell", 'export FOO="bar"'],
|
||||
["ruby", 'def hi\n "ok"\nend'],
|
||||
["kotlin", 'val x: String = "ok"'],
|
||||
["powershell", 'function Get-X { "ok" }'],
|
||||
["pwsh", '$x = "ok"'],
|
||||
["protobuf", 'syntax = "proto3";'],
|
||||
["latex", "\\documentclass{article}"],
|
||||
["perl", 'my $x = "ok";'],
|
||||
["sql", "SELECT 1;"],
|
||||
["lua", "local x = 1"],
|
||||
["gradle", 'id "java"'],
|
||||
["scala", "val x = 1"],
|
||||
["cmake", "project(Paseo)"],
|
||||
["ini", "[section]\nkey = value"],
|
||||
["r", "x <- function(a) a"],
|
||||
["toml", '[server]\nhost = "localhost"'],
|
||||
["diff", "+added"],
|
||||
["patch", "-removed"],
|
||||
];
|
||||
|
||||
for (const [info, code] of samples) {
|
||||
const ext = fenceLanguageToExtension(info);
|
||||
const lines = tokenizeToLines(code, ext);
|
||||
expect(lines, info).not.toBeNull();
|
||||
expect(
|
||||
lines?.flat().some((token) => token.style !== null),
|
||||
info,
|
||||
).toBe(true);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -39,9 +39,18 @@ const LANGUAGE_ALIASES: Record<string, string> = {
|
||||
markdown: "md",
|
||||
elixir: "ex",
|
||||
terraform: "tf",
|
||||
shell: "sh",
|
||||
ruby: "rb",
|
||||
kotlin: "kt",
|
||||
powershell: "ps1",
|
||||
pwsh: "ps1",
|
||||
protobuf: "proto",
|
||||
perl: "pl",
|
||||
latex: "tex",
|
||||
stex: "tex",
|
||||
};
|
||||
|
||||
function fenceLanguageToExtension(info: string | null | undefined): string | null {
|
||||
export function fenceLanguageToExtension(info: string | null | undefined): string | null {
|
||||
if (!info) return null;
|
||||
const first = info.trim().split(/\s+/)[0]?.toLowerCase();
|
||||
if (!first) return null;
|
||||
|
||||
@@ -20,10 +20,13 @@ const PageScrollView =
|
||||
|
||||
interface PageLayoutProps {
|
||||
title?: string;
|
||||
/** Short page description shown below the title on desktop and above the body on compact. */
|
||||
description?: string;
|
||||
/** Compact back button. Defaults to navigating back. */
|
||||
onBack?: () => void;
|
||||
testID?: string;
|
||||
titleTestID?: string;
|
||||
descriptionTestID?: string;
|
||||
/** Controls for the whole page: right of the title on desktop, in the back header on compact. */
|
||||
actions?: ReactNode;
|
||||
/** `wide` for pages that lay content out in a grid, such as a gallery. Defaults to a reading column. */
|
||||
@@ -38,9 +41,11 @@ interface PageLayoutProps {
|
||||
*/
|
||||
export function PageLayout({
|
||||
title,
|
||||
description,
|
||||
onBack,
|
||||
testID,
|
||||
titleTestID,
|
||||
descriptionTestID,
|
||||
actions,
|
||||
width = "default",
|
||||
children,
|
||||
@@ -49,6 +54,24 @@ export function PageLayout({
|
||||
const insets = useSafeAreaInsets();
|
||||
const scrollContentStyle = useMemo(() => ({ paddingBottom: insets.bottom }), [insets.bottom]);
|
||||
const showTitle = !isCompact && title !== undefined;
|
||||
let pageHeader: ReactNode = null;
|
||||
if (showTitle) {
|
||||
pageHeader = (
|
||||
<PageTitle
|
||||
title={title}
|
||||
description={description}
|
||||
actions={actions}
|
||||
testID={titleTestID}
|
||||
descriptionTestID={descriptionTestID}
|
||||
/>
|
||||
);
|
||||
} else if (description) {
|
||||
pageHeader = (
|
||||
<Text style={styles.compactDescription} testID={descriptionTestID}>
|
||||
{description}
|
||||
</Text>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<View style={styles.container}>
|
||||
@@ -65,7 +88,7 @@ export function PageLayout({
|
||||
testID={testID}
|
||||
>
|
||||
<View style={width === "wide" ? styles.contentWide : styles.content}>
|
||||
{showTitle ? <PageTitle title={title} actions={actions} testID={titleTestID} /> : null}
|
||||
{pageHeader}
|
||||
{children}
|
||||
</View>
|
||||
</PageScrollView>
|
||||
@@ -87,12 +110,15 @@ interface PageTitleProps {
|
||||
/** Drawn before the title, such as the icon of the thing the page is about. */
|
||||
icon?: ReactNode;
|
||||
title?: string;
|
||||
/** Short page description rendered directly below the title on the same leading rail. */
|
||||
description?: string;
|
||||
/** A control that belongs to the title, drawn right after it. */
|
||||
adornment?: ReactNode;
|
||||
/** Controls for the whole page, drawn at the trailing edge. */
|
||||
actions?: ReactNode;
|
||||
testID?: string;
|
||||
titleTestID?: string;
|
||||
descriptionTestID?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -103,40 +129,49 @@ export function PageTitle({
|
||||
parent,
|
||||
icon,
|
||||
title,
|
||||
description,
|
||||
adornment,
|
||||
actions,
|
||||
testID,
|
||||
titleTestID = "page-title",
|
||||
descriptionTestID,
|
||||
}: PageTitleProps) {
|
||||
return (
|
||||
<View style={styles.titleRow} testID={testID}>
|
||||
<View style={styles.titleParts}>
|
||||
{parent ? (
|
||||
<PressHighlight
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={parent.accessibilityLabel}
|
||||
onPress={parent.onPress}
|
||||
testID={parent.testID}
|
||||
>
|
||||
{({ hovered }: PressableStateCallbackType & { hovered?: boolean }) => (
|
||||
<Text style={[styles.title, styles.parent, hovered && styles.parentHovered]}>
|
||||
{parent.label}
|
||||
</Text>
|
||||
)}
|
||||
</PressHighlight>
|
||||
) : null}
|
||||
{parent && title !== undefined ? (
|
||||
<ThemedChevronRight size={ICON_SIZE.lg} uniProps={separatorColor} />
|
||||
) : null}
|
||||
{icon}
|
||||
{title !== undefined ? (
|
||||
<Text style={[styles.title, styles.titleLeaf]} numberOfLines={1} testID={titleTestID}>
|
||||
{title}
|
||||
</Text>
|
||||
) : null}
|
||||
{adornment}
|
||||
<View style={styles.titleBlock} testID={testID}>
|
||||
<View style={styles.titleRow}>
|
||||
<View style={styles.titleParts}>
|
||||
{parent ? (
|
||||
<PressHighlight
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={parent.accessibilityLabel}
|
||||
onPress={parent.onPress}
|
||||
testID={parent.testID}
|
||||
>
|
||||
{({ hovered }: PressableStateCallbackType & { hovered?: boolean }) => (
|
||||
<Text style={[styles.title, styles.parent, hovered && styles.parentHovered]}>
|
||||
{parent.label}
|
||||
</Text>
|
||||
)}
|
||||
</PressHighlight>
|
||||
) : null}
|
||||
{parent && title !== undefined ? (
|
||||
<ThemedChevronRight size={ICON_SIZE.lg} uniProps={separatorColor} />
|
||||
) : null}
|
||||
{icon}
|
||||
{title !== undefined ? (
|
||||
<Text style={[styles.title, styles.titleLeaf]} numberOfLines={1} testID={titleTestID}>
|
||||
{title}
|
||||
</Text>
|
||||
) : null}
|
||||
{adornment}
|
||||
</View>
|
||||
{actions}
|
||||
</View>
|
||||
{actions}
|
||||
{description ? (
|
||||
<Text style={styles.description} testID={descriptionTestID}>
|
||||
{description}
|
||||
</Text>
|
||||
) : null}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -166,12 +201,27 @@ const styles = StyleSheet.create((theme) => ({
|
||||
maxWidth: 1080,
|
||||
alignSelf: "center",
|
||||
},
|
||||
titleBlock: {
|
||||
marginBottom: theme.spacing[6],
|
||||
},
|
||||
titleRow: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
justifyContent: "space-between",
|
||||
gap: theme.spacing[4],
|
||||
marginBottom: theme.spacing[6],
|
||||
},
|
||||
description: {
|
||||
marginLeft: theme.spacing[1],
|
||||
marginTop: theme.spacing[1.5],
|
||||
color: theme.colors.foregroundMuted,
|
||||
fontSize: theme.fontSize.sm,
|
||||
lineHeight: Math.round(theme.fontSize.sm * 1.45),
|
||||
},
|
||||
compactDescription: {
|
||||
marginBottom: theme.spacing[4],
|
||||
color: theme.colors.foregroundMuted,
|
||||
fontSize: theme.fontSize.sm,
|
||||
lineHeight: Math.round(theme.fontSize.sm * 1.45),
|
||||
},
|
||||
titleParts: {
|
||||
// Line up with the section titles, which sit inset from their cards.
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
import { DEFAULT_NOTIFICATION_PREFERENCES } from "@getpaseo/protocol/notification-preferences";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
collectNotificationPluginIds,
|
||||
collectNotificationPlugins,
|
||||
hasConnectedHostMissingPushPreferences,
|
||||
setNotificationEventEnabled,
|
||||
setNotificationPluginMuted,
|
||||
} from "./notifications-model";
|
||||
|
||||
describe("notifications settings model", () => {
|
||||
it("unions installed plugin IDs and muted plugin IDs in sorted unique order", () => {
|
||||
const installed = [{ id: "zeta-plugin" }, { id: "alpha-plugin" }, { id: "zeta-plugin" }];
|
||||
const muted = ["beta-removed-plugin", "alpha-plugin"];
|
||||
|
||||
expect(collectNotificationPluginIds(installed, muted)).toEqual([
|
||||
"alpha-plugin",
|
||||
"beta-removed-plugin",
|
||||
"zeta-plugin",
|
||||
]);
|
||||
});
|
||||
|
||||
it("merges server-only configured plugins and display names with client-bundle and muted plugin IDs", () => {
|
||||
const configuredPlugins = [
|
||||
{ id: "server-pipeline", name: "Server Pipeline" },
|
||||
{ id: "shared-plugin", name: "Shared Plugin" },
|
||||
{ id: "headless-id-only" },
|
||||
];
|
||||
const installedPlugins = [{ id: "shared-plugin" }, { id: "client-only-plugin" }];
|
||||
const mutedPluginIds = ["removed-muted-plugin", "server-pipeline"];
|
||||
|
||||
expect(
|
||||
collectNotificationPlugins({
|
||||
configuredPlugins,
|
||||
installedPlugins,
|
||||
mutedPluginIds,
|
||||
}),
|
||||
).toEqual([
|
||||
{ id: "client-only-plugin", label: "client-only-plugin" },
|
||||
{ id: "headless-id-only", label: "headless-id-only" },
|
||||
{ id: "removed-muted-plugin", label: "removed-muted-plugin" },
|
||||
{ id: "server-pipeline", label: "Server Pipeline" },
|
||||
{ id: "shared-plugin", label: "Shared Plugin" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("mutes and unmutes individual plugins while keeping muted IDs normalized", () => {
|
||||
const mutedOnce = setNotificationPluginMuted(
|
||||
DEFAULT_NOTIFICATION_PREFERENCES,
|
||||
"ci-plugin",
|
||||
true,
|
||||
);
|
||||
expect(mutedOnce.plugins.muted).toEqual(["ci-plugin"]);
|
||||
|
||||
const mutedTwice = setNotificationPluginMuted(mutedOnce, "alerts-plugin", true);
|
||||
expect(mutedTwice.plugins.muted).toEqual(["alerts-plugin", "ci-plugin"]);
|
||||
|
||||
const unmuted = setNotificationPluginMuted(mutedTwice, "ci-plugin", false);
|
||||
expect(unmuted.plugins.muted).toEqual(["alerts-plugin"]);
|
||||
});
|
||||
|
||||
it("updates individual built-in event switches without mutating other preferences", () => {
|
||||
const next = setNotificationEventEnabled(
|
||||
DEFAULT_NOTIFICATION_PREFERENCES,
|
||||
"agentFinished",
|
||||
true,
|
||||
);
|
||||
expect(next.events.agentFinished).toBe(true);
|
||||
expect(next.events.agentPermission).toBe(true);
|
||||
expect(next.events.agentError).toBe(true);
|
||||
expect(DEFAULT_NOTIFICATION_PREFERENCES.events.agentFinished).toBe(false);
|
||||
});
|
||||
|
||||
it("detects when any connected host with serverInfo lacks pushNotificationPreferences", () => {
|
||||
const hosts = [{ serverId: "srv-new" }, { serverId: "srv-old" }];
|
||||
|
||||
expect(
|
||||
hasConnectedHostMissingPushPreferences(hosts, {
|
||||
"srv-new": {
|
||||
serverInfo: {
|
||||
serverId: "srv-new",
|
||||
hostname: "new-host",
|
||||
version: "0.18.0",
|
||||
machineKind: null,
|
||||
capabilities: undefined,
|
||||
features: { pushNotificationPreferences: true },
|
||||
},
|
||||
},
|
||||
"srv-old": {
|
||||
serverInfo: {
|
||||
serverId: "srv-old",
|
||||
hostname: "old-host",
|
||||
version: "0.17.0",
|
||||
machineKind: null,
|
||||
capabilities: undefined,
|
||||
features: {},
|
||||
},
|
||||
},
|
||||
}),
|
||||
).toBe(true);
|
||||
|
||||
expect(
|
||||
hasConnectedHostMissingPushPreferences([{ serverId: "srv-new" }], {
|
||||
"srv-new": {
|
||||
serverInfo: {
|
||||
serverId: "srv-new",
|
||||
hostname: "new-host",
|
||||
version: "0.18.0",
|
||||
machineKind: null,
|
||||
capabilities: undefined,
|
||||
features: { pushNotificationPreferences: true },
|
||||
},
|
||||
},
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,104 @@
|
||||
import {
|
||||
normalizeNotificationPreferences,
|
||||
type NotificationPreferences,
|
||||
} from "@getpaseo/protocol/notification-preferences";
|
||||
import type { HostFeatureSessionState } from "@/runtime/host-features";
|
||||
|
||||
export type NotificationEventKey = keyof NotificationPreferences["events"];
|
||||
|
||||
export interface NotificationPluginEntry {
|
||||
id: string;
|
||||
label: string;
|
||||
}
|
||||
|
||||
export function collectNotificationPlugins(input: {
|
||||
configuredPlugins?: readonly { id: string; name?: string }[];
|
||||
installedPlugins: readonly { id: string; name?: string }[];
|
||||
mutedPluginIds: readonly string[];
|
||||
}): NotificationPluginEntry[] {
|
||||
const byId = new Map<string, string>();
|
||||
|
||||
const recordPlugin = (id: string, name?: string) => {
|
||||
const trimmedId = id.trim();
|
||||
if (trimmedId.length === 0) {
|
||||
return;
|
||||
}
|
||||
const trimmedName = typeof name === "string" ? name.trim() : "";
|
||||
const existing = byId.get(trimmedId);
|
||||
if (!existing || existing === trimmedId) {
|
||||
byId.set(trimmedId, trimmedName.length > 0 ? trimmedName : trimmedId);
|
||||
}
|
||||
};
|
||||
|
||||
for (const plugin of input.configuredPlugins ?? []) {
|
||||
recordPlugin(plugin.id, plugin.name);
|
||||
}
|
||||
for (const plugin of input.installedPlugins) {
|
||||
recordPlugin(plugin.id, plugin.name);
|
||||
}
|
||||
for (const mutedId of input.mutedPluginIds) {
|
||||
recordPlugin(mutedId);
|
||||
}
|
||||
|
||||
return Array.from(byId.entries())
|
||||
.sort(([leftId], [rightId]) => leftId.localeCompare(rightId))
|
||||
.map(([id, label]) => ({ id, label }));
|
||||
}
|
||||
|
||||
export function collectNotificationPluginIds(
|
||||
installedPlugins: readonly { id: string }[],
|
||||
mutedPluginIds: readonly string[],
|
||||
): string[] {
|
||||
return collectNotificationPlugins({ installedPlugins, mutedPluginIds }).map((entry) => entry.id);
|
||||
}
|
||||
|
||||
export function setNotificationEventEnabled(
|
||||
preferences: NotificationPreferences,
|
||||
eventKey: NotificationEventKey,
|
||||
enabled: boolean,
|
||||
): NotificationPreferences {
|
||||
return normalizeNotificationPreferences({
|
||||
...preferences,
|
||||
events: {
|
||||
...preferences.events,
|
||||
[eventKey]: enabled,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function setNotificationPluginMuted(
|
||||
preferences: NotificationPreferences,
|
||||
pluginId: string,
|
||||
muted: boolean,
|
||||
): NotificationPreferences {
|
||||
const currentMuted = new Set(preferences.plugins.muted);
|
||||
if (muted) {
|
||||
currentMuted.add(pluginId);
|
||||
} else {
|
||||
currentMuted.delete(pluginId);
|
||||
}
|
||||
return normalizeNotificationPreferences({
|
||||
...preferences,
|
||||
plugins: {
|
||||
...preferences.plugins,
|
||||
muted: Array.from(currentMuted),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function hasConnectedHostMissingPushPreferences(
|
||||
hosts: readonly { serverId: string }[],
|
||||
sessions: HostFeatureSessionState["sessions"],
|
||||
): boolean {
|
||||
for (const host of hosts) {
|
||||
const serverInfo = sessions[host.serverId]?.serverInfo;
|
||||
if (!serverInfo) {
|
||||
continue;
|
||||
}
|
||||
// COMPAT(pushNotificationPreferences): added in v0.18.0, remove gate after 2027-06-01.
|
||||
if (serverInfo.features?.pushNotificationPreferences !== true) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
@@ -0,0 +1,311 @@
|
||||
import { AppearanceText as Text } from "@/appearance/text";
|
||||
import { useCallback, useMemo } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { View } from "react-native";
|
||||
import { StyleSheet } from "react-native-unistyles";
|
||||
import { normalizeNotificationPreferences } from "@getpaseo/protocol/notification-preferences";
|
||||
import { SettingsSection } from "@/components/settings/headings/settings-section";
|
||||
import {
|
||||
collectNotificationPlugins,
|
||||
hasConnectedHostMissingPushPreferences,
|
||||
setNotificationEventEnabled,
|
||||
setNotificationPluginMuted,
|
||||
type NotificationEventKey,
|
||||
} from "@/components/settings/notifications-model";
|
||||
import { Alert } from "@/components/ui/alert";
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
import { isNative } from "@/constants/platform";
|
||||
import { DesktopNotificationsSection } from "@/desktop/components/desktop-notifications-section";
|
||||
import { useAppSettings } from "@/hooks/use-settings";
|
||||
import { useConfiguredPluginsAcrossHosts } from "@/plugins/plugin-list";
|
||||
import { useInstalledPlugins } from "@/plugins/registry";
|
||||
import { useHosts } from "@/runtime/host-runtime";
|
||||
import { useSessionStore } from "@/stores/session-store";
|
||||
import { settingsStyles } from "@/styles/settings";
|
||||
|
||||
const EVENT_KEYS: readonly NotificationEventKey[] = [
|
||||
"agentPermission",
|
||||
"agentError",
|
||||
"agentFinished",
|
||||
"terminalNeedsInput",
|
||||
"terminalFinished",
|
||||
];
|
||||
|
||||
interface EventSwitchRowProps {
|
||||
eventKey: NotificationEventKey;
|
||||
label: string;
|
||||
description: string;
|
||||
value: boolean;
|
||||
disabled: boolean;
|
||||
showBorder: boolean;
|
||||
onChange: (eventKey: NotificationEventKey, value: boolean) => void;
|
||||
}
|
||||
|
||||
function EventSwitchRow({
|
||||
eventKey,
|
||||
label,
|
||||
description,
|
||||
value,
|
||||
disabled,
|
||||
showBorder,
|
||||
onChange,
|
||||
}: EventSwitchRowProps) {
|
||||
const handleChange = useCallback(
|
||||
(nextValue: boolean) => {
|
||||
onChange(eventKey, nextValue);
|
||||
},
|
||||
[eventKey, onChange],
|
||||
);
|
||||
const rowStyle = useMemo(
|
||||
() => [settingsStyles.row, showBorder ? settingsStyles.rowBorder : null],
|
||||
[showBorder],
|
||||
);
|
||||
|
||||
return (
|
||||
<View style={rowStyle}>
|
||||
<View style={settingsStyles.rowContent}>
|
||||
<Text style={settingsStyles.rowTitle}>{label}</Text>
|
||||
<Text style={settingsStyles.rowHint}>{description}</Text>
|
||||
</View>
|
||||
<Switch
|
||||
value={value}
|
||||
onValueChange={handleChange}
|
||||
disabled={disabled}
|
||||
accessibilityLabel={label}
|
||||
testID={`notifications-event-${eventKey}-switch`}
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
interface PluginSwitchRowProps {
|
||||
pluginId: string;
|
||||
label: string;
|
||||
muted: boolean;
|
||||
disabled: boolean;
|
||||
onToggleMuted: (pluginId: string, muted: boolean) => void;
|
||||
}
|
||||
|
||||
function PluginSwitchRow({
|
||||
pluginId,
|
||||
label,
|
||||
muted,
|
||||
disabled,
|
||||
onToggleMuted,
|
||||
}: PluginSwitchRowProps) {
|
||||
const handleChange = useCallback(
|
||||
(enabled: boolean) => {
|
||||
onToggleMuted(pluginId, !enabled);
|
||||
},
|
||||
[onToggleMuted, pluginId],
|
||||
);
|
||||
|
||||
return (
|
||||
<View style={[settingsStyles.row, settingsStyles.rowBorder]}>
|
||||
<View style={settingsStyles.rowContent}>
|
||||
<Text style={settingsStyles.rowTitle}>{label}</Text>
|
||||
{label !== pluginId ? <Text style={settingsStyles.rowHint}>{pluginId}</Text> : null}
|
||||
</View>
|
||||
<Switch
|
||||
value={!muted}
|
||||
onValueChange={handleChange}
|
||||
disabled={disabled}
|
||||
accessibilityLabel={label}
|
||||
testID={`notifications-plugin-switch-${pluginId}`}
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
export function NotificationsSection() {
|
||||
const { t } = useTranslation();
|
||||
const { settings, updateSettings } = useAppSettings();
|
||||
const preferences = settings.notifications;
|
||||
const configuredPlugins = useConfiguredPluginsAcrossHosts();
|
||||
const installedPlugins = useInstalledPlugins();
|
||||
const hosts = useHosts();
|
||||
const sessions = useSessionStore((state) => state.sessions);
|
||||
|
||||
const plugins = useMemo(
|
||||
() =>
|
||||
collectNotificationPlugins({
|
||||
configuredPlugins,
|
||||
installedPlugins,
|
||||
mutedPluginIds: preferences.plugins.muted,
|
||||
}),
|
||||
[configuredPlugins, installedPlugins, preferences.plugins.muted],
|
||||
);
|
||||
const mutedPluginIds = useMemo(
|
||||
() => new Set(preferences.plugins.muted),
|
||||
[preferences.plugins.muted],
|
||||
);
|
||||
const showLegacyHostHint = useMemo(
|
||||
() => isNative && hasConnectedHostMissingPushPreferences(hosts, sessions),
|
||||
[hosts, sessions],
|
||||
);
|
||||
|
||||
const handleMasterEnabledChange = useCallback(
|
||||
(enabled: boolean) => {
|
||||
void updateSettings((current) => ({
|
||||
notifications: normalizeNotificationPreferences({
|
||||
...current.notifications,
|
||||
enabled,
|
||||
}),
|
||||
}));
|
||||
},
|
||||
[updateSettings],
|
||||
);
|
||||
|
||||
const handleEventChange = useCallback(
|
||||
(eventKey: NotificationEventKey, enabled: boolean) => {
|
||||
void updateSettings((current) => ({
|
||||
notifications: setNotificationEventEnabled(current.notifications, eventKey, enabled),
|
||||
}));
|
||||
},
|
||||
[updateSettings],
|
||||
);
|
||||
|
||||
const handlePluginsEnabledChange = useCallback(
|
||||
(enabled: boolean) => {
|
||||
void updateSettings((current) => ({
|
||||
notifications: normalizeNotificationPreferences({
|
||||
...current.notifications,
|
||||
plugins: {
|
||||
...current.notifications.plugins,
|
||||
enabled,
|
||||
},
|
||||
}),
|
||||
}));
|
||||
},
|
||||
[updateSettings],
|
||||
);
|
||||
|
||||
const handlePluginMutedChange = useCallback(
|
||||
(pluginId: string, muted: boolean) => {
|
||||
void updateSettings((current) => ({
|
||||
notifications: setNotificationPluginMuted(current.notifications, pluginId, muted),
|
||||
}));
|
||||
},
|
||||
[updateSettings],
|
||||
);
|
||||
|
||||
const subCardStyle = useMemo(
|
||||
() => [settingsStyles.card, !preferences.enabled ? styles.disabledCard : null],
|
||||
[preferences.enabled],
|
||||
);
|
||||
const showEmptyPluginsRow = preferences.plugins.enabled && plugins.length === 0;
|
||||
const showPluginRows = preferences.plugins.enabled && plugins.length > 0;
|
||||
|
||||
return (
|
||||
<View>
|
||||
<SettingsSection
|
||||
title={t("settings.notifications.title")}
|
||||
testID="notifications-master-section"
|
||||
>
|
||||
<View style={settingsStyles.card} testID="notifications-master-card">
|
||||
<View style={settingsStyles.row}>
|
||||
<View style={settingsStyles.rowContent}>
|
||||
<Text style={settingsStyles.rowTitle}>
|
||||
{t("settings.notifications.enabled.label")}
|
||||
</Text>
|
||||
<Text style={settingsStyles.rowHint}>
|
||||
{preferences.enabled
|
||||
? t("settings.notifications.enabled.description")
|
||||
: t("settings.notifications.enabled.pausedDescription")}
|
||||
</Text>
|
||||
</View>
|
||||
<Switch
|
||||
value={preferences.enabled}
|
||||
onValueChange={handleMasterEnabledChange}
|
||||
accessibilityLabel={t("settings.notifications.enabled.label")}
|
||||
testID="notifications-master-switch"
|
||||
/>
|
||||
</View>
|
||||
</View>
|
||||
{showLegacyHostHint ? (
|
||||
<Alert
|
||||
size="sm"
|
||||
variant="info"
|
||||
title={t("settings.notifications.legacyHostTitle")}
|
||||
description={t("settings.notifications.legacyHostHint")}
|
||||
testID="notifications-legacy-host-alert"
|
||||
/>
|
||||
) : null}
|
||||
</SettingsSection>
|
||||
|
||||
<SettingsSection
|
||||
title={t("settings.notifications.events.title")}
|
||||
testID="notifications-events-section"
|
||||
>
|
||||
<View style={subCardStyle} testID="notifications-events-card">
|
||||
{EVENT_KEYS.map((eventKey, index) => (
|
||||
<EventSwitchRow
|
||||
key={eventKey}
|
||||
eventKey={eventKey}
|
||||
label={t(`settings.notifications.events.${eventKey}.label`)}
|
||||
description={t(`settings.notifications.events.${eventKey}.description`)}
|
||||
value={preferences.events[eventKey]}
|
||||
disabled={!preferences.enabled}
|
||||
showBorder={index > 0}
|
||||
onChange={handleEventChange}
|
||||
/>
|
||||
))}
|
||||
</View>
|
||||
</SettingsSection>
|
||||
|
||||
<SettingsSection
|
||||
title={t("settings.notifications.plugins.title")}
|
||||
testID="notifications-plugins-section"
|
||||
>
|
||||
<View style={subCardStyle} testID="notifications-plugins-card">
|
||||
<View style={settingsStyles.row}>
|
||||
<View style={settingsStyles.rowContent}>
|
||||
<Text style={settingsStyles.rowTitle}>
|
||||
{t("settings.notifications.plugins.enabled.label")}
|
||||
</Text>
|
||||
<Text style={settingsStyles.rowHint}>
|
||||
{t("settings.notifications.plugins.enabled.description")}
|
||||
</Text>
|
||||
</View>
|
||||
<Switch
|
||||
value={preferences.plugins.enabled}
|
||||
onValueChange={handlePluginsEnabledChange}
|
||||
disabled={!preferences.enabled}
|
||||
accessibilityLabel={t("settings.notifications.plugins.enabled.label")}
|
||||
testID="notifications-plugins-enabled-switch"
|
||||
/>
|
||||
</View>
|
||||
{showEmptyPluginsRow ? (
|
||||
<View style={[settingsStyles.row, settingsStyles.rowBorder]}>
|
||||
<View style={settingsStyles.rowContent}>
|
||||
<Text style={settingsStyles.rowHint} testID="notifications-plugins-empty">
|
||||
{t("settings.notifications.plugins.empty")}
|
||||
</Text>
|
||||
</View>
|
||||
</View>
|
||||
) : null}
|
||||
{showPluginRows
|
||||
? plugins.map((plugin) => (
|
||||
<PluginSwitchRow
|
||||
key={plugin.id}
|
||||
pluginId={plugin.id}
|
||||
label={plugin.label}
|
||||
muted={mutedPluginIds.has(plugin.id)}
|
||||
disabled={!preferences.enabled}
|
||||
onToggleMuted={handlePluginMutedChange}
|
||||
/>
|
||||
))
|
||||
: null}
|
||||
</View>
|
||||
</SettingsSection>
|
||||
|
||||
<DesktopNotificationsSection />
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
disabledCard: {
|
||||
opacity: theme.opacity[50],
|
||||
},
|
||||
}));
|
||||
@@ -71,6 +71,7 @@ export interface TerminalEmulatorProps {
|
||||
target: TerminalLocalFileLinkTarget,
|
||||
disposition: "main" | "side",
|
||||
) => Promise<void> | void;
|
||||
onOpenExternalUrl?: (url: string) => Promise<void> | void;
|
||||
onRendererReadyChange?: (change: TerminalRendererReadyChange) => void;
|
||||
pendingModifiers?: PendingTerminalModifiers;
|
||||
focusRequestToken?: number;
|
||||
|
||||
@@ -142,6 +142,7 @@ interface TerminalEmulatorProps {
|
||||
target: TerminalLocalFileLinkTarget,
|
||||
disposition: "main" | "side",
|
||||
) => Promise<void> | void;
|
||||
onOpenExternalUrl?: (url: string) => Promise<void> | void;
|
||||
onRendererReadyChange?: (change: TerminalRendererReadyChange) => void;
|
||||
onFilePaste?: (file: Promise<TerminalFile | null>) => void;
|
||||
pendingModifiers?: PendingTerminalModifiers;
|
||||
@@ -179,6 +180,7 @@ export default function TerminalEmulator({
|
||||
onInputModeChange,
|
||||
onResolveLocalFileLink,
|
||||
onOpenLocalFileLink,
|
||||
onOpenExternalUrl,
|
||||
onRendererReadyChange,
|
||||
onFilePaste,
|
||||
pendingModifiers = { ctrl: false, shift: false, alt: false },
|
||||
@@ -212,6 +214,7 @@ export default function TerminalEmulator({
|
||||
onInputModeChange,
|
||||
onResolveLocalFileLink,
|
||||
onOpenLocalFileLink,
|
||||
onOpenExternalUrl: onOpenExternalUrl ?? openExternalUrl,
|
||||
onFilePaste,
|
||||
});
|
||||
mountCallbacksRef.current = {
|
||||
@@ -224,6 +227,7 @@ export default function TerminalEmulator({
|
||||
onInputModeChange,
|
||||
onResolveLocalFileLink,
|
||||
onOpenLocalFileLink,
|
||||
onOpenExternalUrl: onOpenExternalUrl ?? openExternalUrl,
|
||||
onFilePaste,
|
||||
};
|
||||
const pendingModifiersRef = useRef(pendingModifiers);
|
||||
@@ -459,7 +463,6 @@ export default function TerminalEmulator({
|
||||
runtime.setCallbacks({
|
||||
callbacks: {
|
||||
...mountCallbacksRef.current,
|
||||
onOpenExternalUrl: openExternalUrl,
|
||||
},
|
||||
});
|
||||
runtime.setPendingModifiers({ pendingModifiers: pendingModifiersRef.current });
|
||||
@@ -496,7 +499,7 @@ export default function TerminalEmulator({
|
||||
onResolveLocalFileLink,
|
||||
onOpenLocalFileLink,
|
||||
onFilePaste,
|
||||
onOpenExternalUrl: openExternalUrl,
|
||||
onOpenExternalUrl: onOpenExternalUrl ?? openExternalUrl,
|
||||
},
|
||||
});
|
||||
}, [
|
||||
@@ -505,6 +508,7 @@ export default function TerminalEmulator({
|
||||
onFindResult,
|
||||
onInput,
|
||||
onInputModeChange,
|
||||
onOpenExternalUrl,
|
||||
onOpenLocalFileLink,
|
||||
onPendingModifiersConsumed,
|
||||
onResolveLocalFileLink,
|
||||
|
||||
@@ -102,6 +102,8 @@ import {
|
||||
type OpenFileDisposition,
|
||||
type WorkspaceFileOpenRequest,
|
||||
} from "@/workspace/file-open";
|
||||
import { shouldRouteWorkspaceUrlToProxiedBrowser } from "@/desktop/browser/proxy";
|
||||
import { openExternalUrl } from "@/utils/open-external-url";
|
||||
|
||||
interface TerminalPaneProps {
|
||||
serverId: string;
|
||||
@@ -111,6 +113,7 @@ interface TerminalPaneProps {
|
||||
isPaneFocused: boolean;
|
||||
onOpenFileExplorer: () => void;
|
||||
onOpenWorkspaceFile: (request: WorkspaceFileOpenRequest) => void;
|
||||
onOpenBrowserUrl?: (url: string) => void;
|
||||
}
|
||||
|
||||
const TERMINAL_REFIT_DELAYS_MS = [0, 48, 144, 320];
|
||||
@@ -265,6 +268,7 @@ export function TerminalPane({
|
||||
isPaneFocused,
|
||||
onOpenFileExplorer,
|
||||
onOpenWorkspaceFile,
|
||||
onOpenBrowserUrl,
|
||||
}: TerminalPaneProps) {
|
||||
const { t } = useTranslation();
|
||||
const retainedPanelActive = useRetainedPanelActive();
|
||||
@@ -1162,6 +1166,17 @@ export function TerminalPane({
|
||||
terminalStreamKey,
|
||||
});
|
||||
|
||||
const handleOpenExternalUrl = useCallback(
|
||||
async (url: string) => {
|
||||
if (onOpenBrowserUrl && shouldRouteWorkspaceUrlToProxiedBrowser({ serverId, url })) {
|
||||
onOpenBrowserUrl(url);
|
||||
return;
|
||||
}
|
||||
await openExternalUrl(url);
|
||||
},
|
||||
[onOpenBrowserUrl, serverId],
|
||||
);
|
||||
|
||||
if (!client || !isConnected) {
|
||||
return (
|
||||
<View style={styles.centerState}>
|
||||
@@ -1203,6 +1218,7 @@ export function TerminalPane({
|
||||
onSelectionChange={handleSelectionChange}
|
||||
onResolveLocalFileLink={handleResolveLocalFileLink}
|
||||
onOpenLocalFileLink={handleOpenLocalFileLink}
|
||||
onOpenExternalUrl={handleOpenExternalUrl}
|
||||
onPendingModifiersConsumed={handlePendingModifiersConsumed}
|
||||
pendingModifiers={modifiers}
|
||||
focusRequestToken={focusRequestToken}
|
||||
|
||||
@@ -132,6 +132,7 @@ function buildCreateAgentOptions({
|
||||
effectiveModeId: string;
|
||||
effectiveModelId: string | null;
|
||||
effectiveThinkingOptionId: string | null;
|
||||
selectedSystemPrompt: string;
|
||||
};
|
||||
text: string;
|
||||
attachments: NonNullable<CreateAgentRequestOptions["attachments"]>;
|
||||
@@ -149,6 +150,9 @@ function buildCreateAgentOptions({
|
||||
...(composerState.effectiveThinkingOptionId
|
||||
? { thinkingOptionId: composerState.effectiveThinkingOptionId }
|
||||
: {}),
|
||||
...(composerState.selectedSystemPrompt
|
||||
? { systemPrompt: composerState.selectedSystemPrompt }
|
||||
: {}),
|
||||
...(text.trim() ? { initialPrompt: text.trim() } : {}),
|
||||
...(encodedImages && encodedImages.length > 0 ? { images: encodedImages } : {}),
|
||||
...(attachments.length > 0 ? { attachments } : {}),
|
||||
|
||||
@@ -55,6 +55,7 @@ interface AutoSubmitConfig {
|
||||
model: string | null;
|
||||
thinkingOptionId: string | null;
|
||||
providerOptions: Record<string, unknown>;
|
||||
systemPrompt: string | null;
|
||||
}
|
||||
|
||||
function resolveAutoSubmitConfig(
|
||||
@@ -64,6 +65,7 @@ function resolveAutoSubmitConfig(
|
||||
model?: string | null;
|
||||
thinkingOptionId?: string | null;
|
||||
providerOptions?: Record<string, unknown>;
|
||||
systemPrompt?: string | null;
|
||||
} | null,
|
||||
): AutoSubmitConfig | null {
|
||||
if (!pending) return null;
|
||||
@@ -73,6 +75,7 @@ function resolveAutoSubmitConfig(
|
||||
model: pending.model ?? null,
|
||||
thinkingOptionId: pending.thinkingOptionId ?? null,
|
||||
providerOptions: pending.providerOptions ?? {},
|
||||
systemPrompt: pending.systemPrompt ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -104,6 +107,36 @@ function resolveDraftModeId(input: {
|
||||
return null;
|
||||
}
|
||||
|
||||
function resolveDraftCreateConfig(input: {
|
||||
provider: string;
|
||||
cwd: string;
|
||||
autoSubmitConfig: AutoSubmitConfig | null;
|
||||
composerState: {
|
||||
effectiveModeId: string;
|
||||
effectiveModelId: string | null;
|
||||
effectiveThinkingOptionId: string | null;
|
||||
selectedSystemPrompt: string;
|
||||
providerOptions: Record<string, unknown> | undefined;
|
||||
};
|
||||
}) {
|
||||
const { provider, cwd, autoSubmitConfig, composerState } = input;
|
||||
const modeIdOverride = resolveDraftModeIdOverride({
|
||||
autoSubmitConfig,
|
||||
effectiveModeId: composerState.effectiveModeId,
|
||||
});
|
||||
return buildWorkspaceDraftAgentConfig({
|
||||
provider,
|
||||
cwd,
|
||||
...modeIdOverride,
|
||||
model: autoSubmitConfig?.model ?? (composerState.effectiveModelId || undefined),
|
||||
thinkingOptionId:
|
||||
autoSubmitConfig?.thinkingOptionId ?? (composerState.effectiveThinkingOptionId || undefined),
|
||||
providerOptions: autoSubmitConfig?.providerOptions ?? composerState.providerOptions,
|
||||
systemPrompt:
|
||||
autoSubmitConfig?.systemPrompt ?? (composerState.selectedSystemPrompt || undefined),
|
||||
});
|
||||
}
|
||||
|
||||
async function submitDraftCreateRequest(input: {
|
||||
draftId: string;
|
||||
attempt: { clientMessageId: string };
|
||||
@@ -120,6 +153,7 @@ async function submitDraftCreateRequest(input: {
|
||||
effectiveModeId: string;
|
||||
effectiveModelId: string | null;
|
||||
effectiveThinkingOptionId: string | null;
|
||||
selectedSystemPrompt: string;
|
||||
providerOptions: Record<string, unknown> | undefined;
|
||||
metadata: Record<string, JsonValue>;
|
||||
};
|
||||
@@ -149,18 +183,11 @@ async function submitDraftCreateRequest(input: {
|
||||
if (!provider) {
|
||||
throw new Error(input.selectModelMessage);
|
||||
}
|
||||
const modeIdOverride = resolveDraftModeIdOverride({
|
||||
autoSubmitConfig,
|
||||
effectiveModeId: composerState.effectiveModeId,
|
||||
});
|
||||
const config = buildWorkspaceDraftAgentConfig({
|
||||
const config = resolveDraftCreateConfig({
|
||||
provider,
|
||||
cwd,
|
||||
...modeIdOverride,
|
||||
model: autoSubmitConfig?.model ?? (composerState.effectiveModelId || undefined),
|
||||
thinkingOptionId:
|
||||
autoSubmitConfig?.thinkingOptionId ?? (composerState.effectiveThinkingOptionId || undefined),
|
||||
providerOptions: autoSubmitConfig?.providerOptions ?? composerState.providerOptions,
|
||||
autoSubmitConfig,
|
||||
composerState,
|
||||
});
|
||||
|
||||
const attachmentsArray = Array.isArray(attachments) ? attachments : undefined;
|
||||
@@ -250,6 +277,7 @@ function buildDraftInitialValues(input: {
|
||||
modeId: input.initialSetup.modeId,
|
||||
model: input.initialSetup.model,
|
||||
thinkingOptionId: input.initialSetup.thinkingOptionId,
|
||||
systemPrompt: input.initialSetup.systemPrompt,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -1656,6 +1656,15 @@ function ComposerContentImpl({
|
||||
});
|
||||
}, []);
|
||||
|
||||
const handleImagesDropped = useCallback(
|
||||
(images: ImageAttachment[]) => {
|
||||
if (images.length === 0) return;
|
||||
addImages(images);
|
||||
focusInput();
|
||||
},
|
||||
[addImages, focusInput],
|
||||
);
|
||||
|
||||
const handleWorkspaceFileDropped = useCallback(
|
||||
(payload: WorkspaceFileDragPayload) => {
|
||||
if (!workspaceId) {
|
||||
@@ -1988,6 +1997,7 @@ function ComposerContentImpl({
|
||||
toastErrorRef.current(t("composer.errors.daemonClientDisconnected"));
|
||||
return;
|
||||
}
|
||||
focusInput();
|
||||
await uploadSelectedFiles(files);
|
||||
} catch (error) {
|
||||
console.error("[Composer] Failed to upload dropped files:", error);
|
||||
@@ -1996,7 +2006,7 @@ function ComposerContentImpl({
|
||||
);
|
||||
}
|
||||
},
|
||||
[client, isConnected, t, uploadSelectedFiles],
|
||||
[client, focusInput, isConnected, t, uploadSelectedFiles],
|
||||
);
|
||||
|
||||
const handleRemoveAttachment = useCallback(
|
||||
@@ -2544,7 +2554,7 @@ function ComposerContentImpl({
|
||||
// backdrop and rejects the drop atomically, instead of accepting a drop with no feedback.
|
||||
useFileDrop(
|
||||
{
|
||||
onFiles: addImages,
|
||||
onFiles: handleImagesDropped,
|
||||
onGenericFiles: handleGenericFilesDropped,
|
||||
onWorkspaceFile: handleWorkspaceFileDropped,
|
||||
},
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useRef, ReactNode, useCallback, useEffect } from "react";
|
||||
import { Buffer } from "buffer";
|
||||
import { AppState } from "react-native";
|
||||
import { isNative } from "@/constants/platform";
|
||||
import { observeOpenWorkspaceAgentIds } from "@/stores/workspace-layout-store";
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import { useTranslation } from "react-i18next";
|
||||
@@ -11,21 +12,22 @@ import {
|
||||
createSetAgentInitializing,
|
||||
refreshAgentInitializationTimeout,
|
||||
} from "@/hooks/use-agent-initialization";
|
||||
import type { StreamItem } from "@/types/stream";
|
||||
import { planTimelineTailFetch } from "@/timeline/timeline-sync-plan";
|
||||
import { requestTimelineReplacement } from "@/timeline/timeline-replacement";
|
||||
import { type ViewedTimelineOwner } from "@/timeline/viewed-timeline-sync";
|
||||
import type { SessionOutboundMessage } from "@getpaseo/protocol/messages";
|
||||
import { parseServerInfoStatusPayload } from "@getpaseo/protocol/messages";
|
||||
import type { AgentAttentionNotificationPayload } from "@getpaseo/protocol/agent-attention-notification";
|
||||
import {
|
||||
buildAgentAttentionNotificationPayload,
|
||||
type AgentAttentionReason,
|
||||
type AgentAttentionNotificationPayload,
|
||||
type NotificationPermissionRequest,
|
||||
} from "@getpaseo/protocol/agent-attention-notification";
|
||||
deliverAgentAttentionOsNotification,
|
||||
deliverPluginOsNotification,
|
||||
deliverTerminalAttentionOsNotification,
|
||||
getCurrentNotificationPreferences,
|
||||
} from "./session-notifications";
|
||||
|
||||
import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
|
||||
import type { AgentPermissionResponse } from "@getpaseo/protocol/agent-types";
|
||||
import { useHostFeature } from "@/runtime/host-features";
|
||||
import { getHostRuntimeStore, useHostRuntimeIsConnected } from "@/runtime/host-runtime";
|
||||
import { useVoiceAudioEngineOptional, useVoiceRuntimeOptional } from "@/contexts/voice-context";
|
||||
import type { AudioPlaybackSource } from "@/audio";
|
||||
@@ -33,10 +35,9 @@ import {
|
||||
selectAgentTimelineState,
|
||||
toDaemonServerInfo,
|
||||
useSessionStore,
|
||||
type SessionState,
|
||||
} from "@/stores/session-store";
|
||||
import { sendOsNotification } from "@/utils/os-notifications";
|
||||
import { getIsAppActivelyVisible, getIsAppVisible } from "@/utils/app-visibility";
|
||||
import { getIsAppVisible } from "@/utils/app-visibility";
|
||||
import {
|
||||
getInitKey,
|
||||
getInitDeferred,
|
||||
@@ -98,71 +99,6 @@ function buildAudioPlaybackSource(chunks: BufferedAudioChunk[]): AudioPlaybackSo
|
||||
};
|
||||
}
|
||||
|
||||
const findLatestAssistantMessageText = (items: StreamItem[]): string | null => {
|
||||
for (let i = items.length - 1; i >= 0; i -= 1) {
|
||||
const item = items[i];
|
||||
if (item.kind === "assistant_message") {
|
||||
return item.text;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
const getLatestPermissionRequest = (
|
||||
session: SessionState | undefined,
|
||||
agentId: string,
|
||||
): NotificationPermissionRequest | null => {
|
||||
if (!session) {
|
||||
return null;
|
||||
}
|
||||
|
||||
let latest: NotificationPermissionRequest | null = null;
|
||||
for (const pending of session.pendingPermissions.values()) {
|
||||
if (pending.agentId === agentId) {
|
||||
latest = pending.request;
|
||||
}
|
||||
}
|
||||
if (latest) {
|
||||
return latest;
|
||||
}
|
||||
|
||||
const agentPending = session.agents.get(agentId)?.pendingPermissions;
|
||||
if (agentPending && agentPending.length > 0) {
|
||||
return agentPending[agentPending.length - 1] as NotificationPermissionRequest;
|
||||
}
|
||||
|
||||
return null;
|
||||
};
|
||||
|
||||
interface AgentAttentionNotificationInput {
|
||||
notification?: AgentAttentionNotificationPayload;
|
||||
reason: AgentAttentionReason;
|
||||
serverId: string;
|
||||
workspaceId: string | undefined;
|
||||
agentId: string;
|
||||
assistantMessage: string | null;
|
||||
permissionRequest: NotificationPermissionRequest | null;
|
||||
}
|
||||
|
||||
function resolveAgentAttentionNotification(
|
||||
input: AgentAttentionNotificationInput,
|
||||
): AgentAttentionNotificationPayload | null {
|
||||
if (input.notification) {
|
||||
return input.notification.data.workspaceId ? input.notification : null;
|
||||
}
|
||||
if (!input.workspaceId) {
|
||||
return null;
|
||||
}
|
||||
return buildAgentAttentionNotificationPayload({
|
||||
reason: input.reason,
|
||||
serverId: input.serverId,
|
||||
workspaceId: input.workspaceId,
|
||||
agentId: input.agentId,
|
||||
assistantMessage: input.reason === "finished" ? input.assistantMessage : null,
|
||||
permissionRequest: input.reason === "permission" ? input.permissionRequest : null,
|
||||
});
|
||||
}
|
||||
|
||||
function notifyVoiceAbortFailure(
|
||||
data: Extract<SessionOutboundMessage, { type: "activity_log" }>["payload"],
|
||||
notifyError: (message: string) => void,
|
||||
@@ -202,6 +138,10 @@ function SessionProviderInternal({ children, serverId, client }: SessionProvider
|
||||
const voiceAudioEngine = useVoiceAudioEngineOptional();
|
||||
const queryClient = useQueryClient();
|
||||
const isConnected = useHostRuntimeIsConnected(serverId);
|
||||
// COMPAT(pluginNotifications): added in v0.18.0, remove gate after 2027-06-01.
|
||||
const supportsPluginNotifications =
|
||||
useHostFeature(serverId, "pluginNotifications") ||
|
||||
client.getLastServerInfoMessage()?.features?.pluginNotifications === true;
|
||||
const toast = useToast();
|
||||
|
||||
// Zustand store actions
|
||||
@@ -251,7 +191,10 @@ function SessionProviderInternal({ children, serverId, client }: SessionProvider
|
||||
focusedAgentId,
|
||||
focusedTerminalId,
|
||||
});
|
||||
useEffect(() => startPushNotifications({ client, serverId }), [client, serverId]);
|
||||
useEffect(
|
||||
() => startPushNotifications({ client, serverId, queryClient }),
|
||||
[client, queryClient, serverId],
|
||||
);
|
||||
|
||||
const notifyAgentAttention = useCallback(
|
||||
(params: {
|
||||
@@ -260,52 +203,17 @@ function SessionProviderInternal({ children, serverId, client }: SessionProvider
|
||||
timestamp: string;
|
||||
notification?: AgentAttentionNotificationPayload;
|
||||
}) => {
|
||||
const appState = appStateRef.current;
|
||||
const session = useSessionStore.getState().sessions[serverId];
|
||||
const attentionFocusedAgentId = session?.focusedAgentId ?? null;
|
||||
if (params.reason === "error") {
|
||||
return;
|
||||
}
|
||||
const isActivelyVisible = getIsAppActivelyVisible(appState);
|
||||
const isAwayFromAgent = !isActivelyVisible || attentionFocusedAgentId !== params.agentId;
|
||||
if (!isAwayFromAgent) {
|
||||
return;
|
||||
}
|
||||
|
||||
const timestampMs = new Date(params.timestamp).getTime();
|
||||
const lastNotified = attentionNotifiedRef.current.get(params.agentId);
|
||||
if (lastNotified && lastNotified >= timestampMs) {
|
||||
return;
|
||||
}
|
||||
attentionNotifiedRef.current.set(params.agentId, timestampMs);
|
||||
|
||||
const head = session?.agentStreamHead.get(params.agentId) ?? [];
|
||||
const tail = session?.agentStreamTail.get(params.agentId) ?? [];
|
||||
const assistantMessage =
|
||||
findLatestAssistantMessageText(head) ?? findLatestAssistantMessageText(tail);
|
||||
const permissionRequest = getLatestPermissionRequest(session, params.agentId);
|
||||
const workspaceId = session?.agents?.get(params.agentId)?.workspaceId;
|
||||
|
||||
const notification = resolveAgentAttentionNotification({
|
||||
notification: params.notification,
|
||||
reason: params.reason,
|
||||
deliverAgentAttentionOsNotification({
|
||||
serverId,
|
||||
workspaceId,
|
||||
agentId: params.agentId,
|
||||
assistantMessage,
|
||||
permissionRequest,
|
||||
});
|
||||
if (!notification) {
|
||||
return;
|
||||
}
|
||||
|
||||
void sendOsNotification({
|
||||
title: notification.title,
|
||||
body: notification.body,
|
||||
data: notification.data,
|
||||
params,
|
||||
appState: appStateRef.current,
|
||||
session: useSessionStore.getState().sessions[serverId],
|
||||
attentionNotified: attentionNotifiedRef.current,
|
||||
preferences: getCurrentNotificationPreferences(queryClient),
|
||||
sendNotification: sendOsNotification,
|
||||
});
|
||||
},
|
||||
[serverId],
|
||||
[queryClient, serverId],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -647,20 +555,11 @@ function SessionProviderInternal({ children, serverId, client }: SessionProvider
|
||||
if (message.type !== "terminal_attention_required") {
|
||||
return;
|
||||
}
|
||||
if (!message.payload.shouldNotify) {
|
||||
return;
|
||||
}
|
||||
void sendOsNotification({
|
||||
title: message.payload.title,
|
||||
body: message.payload.body,
|
||||
// serverId + workspaceId + terminalId route a tap to the terminal tab; cwd is
|
||||
// carried as a fallback identifier when the daemon resolved no workspace.
|
||||
data: {
|
||||
serverId: message.payload.serverId ?? serverId,
|
||||
terminalId: message.payload.terminalId,
|
||||
cwd: message.payload.cwd,
|
||||
...(message.payload.workspaceId ? { workspaceId: message.payload.workspaceId } : {}),
|
||||
},
|
||||
deliverTerminalAttentionOsNotification({
|
||||
serverId,
|
||||
payload: message.payload,
|
||||
preferences: getCurrentNotificationPreferences(queryClient),
|
||||
sendNotification: sendOsNotification,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -698,6 +597,41 @@ function SessionProviderInternal({ children, serverId, client }: SessionProvider
|
||||
voiceAudioEngine,
|
||||
]);
|
||||
|
||||
useEffect(() => {
|
||||
// Native apps receive plugin alerts via remote push only (`sendOsNotification` is a no-op
|
||||
// on native). Subscribing on native would mark the phone as the active in-app recipient and
|
||||
// suppress its own Expo push without rendering anything in-app.
|
||||
// COMPAT(pluginNotifications): added in v0.18.0, remove gate after 2027-06-01.
|
||||
if (isNative || !supportsPluginNotifications) {
|
||||
return;
|
||||
}
|
||||
const pluginNotificationsFeed = client.observeEvents(["plugin.notification"], {
|
||||
notifications: true,
|
||||
});
|
||||
const unsubPluginNotification = pluginNotificationsFeed.subscribe({
|
||||
snapshot: () => {},
|
||||
update: (message) => {
|
||||
if (message.type !== "plugin.notification") {
|
||||
return;
|
||||
}
|
||||
deliverPluginOsNotification({
|
||||
serverId,
|
||||
payload: message.payload,
|
||||
preferences: getCurrentNotificationPreferences(queryClient),
|
||||
sendNotification: sendOsNotification,
|
||||
});
|
||||
},
|
||||
});
|
||||
return () => {
|
||||
unsubPluginNotification();
|
||||
void pluginNotificationsFeed
|
||||
.release()
|
||||
.catch((error) =>
|
||||
console.warn("[Session] Failed to release plugin notifications feed", error),
|
||||
);
|
||||
};
|
||||
}, [client, queryClient, serverId, supportsPluginNotifications]);
|
||||
|
||||
const _cancelAgentRun = useCallback(
|
||||
(agentId: string) => {
|
||||
if (!client) {
|
||||
|
||||
@@ -0,0 +1,376 @@
|
||||
import { QueryClient } from "@tanstack/react-query";
|
||||
import {
|
||||
DEFAULT_NOTIFICATION_PREFERENCES,
|
||||
type NotificationPreferences,
|
||||
} from "@getpaseo/protocol/notification-preferences";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { APP_SETTINGS_QUERY_KEY, DEFAULT_CLIENT_SETTINGS } from "@/hooks/use-settings/storage";
|
||||
import {
|
||||
deliverAgentAttentionOsNotification,
|
||||
deliverPluginOsNotification,
|
||||
deliverTerminalAttentionOsNotification,
|
||||
getCurrentNotificationPreferences,
|
||||
} from "./session-notifications";
|
||||
|
||||
function createNotificationRecorder() {
|
||||
const sent: Array<{ title: string; body?: string; data?: Record<string, unknown> }> = [];
|
||||
return {
|
||||
sent,
|
||||
sendNotification: async (payload: {
|
||||
title: string;
|
||||
body?: string;
|
||||
data?: Record<string, unknown>;
|
||||
}) => {
|
||||
sent.push(payload);
|
||||
return true;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function makeAgentAttentionParams(reason: "permission" | "error" | "finished", index = 1) {
|
||||
return {
|
||||
agentId: `agent-${reason}-${index}`,
|
||||
reason,
|
||||
timestamp: new Date(1_700_000_000_000 + index * 1000).toISOString(),
|
||||
notification: {
|
||||
title: `Agent ${reason}`,
|
||||
body: `Body for ${reason}`,
|
||||
data: {
|
||||
serverId: "srv-1",
|
||||
workspaceId: "ws-1",
|
||||
agentId: `agent-${reason}-${index}`,
|
||||
reason,
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe("session OS notification filtering", () => {
|
||||
it("normalizes notification preferences from query cache or falls back to defaults", () => {
|
||||
const emptyClient = new QueryClient();
|
||||
expect(getCurrentNotificationPreferences(emptyClient)).toEqual(
|
||||
DEFAULT_NOTIFICATION_PREFERENCES,
|
||||
);
|
||||
|
||||
const populatedClient = new QueryClient();
|
||||
const custom: NotificationPreferences = {
|
||||
...DEFAULT_NOTIFICATION_PREFERENCES,
|
||||
events: {
|
||||
...DEFAULT_NOTIFICATION_PREFERENCES.events,
|
||||
agentFinished: true,
|
||||
},
|
||||
};
|
||||
populatedClient.setQueryData(APP_SETTINGS_QUERY_KEY, {
|
||||
...DEFAULT_CLIENT_SETTINGS,
|
||||
notifications: custom,
|
||||
});
|
||||
expect(getCurrentNotificationPreferences(populatedClient)).toEqual(custom);
|
||||
});
|
||||
|
||||
it("with default preferences, notifies on permission, error, and terminalNeedsInput, and skips finished and terminalFinished", () => {
|
||||
const recorder = createNotificationRecorder();
|
||||
const attentionNotified = new Map<string, number>();
|
||||
const preferences = DEFAULT_NOTIFICATION_PREFERENCES;
|
||||
|
||||
expect(
|
||||
deliverAgentAttentionOsNotification({
|
||||
serverId: "srv-1",
|
||||
params: makeAgentAttentionParams("permission", 1),
|
||||
isActivelyVisible: false,
|
||||
session: undefined,
|
||||
attentionNotified,
|
||||
preferences,
|
||||
sendNotification: recorder.sendNotification,
|
||||
}),
|
||||
).toBe(true);
|
||||
|
||||
expect(
|
||||
deliverAgentAttentionOsNotification({
|
||||
serverId: "srv-1",
|
||||
params: makeAgentAttentionParams("error", 2),
|
||||
isActivelyVisible: false,
|
||||
session: undefined,
|
||||
attentionNotified,
|
||||
preferences,
|
||||
sendNotification: recorder.sendNotification,
|
||||
}),
|
||||
).toBe(true);
|
||||
|
||||
expect(
|
||||
deliverAgentAttentionOsNotification({
|
||||
serverId: "srv-1",
|
||||
params: makeAgentAttentionParams("finished", 3),
|
||||
isActivelyVisible: false,
|
||||
session: undefined,
|
||||
attentionNotified,
|
||||
preferences,
|
||||
sendNotification: recorder.sendNotification,
|
||||
}),
|
||||
).toBe(false);
|
||||
|
||||
expect(
|
||||
deliverTerminalAttentionOsNotification({
|
||||
serverId: "srv-1",
|
||||
payload: {
|
||||
serverId: "srv-1",
|
||||
terminalId: "term-1",
|
||||
cwd: "/repo",
|
||||
workspaceId: "ws-1",
|
||||
reason: "needs_input",
|
||||
title: "Terminal waiting for input",
|
||||
body: "zsh",
|
||||
shouldNotify: true,
|
||||
},
|
||||
preferences,
|
||||
sendNotification: recorder.sendNotification,
|
||||
}),
|
||||
).toBe(true);
|
||||
|
||||
expect(
|
||||
deliverTerminalAttentionOsNotification({
|
||||
serverId: "srv-1",
|
||||
payload: {
|
||||
serverId: "srv-1",
|
||||
terminalId: "term-1",
|
||||
cwd: "/repo",
|
||||
workspaceId: "ws-1",
|
||||
reason: "finished",
|
||||
title: "Command finished",
|
||||
body: "zsh",
|
||||
shouldNotify: true,
|
||||
},
|
||||
preferences,
|
||||
sendNotification: recorder.sendNotification,
|
||||
}),
|
||||
).toBe(false);
|
||||
|
||||
expect(recorder.sent.map((item) => item.title)).toEqual([
|
||||
"Agent permission",
|
||||
"Agent error",
|
||||
"Terminal waiting for input",
|
||||
]);
|
||||
});
|
||||
|
||||
it("delivers finished notifications when agentFinished and terminalFinished are enabled", () => {
|
||||
const recorder = createNotificationRecorder();
|
||||
const attentionNotified = new Map<string, number>();
|
||||
const preferences: NotificationPreferences = {
|
||||
...DEFAULT_NOTIFICATION_PREFERENCES,
|
||||
events: {
|
||||
...DEFAULT_NOTIFICATION_PREFERENCES.events,
|
||||
agentFinished: true,
|
||||
terminalFinished: true,
|
||||
},
|
||||
};
|
||||
|
||||
expect(
|
||||
deliverAgentAttentionOsNotification({
|
||||
serverId: "srv-1",
|
||||
params: makeAgentAttentionParams("finished", 1),
|
||||
isActivelyVisible: false,
|
||||
session: undefined,
|
||||
attentionNotified,
|
||||
preferences,
|
||||
sendNotification: recorder.sendNotification,
|
||||
}),
|
||||
).toBe(true);
|
||||
|
||||
expect(
|
||||
deliverTerminalAttentionOsNotification({
|
||||
serverId: "srv-1",
|
||||
payload: {
|
||||
serverId: "srv-1",
|
||||
terminalId: "term-1",
|
||||
cwd: "/repo",
|
||||
workspaceId: "ws-1",
|
||||
reason: "finished",
|
||||
title: "Command finished",
|
||||
body: "zsh",
|
||||
shouldNotify: true,
|
||||
},
|
||||
preferences,
|
||||
sendNotification: recorder.sendNotification,
|
||||
}),
|
||||
).toBe(true);
|
||||
|
||||
expect(recorder.sent.map((item) => item.title)).toEqual(["Agent finished", "Command finished"]);
|
||||
});
|
||||
|
||||
it("blocks all agent and terminal notifications when master enabled is false", () => {
|
||||
const recorder = createNotificationRecorder();
|
||||
const attentionNotified = new Map<string, number>();
|
||||
const preferences: NotificationPreferences = {
|
||||
enabled: false,
|
||||
events: {
|
||||
agentPermission: true,
|
||||
agentError: true,
|
||||
agentFinished: true,
|
||||
terminalNeedsInput: true,
|
||||
terminalFinished: true,
|
||||
},
|
||||
plugins: {
|
||||
enabled: true,
|
||||
muted: [],
|
||||
},
|
||||
};
|
||||
|
||||
for (const reason of ["permission", "error", "finished"] as const) {
|
||||
expect(
|
||||
deliverAgentAttentionOsNotification({
|
||||
serverId: "srv-1",
|
||||
params: makeAgentAttentionParams(reason),
|
||||
isActivelyVisible: false,
|
||||
session: undefined,
|
||||
attentionNotified,
|
||||
preferences,
|
||||
sendNotification: recorder.sendNotification,
|
||||
}),
|
||||
).toBe(false);
|
||||
}
|
||||
|
||||
for (const reason of ["needs_input", "finished"] as const) {
|
||||
expect(
|
||||
deliverTerminalAttentionOsNotification({
|
||||
serverId: "srv-1",
|
||||
payload: {
|
||||
serverId: "srv-1",
|
||||
terminalId: "term-1",
|
||||
cwd: "/repo",
|
||||
workspaceId: "ws-1",
|
||||
reason,
|
||||
title: `Terminal ${reason}`,
|
||||
body: "zsh",
|
||||
shouldNotify: true,
|
||||
},
|
||||
preferences,
|
||||
sendNotification: recorder.sendNotification,
|
||||
}),
|
||||
).toBe(false);
|
||||
}
|
||||
|
||||
expect(recorder.sent).toEqual([]);
|
||||
});
|
||||
|
||||
it("filters plugin.notification OS notifications across master, plugin switch, per-plugin mute, and all-builtins-off combinations", () => {
|
||||
const recorder = createNotificationRecorder();
|
||||
const basePayload = {
|
||||
serverId: "srv-1",
|
||||
pluginId: "ci-alerts",
|
||||
notificationId: "notif-1",
|
||||
title: "Build failed",
|
||||
body: "Check logs",
|
||||
open: { type: "screen" as const, screenId: "report", params: { buildId: "42" } },
|
||||
data: { buildId: 42 },
|
||||
shouldNotify: true,
|
||||
};
|
||||
|
||||
// shouldNotify: false -> not delivered
|
||||
expect(
|
||||
deliverPluginOsNotification({
|
||||
serverId: "srv-1",
|
||||
payload: { ...basePayload, shouldNotify: false },
|
||||
preferences: DEFAULT_NOTIFICATION_PREFERENCES,
|
||||
sendNotification: recorder.sendNotification,
|
||||
}),
|
||||
).toBe(false);
|
||||
|
||||
// Master off -> blocks plugin notification
|
||||
expect(
|
||||
deliverPluginOsNotification({
|
||||
serverId: "srv-1",
|
||||
payload: basePayload,
|
||||
preferences: { ...DEFAULT_NOTIFICATION_PREFERENCES, enabled: false },
|
||||
sendNotification: recorder.sendNotification,
|
||||
}),
|
||||
).toBe(false);
|
||||
|
||||
// Plugins switch off -> blocks plugin notification
|
||||
expect(
|
||||
deliverPluginOsNotification({
|
||||
serverId: "srv-1",
|
||||
payload: basePayload,
|
||||
preferences: {
|
||||
...DEFAULT_NOTIFICATION_PREFERENCES,
|
||||
plugins: { enabled: false, muted: [] },
|
||||
},
|
||||
sendNotification: recorder.sendNotification,
|
||||
}),
|
||||
).toBe(false);
|
||||
|
||||
// Per-plugin mute -> blocks muted plugin while allowing unmuted plugin
|
||||
const mutedPreferences: NotificationPreferences = {
|
||||
...DEFAULT_NOTIFICATION_PREFERENCES,
|
||||
plugins: {
|
||||
enabled: true,
|
||||
muted: ["ci-alerts"],
|
||||
},
|
||||
};
|
||||
expect(
|
||||
deliverPluginOsNotification({
|
||||
serverId: "srv-1",
|
||||
payload: basePayload,
|
||||
preferences: mutedPreferences,
|
||||
sendNotification: recorder.sendNotification,
|
||||
}),
|
||||
).toBe(false);
|
||||
expect(
|
||||
deliverPluginOsNotification({
|
||||
serverId: "srv-1",
|
||||
payload: { ...basePayload, pluginId: "deploy-watch", notificationId: "notif-2" },
|
||||
preferences: mutedPreferences,
|
||||
sendNotification: recorder.sendNotification,
|
||||
}),
|
||||
).toBe(true);
|
||||
|
||||
// All built-in events off + plugins on -> delivers plugin notification
|
||||
const onlyPluginsPreferences: NotificationPreferences = {
|
||||
enabled: true,
|
||||
events: {
|
||||
agentPermission: false,
|
||||
agentError: false,
|
||||
agentFinished: false,
|
||||
terminalNeedsInput: false,
|
||||
terminalFinished: false,
|
||||
},
|
||||
plugins: {
|
||||
enabled: true,
|
||||
muted: [],
|
||||
},
|
||||
};
|
||||
expect(
|
||||
deliverPluginOsNotification({
|
||||
serverId: "srv-1",
|
||||
payload: basePayload,
|
||||
preferences: onlyPluginsPreferences,
|
||||
sendNotification: recorder.sendNotification,
|
||||
}),
|
||||
).toBe(true);
|
||||
|
||||
expect(recorder.sent).toEqual([
|
||||
{
|
||||
title: "Build failed",
|
||||
body: "Check logs",
|
||||
data: {
|
||||
kind: "plugin",
|
||||
serverId: "srv-1",
|
||||
pluginId: "deploy-watch",
|
||||
notificationId: "notif-2",
|
||||
open: { type: "screen", screenId: "report", params: { buildId: "42" } },
|
||||
data: { buildId: 42 },
|
||||
},
|
||||
},
|
||||
{
|
||||
title: "Build failed",
|
||||
body: "Check logs",
|
||||
data: {
|
||||
kind: "plugin",
|
||||
serverId: "srv-1",
|
||||
pluginId: "ci-alerts",
|
||||
notificationId: "notif-1",
|
||||
open: { type: "screen", screenId: "report", params: { buildId: "42" } },
|
||||
data: { buildId: 42 },
|
||||
},
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,235 @@
|
||||
import {
|
||||
buildAgentAttentionNotificationPayload,
|
||||
type AgentAttentionNotificationPayload,
|
||||
type AgentAttentionReason,
|
||||
type NotificationPermissionRequest,
|
||||
} from "@getpaseo/protocol/agent-attention-notification";
|
||||
import type { SessionOutboundMessage } from "@getpaseo/protocol/messages";
|
||||
import {
|
||||
normalizeNotificationPreferences,
|
||||
shouldDeliverNotification,
|
||||
type NotificationPreferences,
|
||||
} from "@getpaseo/protocol/notification-preferences";
|
||||
import type { QueryClient } from "@tanstack/react-query";
|
||||
import { APP_SETTINGS_QUERY_KEY, type AppSettings } from "@/hooks/use-settings/storage";
|
||||
import type { SessionState } from "@/stores/session-store";
|
||||
import type { StreamItem } from "@/types/stream";
|
||||
import { getIsAppActivelyVisible } from "@/utils/app-visibility";
|
||||
|
||||
type TerminalAttentionPayload = Extract<
|
||||
SessionOutboundMessage,
|
||||
{ type: "terminal_attention_required" }
|
||||
>["payload"];
|
||||
|
||||
type PluginNotificationPayload = Extract<
|
||||
SessionOutboundMessage,
|
||||
{ type: "plugin.notification" }
|
||||
>["payload"];
|
||||
|
||||
export type OsNotificationSender = (payload: {
|
||||
title: string;
|
||||
body?: string;
|
||||
data?: Record<string, unknown>;
|
||||
}) => Promise<boolean>;
|
||||
|
||||
export function getCurrentNotificationPreferences(
|
||||
queryClient: Pick<QueryClient, "getQueryData">,
|
||||
): NotificationPreferences {
|
||||
return normalizeNotificationPreferences(
|
||||
queryClient.getQueryData<AppSettings>(APP_SETTINGS_QUERY_KEY)?.notifications,
|
||||
);
|
||||
}
|
||||
|
||||
const findLatestAssistantMessageText = (items: StreamItem[]): string | null => {
|
||||
for (let i = items.length - 1; i >= 0; i -= 1) {
|
||||
const item = items[i];
|
||||
if (item.kind === "assistant_message") {
|
||||
return item.text;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
const getLatestPermissionRequest = (
|
||||
session: SessionState | undefined,
|
||||
agentId: string,
|
||||
): NotificationPermissionRequest | null => {
|
||||
if (!session) {
|
||||
return null;
|
||||
}
|
||||
|
||||
let latest: NotificationPermissionRequest | null = null;
|
||||
for (const pending of session.pendingPermissions.values()) {
|
||||
if (pending.agentId === agentId) {
|
||||
latest = pending.request;
|
||||
}
|
||||
}
|
||||
if (latest) {
|
||||
return latest;
|
||||
}
|
||||
|
||||
const agentPending = session.agents.get(agentId)?.pendingPermissions;
|
||||
if (agentPending && agentPending.length > 0) {
|
||||
return agentPending[agentPending.length - 1] as NotificationPermissionRequest;
|
||||
}
|
||||
|
||||
return null;
|
||||
};
|
||||
|
||||
interface AgentAttentionNotificationInput {
|
||||
notification?: AgentAttentionNotificationPayload;
|
||||
reason: AgentAttentionReason;
|
||||
serverId: string;
|
||||
workspaceId: string | undefined;
|
||||
agentId: string;
|
||||
assistantMessage: string | null;
|
||||
permissionRequest: NotificationPermissionRequest | null;
|
||||
}
|
||||
|
||||
export function resolveAgentAttentionNotification(
|
||||
input: AgentAttentionNotificationInput,
|
||||
): AgentAttentionNotificationPayload | null {
|
||||
if (input.notification) {
|
||||
return input.notification.data.workspaceId ? input.notification : null;
|
||||
}
|
||||
if (!input.workspaceId) {
|
||||
return null;
|
||||
}
|
||||
return buildAgentAttentionNotificationPayload({
|
||||
reason: input.reason,
|
||||
serverId: input.serverId,
|
||||
workspaceId: input.workspaceId,
|
||||
agentId: input.agentId,
|
||||
assistantMessage: input.reason === "finished" ? input.assistantMessage : null,
|
||||
permissionRequest: input.reason === "permission" ? input.permissionRequest : null,
|
||||
});
|
||||
}
|
||||
|
||||
export function deliverAgentAttentionOsNotification(input: {
|
||||
serverId: string;
|
||||
params: {
|
||||
agentId: string;
|
||||
reason: "finished" | "error" | "permission";
|
||||
timestamp: string;
|
||||
notification?: AgentAttentionNotificationPayload;
|
||||
};
|
||||
appState?: string;
|
||||
isActivelyVisible?: boolean;
|
||||
session: SessionState | undefined;
|
||||
attentionNotified: Map<string, number>;
|
||||
preferences: NotificationPreferences;
|
||||
sendNotification: OsNotificationSender;
|
||||
}): boolean {
|
||||
const attentionFocusedAgentId = input.session?.focusedAgentId ?? null;
|
||||
const isActivelyVisible =
|
||||
input.isActivelyVisible ?? getIsAppActivelyVisible(input.appState ?? "active");
|
||||
const isAwayFromAgent = !isActivelyVisible || attentionFocusedAgentId !== input.params.agentId;
|
||||
if (!isAwayFromAgent) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (
|
||||
!shouldDeliverNotification(input.preferences, {
|
||||
kind: "agent",
|
||||
reason: input.params.reason,
|
||||
})
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const timestampMs = new Date(input.params.timestamp).getTime();
|
||||
const lastNotified = input.attentionNotified.get(input.params.agentId);
|
||||
if (lastNotified && lastNotified >= timestampMs) {
|
||||
return false;
|
||||
}
|
||||
input.attentionNotified.set(input.params.agentId, timestampMs);
|
||||
|
||||
const head = input.session?.agentStreamHead.get(input.params.agentId) ?? [];
|
||||
const tail = input.session?.agentStreamTail.get(input.params.agentId) ?? [];
|
||||
const assistantMessage =
|
||||
findLatestAssistantMessageText(head) ?? findLatestAssistantMessageText(tail);
|
||||
const permissionRequest = getLatestPermissionRequest(input.session, input.params.agentId);
|
||||
const workspaceId = input.session?.agents?.get(input.params.agentId)?.workspaceId;
|
||||
|
||||
const notification = resolveAgentAttentionNotification({
|
||||
notification: input.params.notification,
|
||||
reason: input.params.reason,
|
||||
serverId: input.serverId,
|
||||
workspaceId,
|
||||
agentId: input.params.agentId,
|
||||
assistantMessage,
|
||||
permissionRequest,
|
||||
});
|
||||
if (!notification) {
|
||||
return false;
|
||||
}
|
||||
|
||||
void input.sendNotification({
|
||||
title: notification.title,
|
||||
body: notification.body,
|
||||
data: notification.data,
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
export function deliverTerminalAttentionOsNotification(input: {
|
||||
serverId: string;
|
||||
payload: TerminalAttentionPayload;
|
||||
preferences: NotificationPreferences;
|
||||
sendNotification: OsNotificationSender;
|
||||
}): boolean {
|
||||
if (!input.payload.shouldNotify) {
|
||||
return false;
|
||||
}
|
||||
if (
|
||||
!shouldDeliverNotification(input.preferences, {
|
||||
kind: "terminal",
|
||||
reason: input.payload.reason,
|
||||
})
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
void input.sendNotification({
|
||||
title: input.payload.title,
|
||||
body: input.payload.body,
|
||||
data: {
|
||||
serverId: input.payload.serverId ?? input.serverId,
|
||||
terminalId: input.payload.terminalId,
|
||||
cwd: input.payload.cwd,
|
||||
...(input.payload.workspaceId ? { workspaceId: input.payload.workspaceId } : {}),
|
||||
},
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
export function deliverPluginOsNotification(input: {
|
||||
serverId: string;
|
||||
payload: PluginNotificationPayload;
|
||||
preferences: NotificationPreferences;
|
||||
sendNotification: OsNotificationSender;
|
||||
}): boolean {
|
||||
if (!input.payload.shouldNotify) {
|
||||
return false;
|
||||
}
|
||||
if (
|
||||
!shouldDeliverNotification(input.preferences, {
|
||||
kind: "plugin",
|
||||
pluginId: input.payload.pluginId,
|
||||
})
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
void input.sendNotification({
|
||||
title: input.payload.title,
|
||||
body: input.payload.body,
|
||||
data: {
|
||||
kind: "plugin",
|
||||
serverId: input.payload.serverId ?? input.serverId,
|
||||
pluginId: input.payload.pluginId,
|
||||
notificationId: input.payload.notificationId,
|
||||
...(input.payload.open ? { open: input.payload.open } : {}),
|
||||
...(input.payload.data ? { data: input.payload.data } : {}),
|
||||
},
|
||||
});
|
||||
return true;
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
import { beforeEach, describe, expect, test } from "vitest";
|
||||
import type { SessionInboundMessage, SessionOutboundMessage } from "@getpaseo/protocol/messages";
|
||||
import { createJSONStorage, type StateStorage } from "zustand/middleware";
|
||||
import { mountBrowserAutomationHandler } from "./handler";
|
||||
import { mountBrowserAutomationHandler, type BrowserAutomationHandlerOptions } from "./handler";
|
||||
import type { DesktopHostBridge } from "@/desktop/host";
|
||||
import { useBrowserStore } from "@/desktop/browser/store";
|
||||
import { findPaneById } from "@/stores/workspace-layout-actions";
|
||||
@@ -107,12 +107,14 @@ class FakeResidentBrowser {
|
||||
browserId: string;
|
||||
workspaceId: string;
|
||||
url: string;
|
||||
partition?: string;
|
||||
}> = [];
|
||||
|
||||
public ensure = (input: {
|
||||
browserId: string;
|
||||
workspaceId: string;
|
||||
url: string;
|
||||
partition?: string;
|
||||
}): HTMLElement | null => {
|
||||
this.ensuredWebviews.push(input);
|
||||
return null;
|
||||
@@ -129,6 +131,8 @@ class BrowserAutomationHandlerHarness {
|
||||
input: {
|
||||
serverId?: string;
|
||||
host?: DesktopHostBridge | null;
|
||||
readHostBrowserRouting?: BrowserAutomationHandlerOptions["readHostBrowserRouting"];
|
||||
prepareHostBrowserPartition?: BrowserAutomationHandlerOptions["prepareHostBrowserPartition"];
|
||||
registrationWaitTimeoutMs?: number;
|
||||
registrationPollIntervalMs?: number;
|
||||
} = {},
|
||||
@@ -138,6 +142,12 @@ class BrowserAutomationHandlerHarness {
|
||||
...(input.serverId ? { serverId: input.serverId } : {}),
|
||||
getHost: () => (input.host === undefined ? { browser: this.browser } : input.host),
|
||||
ensureResidentBrowserWebview: this.resident.ensure,
|
||||
...(input.readHostBrowserRouting
|
||||
? { readHostBrowserRouting: input.readHostBrowserRouting }
|
||||
: {}),
|
||||
...(input.prepareHostBrowserPartition
|
||||
? { prepareHostBrowserPartition: input.prepareHostBrowserPartition }
|
||||
: {}),
|
||||
...(input.registrationWaitTimeoutMs !== undefined
|
||||
? { registrationWaitTimeoutMs: input.registrationWaitTimeoutMs }
|
||||
: {}),
|
||||
@@ -165,7 +175,7 @@ function browserAutomationRequest(): BrowserAutomationExecuteRequest {
|
||||
};
|
||||
}
|
||||
|
||||
function browserNewTabRequest(): BrowserAutomationExecuteRequest {
|
||||
function browserNewTabRequest(input?: { url?: string }): BrowserAutomationExecuteRequest {
|
||||
return {
|
||||
type: "browser.automation.execute.request",
|
||||
requestId: "req-new",
|
||||
@@ -173,7 +183,7 @@ function browserNewTabRequest(): BrowserAutomationExecuteRequest {
|
||||
workspaceId: "wks_workspace_a",
|
||||
command: {
|
||||
command: "new_tab",
|
||||
args: { url: "https://example.com" },
|
||||
args: { url: input?.url ?? "https://example.com" },
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -240,11 +250,14 @@ function currentBrowserTabs() {
|
||||
}));
|
||||
}
|
||||
|
||||
function newTabResultFrom(payload: BrowserAutomationResponsePayload) {
|
||||
function newTabResultFrom(
|
||||
payload: BrowserAutomationResponsePayload,
|
||||
expectedUrl = "https://example.com",
|
||||
) {
|
||||
expect(payload).toMatchObject({
|
||||
requestId: "req-new",
|
||||
ok: true,
|
||||
result: { command: "new_tab", workspaceId: "wks_workspace_a", url: "https://example.com" },
|
||||
result: { command: "new_tab", workspaceId: "wks_workspace_a", url: expectedUrl },
|
||||
});
|
||||
if (!payload.ok || payload.result.command !== "new_tab") {
|
||||
throw new Error("Expected browser_new_tab success payload");
|
||||
@@ -615,4 +628,70 @@ describe("mountBrowserAutomationHandler", () => {
|
||||
expect(browser.browser.executedRequests).toEqual([]);
|
||||
expect(browser.client.sentResponses).toEqual([]);
|
||||
});
|
||||
|
||||
test("remote agent browser_new_tab prepares the host proxy partition and sets routingMode to host", async () => {
|
||||
const browser = new BrowserAutomationHandlerHarness();
|
||||
const preparedServers: string[] = [];
|
||||
browser.mount({
|
||||
serverId: "remote-1",
|
||||
readHostBrowserRouting: () => ({
|
||||
kind: "remote",
|
||||
support: "supported",
|
||||
target: { type: "directTcp", endpoint: "10.0.0.5:6767" },
|
||||
}),
|
||||
prepareHostBrowserPartition: async (serverId) => {
|
||||
preparedServers.push(serverId);
|
||||
return {
|
||||
ok: true,
|
||||
partition: "persist:paseo-browser-host-0123456789abcdef",
|
||||
isRemoteHost: true,
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
browser.receive(browserNewTabRequest({ url: "http://localhost:5173" }));
|
||||
await flushAsyncWork();
|
||||
|
||||
const result = newTabResultFrom(browser.client.payloadAt(0), "http://localhost:5173");
|
||||
expect(preparedServers).toEqual(["remote-1"]);
|
||||
expect(useBrowserStore.getState().browsersById[result.browserId]?.routingMode).toBe("host");
|
||||
expect(browser.resident.ensuredWebviews).toEqual([
|
||||
{
|
||||
browserId: result.browserId,
|
||||
workspaceId: "wks_workspace_a",
|
||||
url: "http://localhost:5173",
|
||||
partition: "persist:paseo-browser-host-0123456789abcdef",
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
test("remote agent browser_new_tab fails closed without creating a webview when host proxy cannot prepare", async () => {
|
||||
const browser = new BrowserAutomationHandlerHarness();
|
||||
browser.mount({
|
||||
serverId: "remote-old",
|
||||
readHostBrowserRouting: () => ({
|
||||
kind: "remote",
|
||||
support: "daemon_update_required",
|
||||
}),
|
||||
prepareHostBrowserPartition: async () => ({
|
||||
ok: false,
|
||||
reason: "daemon_update_required",
|
||||
message: "Update this host daemon to browse through the host proxy.",
|
||||
}),
|
||||
});
|
||||
|
||||
browser.receive(browserNewTabRequest({ url: "http://localhost:5173" }));
|
||||
await flushAsyncWork();
|
||||
|
||||
expect(browser.resident.ensuredWebviews).toEqual([]);
|
||||
expect(browser.client.payloadAt(0)).toEqual({
|
||||
requestId: "req-new",
|
||||
ok: false,
|
||||
error: {
|
||||
code: "browser_unsupported",
|
||||
message: "Update this host daemon to browse through the host proxy.",
|
||||
retryable: false,
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -7,6 +7,11 @@ import {
|
||||
removeResidentBrowserWebview,
|
||||
resizeResidentBrowserWebview,
|
||||
} from "@/desktop/browser/resident-webviews";
|
||||
import {
|
||||
installBrowserProxyRendererBridge,
|
||||
prepareHostBrowserPartition as prepareHostBrowserPartitionDefault,
|
||||
readHostBrowserRouting as readHostBrowserRoutingDefault,
|
||||
} from "@/desktop/browser/proxy";
|
||||
import {
|
||||
createFixedBrowserViewport,
|
||||
createWorkspaceBrowser,
|
||||
@@ -42,6 +47,8 @@ export interface BrowserAutomationHandlerOptions {
|
||||
serverId?: string;
|
||||
getHost?: () => DesktopHostBridge | null;
|
||||
ensureResidentBrowserWebview?: typeof ensureResidentBrowserWebviewDefault;
|
||||
readHostBrowserRouting?: typeof readHostBrowserRoutingDefault;
|
||||
prepareHostBrowserPartition?: typeof prepareHostBrowserPartitionDefault;
|
||||
registrationWaitTimeoutMs?: number;
|
||||
registrationPollIntervalMs?: number;
|
||||
}
|
||||
@@ -49,6 +56,7 @@ export interface BrowserAutomationHandlerOptions {
|
||||
export function mountBrowserAutomationHandler(
|
||||
options: BrowserAutomationHandlerOptions,
|
||||
): () => void {
|
||||
installBrowserProxyRendererBridge();
|
||||
const getHost = options.getHost ?? getDesktopHost;
|
||||
const unsubscribe = options.client.on("browser.automation.execute.request", (request) => {
|
||||
void handleBrowserAutomationRequest({
|
||||
@@ -58,6 +66,9 @@ export function mountBrowserAutomationHandler(
|
||||
serverId: options.serverId,
|
||||
ensureResidentBrowserWebview:
|
||||
options.ensureResidentBrowserWebview ?? ensureResidentBrowserWebviewDefault,
|
||||
readHostBrowserRouting: options.readHostBrowserRouting ?? readHostBrowserRoutingDefault,
|
||||
prepareHostBrowserPartition:
|
||||
options.prepareHostBrowserPartition ?? prepareHostBrowserPartitionDefault,
|
||||
...(options.registrationWaitTimeoutMs !== undefined
|
||||
? { registrationWaitTimeoutMs: options.registrationWaitTimeoutMs }
|
||||
: {}),
|
||||
@@ -117,6 +128,8 @@ async function handleBrowserAutomationRequest(params: {
|
||||
request: BrowserAutomationExecuteRequest;
|
||||
serverId?: string;
|
||||
ensureResidentBrowserWebview: typeof ensureResidentBrowserWebviewDefault;
|
||||
readHostBrowserRouting: typeof readHostBrowserRoutingDefault;
|
||||
prepareHostBrowserPartition: typeof prepareHostBrowserPartitionDefault;
|
||||
registrationWaitTimeoutMs?: number;
|
||||
registrationPollIntervalMs?: number;
|
||||
}): Promise<void> {
|
||||
@@ -126,6 +139,8 @@ async function handleBrowserAutomationRequest(params: {
|
||||
request,
|
||||
serverId,
|
||||
ensureResidentBrowserWebview,
|
||||
readHostBrowserRouting,
|
||||
prepareHostBrowserPartition,
|
||||
registrationWaitTimeoutMs,
|
||||
registrationPollIntervalMs,
|
||||
} = params;
|
||||
@@ -141,6 +156,8 @@ async function handleBrowserAutomationRequest(params: {
|
||||
serverId,
|
||||
browserHost,
|
||||
ensureResidentBrowserWebview,
|
||||
readHostBrowserRouting,
|
||||
prepareHostBrowserPartition,
|
||||
...(registrationWaitTimeoutMs !== undefined ? { registrationWaitTimeoutMs } : {}),
|
||||
...(registrationPollIntervalMs !== undefined ? { registrationPollIntervalMs } : {}),
|
||||
}),
|
||||
@@ -335,6 +352,8 @@ async function openBrowserTabForRequest(params: {
|
||||
serverId?: string;
|
||||
browserHost: DesktopHostBridge["browser"] | undefined;
|
||||
ensureResidentBrowserWebview: typeof ensureResidentBrowserWebviewDefault;
|
||||
readHostBrowserRouting: typeof readHostBrowserRoutingDefault;
|
||||
prepareHostBrowserPartition: typeof prepareHostBrowserPartitionDefault;
|
||||
registrationWaitTimeoutMs?: number;
|
||||
registrationPollIntervalMs?: number;
|
||||
}): Promise<BrowserAutomationResponsePayload> {
|
||||
@@ -343,6 +362,8 @@ async function openBrowserTabForRequest(params: {
|
||||
serverId,
|
||||
browserHost,
|
||||
ensureResidentBrowserWebview,
|
||||
readHostBrowserRouting,
|
||||
prepareHostBrowserPartition,
|
||||
registrationWaitTimeoutMs,
|
||||
registrationPollIntervalMs,
|
||||
} = params;
|
||||
@@ -359,8 +380,27 @@ async function openBrowserTabForRequest(params: {
|
||||
});
|
||||
}
|
||||
|
||||
const hostRouting = readHostBrowserRouting(serverId);
|
||||
let targetPartition: string | undefined;
|
||||
let routingMode: "host" | "local" | undefined;
|
||||
if (hostRouting.kind === "remote") {
|
||||
const prepared = await prepareHostBrowserPartition(serverId);
|
||||
if (!prepared.ok) {
|
||||
return browserAutomationFailure({
|
||||
requestId: request.requestId,
|
||||
code: "browser_unsupported",
|
||||
message: prepared.message,
|
||||
});
|
||||
}
|
||||
targetPartition = prepared.partition;
|
||||
routingMode = "host";
|
||||
}
|
||||
|
||||
const url = command.args.url ?? "https://example.com";
|
||||
const { browserId, url: normalizedUrl } = createWorkspaceBrowser({ initialUrl: url });
|
||||
const { browserId, url: normalizedUrl } = createWorkspaceBrowser({
|
||||
initialUrl: url,
|
||||
routingMode,
|
||||
});
|
||||
const workspaceKey = buildWorkspaceTabPersistenceKey({ serverId, workspaceId });
|
||||
if (!workspaceKey) {
|
||||
return browserAutomationFailure({
|
||||
@@ -376,7 +416,12 @@ async function openBrowserTabForRequest(params: {
|
||||
});
|
||||
|
||||
if (browserHost?.executeAutomationCommand) {
|
||||
ensureResidentBrowserWebview({ browserId, workspaceId, url: normalizedUrl });
|
||||
ensureResidentBrowserWebview({
|
||||
browserId,
|
||||
workspaceId,
|
||||
url: normalizedUrl,
|
||||
...(targetPartition ? { partition: targetPartition } : {}),
|
||||
});
|
||||
const registered = await waitForBrowserRegistration({
|
||||
request,
|
||||
browserId,
|
||||
|
||||
@@ -10,7 +10,14 @@ import {
|
||||
createElement,
|
||||
} from "react";
|
||||
import { createPortal } from "react-dom";
|
||||
import { Pressable, Text, View, type StyleProp, type ViewStyle } from "react-native";
|
||||
import {
|
||||
Pressable,
|
||||
Text,
|
||||
View,
|
||||
type PressableStateCallbackType,
|
||||
type StyleProp,
|
||||
type ViewStyle,
|
||||
} from "react-native";
|
||||
import {
|
||||
EditingTextInput as TextInput,
|
||||
type EditingTextInputHandle,
|
||||
@@ -33,7 +40,9 @@ import {
|
||||
import { StyleSheet, useUnistyles, withUnistyles } from "react-native-unistyles";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import * as Clipboard from "expo-clipboard";
|
||||
import { Alert } from "@/components/ui/alert";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { LoadingSpinner } from "@/components/ui/loading-spinner";
|
||||
import { useRetainedPanelActive } from "@/components/retained-panel";
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
|
||||
import { useToast } from "@/contexts/toast-context";
|
||||
@@ -51,7 +60,12 @@ import {
|
||||
import type { AttachmentMetadata, BrowserElementAttachment } from "@/attachments/types";
|
||||
import { persistAttachmentFromDataUrl } from "@/attachments/service";
|
||||
import { WORKSPACE_SECONDARY_HEADER_HEIGHT } from "@/constants/layout";
|
||||
import { defaultHostAppearance, resolveHostIcon } from "@/hosts/appearance";
|
||||
import { HostIconGlyph } from "@/hosts/host-icon-glyph";
|
||||
import { getOverlayRoot } from "@/lib/overlay-root";
|
||||
import { useHosts } from "@/runtime/host-runtime";
|
||||
import { useSessionStore } from "@/stores/session-store";
|
||||
import { STATUS_INDICATOR_FILLED_DOT_SIZE } from "@/utils/status-indicator-geometry";
|
||||
import {
|
||||
getDesktopHost,
|
||||
isElectronRuntime,
|
||||
@@ -66,6 +80,7 @@ import {
|
||||
} from "@/desktop/browser/store";
|
||||
import {
|
||||
applyInactiveBrowserWebviewViewport,
|
||||
getResidentBrowserWebviewPartition,
|
||||
prepareBrowserWebview,
|
||||
presentBrowserWebview,
|
||||
rememberBrowserWebviewSize,
|
||||
@@ -73,6 +88,7 @@ import {
|
||||
removeResidentBrowserWebview,
|
||||
takeResidentBrowserWebview,
|
||||
} from "../resident-webviews";
|
||||
import { useHostBrowserProxy, type BrowserProxyPaneState } from "../proxy";
|
||||
import {
|
||||
createElementSelectorController,
|
||||
type BrowserElementSelection,
|
||||
@@ -476,10 +492,211 @@ const ThemedSmartphone = withUnistyles(Smartphone);
|
||||
const ThemedTablet = withUnistyles(Tablet);
|
||||
const ThemedMonitor = withUnistyles(Monitor);
|
||||
const ThemedChevronDown = withUnistyles(ChevronDown);
|
||||
const ThemedLoadingSpinner = withUnistyles(LoadingSpinner);
|
||||
const deviceMutedIconMapping = (theme: { colors: { foregroundMuted: string } }) => ({
|
||||
color: theme.colors.foregroundMuted,
|
||||
});
|
||||
|
||||
function BrowserRoutingButton({
|
||||
serverId,
|
||||
state,
|
||||
style,
|
||||
onToggle,
|
||||
}: {
|
||||
serverId: string;
|
||||
state: BrowserProxyPaneState;
|
||||
style: (state: { hovered?: boolean; pressed?: boolean }) => StyleProp<ViewStyle>;
|
||||
onToggle: () => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const hosts = useHosts();
|
||||
const host = useMemo(
|
||||
() => hosts.find((entry) => entry.serverId === serverId) ?? null,
|
||||
[hosts, serverId],
|
||||
);
|
||||
const detectedMachineKind = useSessionStore(
|
||||
(store) => store.sessions[serverId]?.serverInfo?.machineKind ?? null,
|
||||
);
|
||||
const hostIcon = useMemo(
|
||||
() =>
|
||||
resolveHostIcon({
|
||||
appearance: host?.appearance ?? defaultHostAppearance(),
|
||||
detectedMachineKind,
|
||||
}),
|
||||
[detectedMachineKind, host?.appearance],
|
||||
);
|
||||
const hostColor = host?.appearance.color ?? "none";
|
||||
|
||||
const isHostRouted = state.effectiveRoutingMode === "host";
|
||||
const tooltipText = isHostRouted
|
||||
? t("workspace.browser.routing.tooltipHost", { hostName: state.hostLabel })
|
||||
: t("workspace.browser.routing.tooltipLocal", { hostName: state.hostLabel });
|
||||
const accessibilityLabel = isHostRouted
|
||||
? t("workspace.browser.routing.switchToLocal", { hostName: state.hostLabel })
|
||||
: t("workspace.browser.routing.switchToHost", { hostName: state.hostLabel });
|
||||
const accessibilityState = useMemo(() => ({ selected: isHostRouted }), [isHostRouted]);
|
||||
|
||||
let dotStyle = styles.routingDotPending;
|
||||
if (state.kind === "ready" && state.proxyStatus === "ready") {
|
||||
dotStyle = styles.routingDotReady;
|
||||
} else if (
|
||||
state.kind === "proxy_error" ||
|
||||
(state.kind === "ready" && state.proxyStatus === "error")
|
||||
) {
|
||||
dotStyle = styles.routingDotError;
|
||||
}
|
||||
|
||||
return (
|
||||
<Tooltip delayDuration={0} enabledOnDesktop enabledOnMobile={false}>
|
||||
<TooltipTrigger asChild>
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={accessibilityLabel}
|
||||
accessibilityState={accessibilityState}
|
||||
onPress={onToggle}
|
||||
style={style}
|
||||
testID="browser-routing-pill"
|
||||
>
|
||||
{({ hovered, pressed }: PressableStateCallbackType & { hovered?: boolean }) =>
|
||||
isHostRouted ? (
|
||||
<View style={styles.routingIconFrame}>
|
||||
<HostIconGlyph icon={hostIcon} color={hostColor} size={16} />
|
||||
<View
|
||||
style={[
|
||||
styles.routingDotHalo,
|
||||
hovered || pressed ? styles.routingDotHaloHovered : styles.routingDotHaloRest,
|
||||
]}
|
||||
>
|
||||
<View style={[styles.routingDot, dotStyle]} />
|
||||
</View>
|
||||
</View>
|
||||
) : (
|
||||
<ThemedMonitor size={16} uniProps={deviceMutedIconMapping} />
|
||||
)
|
||||
}
|
||||
</Pressable>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="bottom" align="center" offset={8}>
|
||||
<Text style={styles.toolbarTooltipText}>{tooltipText}</Text>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
|
||||
function BrowserProxyStatusPanel({
|
||||
state,
|
||||
onBrowseLocally,
|
||||
}: {
|
||||
state: Exclude<BrowserProxyPaneState, { kind: "ready" }>;
|
||||
onBrowseLocally: () => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
if (state.kind === "connecting") {
|
||||
const label = state.isReconnecting
|
||||
? t("workspace.browser.proxy.reconnecting", { hostName: state.hostLabel })
|
||||
: t("workspace.browser.proxy.connecting", { hostName: state.hostLabel });
|
||||
return (
|
||||
<View style={styles.proxyStatusContainer} testID="browser-proxy-status">
|
||||
<View style={styles.proxyConnectingCard}>
|
||||
<View style={styles.proxyConnectingRow}>
|
||||
<ThemedLoadingSpinner size={16} uniProps={deviceMutedIconMapping} />
|
||||
<Text style={styles.proxyConnectingText}>{label}</Text>
|
||||
</View>
|
||||
<Button variant="outline" onPress={onBrowseLocally} testID="browser-proxy-browse-locally">
|
||||
{t("workspace.browser.proxy.browseLocally")}
|
||||
</Button>
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
if (state.kind === "daemon_update_required") {
|
||||
return (
|
||||
<View style={styles.proxyStatusContainer} testID="browser-proxy-status">
|
||||
<View style={styles.proxyAlertFrame}>
|
||||
<Alert
|
||||
variant="warning"
|
||||
title={t("workspace.browser.proxy.updateTitle", { hostName: state.hostLabel })}
|
||||
description={t("workspace.browser.proxy.updateDescription")}
|
||||
>
|
||||
<Button
|
||||
variant="outline"
|
||||
onPress={onBrowseLocally}
|
||||
testID="browser-proxy-browse-locally"
|
||||
>
|
||||
{t("workspace.browser.proxy.browseLocally")}
|
||||
</Button>
|
||||
</Alert>
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
if (state.kind === "routed_unsupported") {
|
||||
return (
|
||||
<View style={styles.proxyStatusContainer} testID="browser-proxy-status">
|
||||
<View style={styles.proxyAlertFrame}>
|
||||
<Alert
|
||||
variant="info"
|
||||
title={t("workspace.browser.proxy.routedTitle")}
|
||||
description={t("workspace.browser.proxy.routedDescription")}
|
||||
>
|
||||
<Button
|
||||
variant="outline"
|
||||
onPress={onBrowseLocally}
|
||||
testID="browser-proxy-browse-locally"
|
||||
>
|
||||
{t("workspace.browser.proxy.browseLocally")}
|
||||
</Button>
|
||||
</Alert>
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
if (state.kind === "host_offline") {
|
||||
return (
|
||||
<View style={styles.proxyStatusContainer} testID="browser-proxy-status">
|
||||
<View style={styles.proxyAlertFrame}>
|
||||
<Alert
|
||||
variant="warning"
|
||||
title={t("workspace.browser.proxy.offlineTitle", { hostName: state.hostLabel })}
|
||||
description={t("workspace.browser.proxy.offlineDescription")}
|
||||
>
|
||||
<Button
|
||||
variant="outline"
|
||||
onPress={onBrowseLocally}
|
||||
testID="browser-proxy-browse-locally"
|
||||
>
|
||||
{t("workspace.browser.proxy.browseLocally")}
|
||||
</Button>
|
||||
</Alert>
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<View style={styles.proxyStatusContainer} testID="browser-proxy-status">
|
||||
<View style={styles.proxyAlertFrame}>
|
||||
<Alert
|
||||
variant="error"
|
||||
title={t("workspace.browser.proxy.errorTitle")}
|
||||
description={state.message}
|
||||
>
|
||||
<Button variant="secondary" onPress={state.retry} testID="browser-proxy-retry">
|
||||
{t("common.actions.retry")}
|
||||
</Button>
|
||||
<Button variant="outline" onPress={onBrowseLocally} testID="browser-proxy-browse-locally">
|
||||
{t("workspace.browser.proxy.browseLocally")}
|
||||
</Button>
|
||||
</Alert>
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function resolveThemedDeviceIcon(icon: LucideIcon): typeof ThemedMaximize {
|
||||
if (icon === Smartphone) return ThemedSmartphone;
|
||||
if (icon === Tablet) return ThemedTablet;
|
||||
@@ -573,6 +790,32 @@ function deviceSizeIdForViewport(viewport: BrowserViewport): DeviceSizeId | null
|
||||
);
|
||||
}
|
||||
|
||||
function acquirePartitionedWebview(input: {
|
||||
browserId: string;
|
||||
workspaceId: string;
|
||||
partition: string;
|
||||
initialUrl: string;
|
||||
}): ElectronWebview {
|
||||
const existingResident = takeResidentBrowserWebview(input.browserId) as ElectronWebview | null;
|
||||
if (
|
||||
existingResident &&
|
||||
getResidentBrowserWebviewPartition(existingResident) === input.partition
|
||||
) {
|
||||
return existingResident;
|
||||
}
|
||||
if (existingResident) {
|
||||
removeResidentBrowserWebview(input.browserId);
|
||||
}
|
||||
const webview = document.createElement("webview") as ElectronWebview;
|
||||
prepareBrowserWebview(webview, {
|
||||
browserId: input.browserId,
|
||||
workspaceId: input.workspaceId,
|
||||
initialUrl: input.initialUrl,
|
||||
partition: input.partition,
|
||||
});
|
||||
return webview;
|
||||
}
|
||||
|
||||
function rememberResolvedBrowserWebviewSize(browserId: string, webview: HTMLElement): void {
|
||||
const bounds = webview.getBoundingClientRect();
|
||||
rememberBrowserWebviewSize({ browserId, width: bounds.width, height: bounds.height });
|
||||
@@ -599,6 +842,9 @@ export function BrowserPane({
|
||||
const browser = useBrowserStore((state) => state.browsersById[browserId] ?? null);
|
||||
const updateBrowser = useBrowserStore((state) => state.updateBrowser);
|
||||
const setBrowserViewport = useBrowserStore((state) => state.setBrowserViewport);
|
||||
const setBrowserRoutingMode = useBrowserStore((state) => state.setBrowserRoutingMode);
|
||||
const proxyState = useHostBrowserProxy({ serverId, routingMode: browser?.routingMode });
|
||||
const activePartition = proxyState.kind === "ready" ? proxyState.partition : null;
|
||||
const browserViewport = browser?.viewport ?? RESPONSIVE_BROWSER_VIEWPORT;
|
||||
const browserViewportRef = useRef(browserViewport);
|
||||
browserViewportRef.current = browserViewport;
|
||||
@@ -726,26 +972,32 @@ export function BrowserPane({
|
||||
|
||||
const host = webviewHostRef.current;
|
||||
const clip = webviewClipRef.current;
|
||||
|
||||
if (!activePartition) {
|
||||
host?.replaceChildren();
|
||||
removeResidentBrowserWebview(browserId);
|
||||
webviewRef.current = null;
|
||||
return;
|
||||
}
|
||||
|
||||
if (!host || !clip) {
|
||||
return;
|
||||
}
|
||||
|
||||
host.replaceChildren();
|
||||
|
||||
const currentUrl = browserRef.current?.url ?? initialUrlRef.current;
|
||||
const initialUnsafeNavigationMessage = getUnsafeNavigationMessage(
|
||||
initialUrlRef.current,
|
||||
currentUrl,
|
||||
browserErrorLabelsRef.current,
|
||||
);
|
||||
const residentWebview = takeResidentBrowserWebview(browserId) as ElectronWebview | null;
|
||||
const webview = residentWebview ?? (document.createElement("webview") as ElectronWebview);
|
||||
const webview = acquirePartitionedWebview({
|
||||
browserId,
|
||||
workspaceId,
|
||||
partition: activePartition,
|
||||
initialUrl: initialUnsafeNavigationMessage ? "about:blank" : currentUrl,
|
||||
});
|
||||
webviewRef.current = webview;
|
||||
if (!residentWebview) {
|
||||
prepareBrowserWebview(webview, {
|
||||
browserId,
|
||||
workspaceId,
|
||||
initialUrl: initialUnsafeNavigationMessage ? "about:blank" : initialUrlRef.current,
|
||||
});
|
||||
}
|
||||
releaseResidentBrowserWebview(browserId, webview);
|
||||
if (isPresentedRef.current) {
|
||||
presentBrowserWebview(browserId, webview, host, clip, browserViewportRef.current);
|
||||
@@ -907,7 +1159,7 @@ export function BrowserPane({
|
||||
}
|
||||
};
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [browserId, onFocusPane]);
|
||||
}, [activePartition, browserId, onFocusPane, workspaceId]);
|
||||
|
||||
useEffect(() => {
|
||||
const webview = webviewRef.current;
|
||||
@@ -1415,6 +1667,18 @@ export function BrowserPane({
|
||||
[isResponsiveDevice],
|
||||
);
|
||||
|
||||
const handleToggleRoutingMode = useCallback(() => {
|
||||
if (!proxyState.isRemoteHost) {
|
||||
return;
|
||||
}
|
||||
const nextMode = proxyState.effectiveRoutingMode === "host" ? "local" : "host";
|
||||
setBrowserRoutingMode(browserId, nextMode);
|
||||
}, [browserId, proxyState.effectiveRoutingMode, proxyState.isRemoteHost, setBrowserRoutingMode]);
|
||||
|
||||
const handleBrowseLocally = useCallback(() => {
|
||||
setBrowserRoutingMode(browserId, "local");
|
||||
}, [browserId, setBrowserRoutingMode]);
|
||||
|
||||
const setWebviewHostNode = useCallback((node: HTMLDivElement | null) => {
|
||||
webviewHostRef.current = node;
|
||||
}, []);
|
||||
@@ -1464,6 +1728,14 @@ export function BrowserPane({
|
||||
<RotateCw size={16} color={theme.colors.foregroundMuted} />
|
||||
</ToolbarButton>
|
||||
</View>
|
||||
{proxyState.isRemoteHost ? (
|
||||
<BrowserRoutingButton
|
||||
serverId={serverId}
|
||||
state={proxyState}
|
||||
style={baseIconButtonStyle}
|
||||
onToggle={handleToggleRoutingMode}
|
||||
/>
|
||||
) : null}
|
||||
<View style={styles.urlBarWrap}>
|
||||
<TextInput
|
||||
accessibilityLabel={t("workspace.browser.controls.browserUrl")}
|
||||
@@ -1540,18 +1812,24 @@ export function BrowserPane({
|
||||
style={webviewWrapStyle}
|
||||
testID={`browser-webview-clip-${browserId}`}
|
||||
>
|
||||
{createElement("div", {
|
||||
ref: setWebviewHostNode,
|
||||
style: webviewHostStyle,
|
||||
})}
|
||||
{pendingSelection ? (
|
||||
<BrowserElementAnnotationCard
|
||||
anchor={webviewClipRef.current}
|
||||
selection={pendingSelection}
|
||||
onSubmit={submitAnnotation}
|
||||
onCancel={cancelAnnotation}
|
||||
/>
|
||||
) : null}
|
||||
{proxyState.kind === "ready" ? (
|
||||
<>
|
||||
{createElement("div", {
|
||||
ref: setWebviewHostNode,
|
||||
style: webviewHostStyle,
|
||||
})}
|
||||
{pendingSelection ? (
|
||||
<BrowserElementAnnotationCard
|
||||
anchor={webviewClipRef.current}
|
||||
selection={pendingSelection}
|
||||
onSubmit={submitAnnotation}
|
||||
onCancel={cancelAnnotation}
|
||||
/>
|
||||
) : null}
|
||||
</>
|
||||
) : (
|
||||
<BrowserProxyStatusPanel state={proxyState} onBrowseLocally={handleBrowseLocally} />
|
||||
)}
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
@@ -1853,4 +2131,65 @@ const styles = StyleSheet.create((theme) => ({
|
||||
unavailableSubtitle: {
|
||||
fontSize: theme.fontSize.sm,
|
||||
},
|
||||
routingIconFrame: {
|
||||
position: "relative",
|
||||
width: 18,
|
||||
height: 18,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
},
|
||||
routingDotHalo: {
|
||||
position: "absolute",
|
||||
right: -2,
|
||||
bottom: -2,
|
||||
width: STATUS_INDICATOR_FILLED_DOT_SIZE + 3,
|
||||
height: STATUS_INDICATOR_FILLED_DOT_SIZE + 3,
|
||||
borderRadius: theme.borderRadius.full,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
},
|
||||
routingDotHaloRest: {
|
||||
backgroundColor: theme.colors.surface0,
|
||||
},
|
||||
routingDotHaloHovered: {
|
||||
backgroundColor: theme.colors.surface2,
|
||||
},
|
||||
routingDot: {
|
||||
width: STATUS_INDICATOR_FILLED_DOT_SIZE,
|
||||
height: STATUS_INDICATOR_FILLED_DOT_SIZE,
|
||||
borderRadius: theme.borderRadius.full,
|
||||
},
|
||||
routingDotReady: {
|
||||
backgroundColor: theme.colors.statusDotSuccess,
|
||||
},
|
||||
routingDotPending: {
|
||||
backgroundColor: theme.colors.statusDotWarning,
|
||||
},
|
||||
routingDotError: {
|
||||
backgroundColor: theme.colors.statusDotDanger,
|
||||
},
|
||||
proxyStatusContainer: {
|
||||
flex: 1,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
padding: theme.spacing[6],
|
||||
backgroundColor: theme.colors.surface0,
|
||||
},
|
||||
proxyConnectingCard: {
|
||||
alignItems: "center",
|
||||
gap: theme.spacing[3],
|
||||
},
|
||||
proxyConnectingRow: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: theme.spacing[2],
|
||||
},
|
||||
proxyConnectingText: {
|
||||
fontSize: theme.fontSize.base,
|
||||
color: theme.colors.foregroundMuted,
|
||||
},
|
||||
proxyAlertFrame: {
|
||||
width: "100%",
|
||||
maxWidth: 420,
|
||||
},
|
||||
}));
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
export {
|
||||
classifyHostBrowserRouting,
|
||||
extractBrowserProxyTarget,
|
||||
isLocalHostConnection,
|
||||
isLoopbackBrowserUrl,
|
||||
isLoopbackHost,
|
||||
shouldOpenUrlInProxiedWorkspaceBrowser,
|
||||
type ClassifyHostBrowserRoutingInput,
|
||||
type HostBrowserRouting,
|
||||
} from "./internal/classify";
|
||||
export {
|
||||
ensureHostBrowserProxy,
|
||||
installBrowserProxyRendererBridge,
|
||||
prepareHostBrowserPartition,
|
||||
readHostBrowserRouting,
|
||||
shouldRouteWorkspaceUrlToProxiedBrowser,
|
||||
type PrepareHostBrowserPartitionResult,
|
||||
} from "./internal/bridge";
|
||||
export { useHostBrowserProxy, type BrowserProxyPaneState } from "./internal/use-host-browser-proxy";
|
||||
@@ -0,0 +1,307 @@
|
||||
import { getIsElectron } from "@/constants/platform";
|
||||
import {
|
||||
getDesktopHost,
|
||||
type DesktopBrowserProxyStatusSnapshot,
|
||||
type DesktopBrowserProxyTicketRequestEvent,
|
||||
} from "@/desktop/host";
|
||||
import { i18n } from "@/i18n/i18next";
|
||||
import { getHostRuntimeStore } from "@/runtime/host-runtime";
|
||||
import { useSessionStore } from "@/stores/session-store";
|
||||
import {
|
||||
classifyHostBrowserRouting,
|
||||
shouldOpenUrlInProxiedWorkspaceBrowser,
|
||||
type HostBrowserRouting,
|
||||
} from "./classify";
|
||||
|
||||
const statusByServerId = new Map<string, DesktopBrowserProxyStatusSnapshot>();
|
||||
const statusListenersByServerId = new Map<string, Set<() => void>>();
|
||||
const trackedHostIds = new Set<string>();
|
||||
const lastHostConnectionStatus = new Map<string, string>();
|
||||
let bridgeInstalled = false;
|
||||
|
||||
function notifyStatusListeners(serverId: string): void {
|
||||
const listeners = statusListenersByServerId.get(serverId);
|
||||
if (!listeners) return;
|
||||
for (const listener of listeners) {
|
||||
listener();
|
||||
}
|
||||
}
|
||||
|
||||
function setCachedStatus(snapshot: DesktopBrowserProxyStatusSnapshot): void {
|
||||
const existing = statusByServerId.get(snapshot.serverId);
|
||||
if (
|
||||
existing &&
|
||||
existing.status === snapshot.status &&
|
||||
existing.error === snapshot.error &&
|
||||
existing.partition === snapshot.partition &&
|
||||
existing.socksPort === snapshot.socksPort
|
||||
) {
|
||||
return;
|
||||
}
|
||||
statusByServerId.set(snapshot.serverId, snapshot);
|
||||
notifyStatusListeners(snapshot.serverId);
|
||||
}
|
||||
|
||||
function isStatusSnapshot(value: unknown): value is DesktopBrowserProxyStatusSnapshot {
|
||||
if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
|
||||
const record = value as Record<string, unknown>;
|
||||
return (
|
||||
typeof record.serverId === "string" &&
|
||||
typeof record.partition === "string" &&
|
||||
typeof record.status === "string"
|
||||
);
|
||||
}
|
||||
|
||||
function isTicketRequestEvent(value: unknown): value is DesktopBrowserProxyTicketRequestEvent {
|
||||
if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
|
||||
const record = value as Record<string, unknown>;
|
||||
return typeof record.requestId === "string" && typeof record.serverId === "string";
|
||||
}
|
||||
|
||||
async function handleTicketRequest(event: DesktopBrowserProxyTicketRequestEvent): Promise<void> {
|
||||
const deliver = getDesktopHost()?.browser?.deliverProxyTicket;
|
||||
if (typeof deliver !== "function") return;
|
||||
|
||||
const snapshot = getHostRuntimeStore().getSnapshot(event.serverId);
|
||||
const client = snapshot?.client ?? null;
|
||||
if (!client || snapshot?.connectionStatus !== "online") {
|
||||
await deliver({
|
||||
requestId: event.requestId,
|
||||
error: i18n.t("workspace.terminal.hostDisconnected"),
|
||||
}).catch(() => {});
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await client.createNetworkTunnelTicket();
|
||||
await deliver({ requestId: event.requestId, ticket: result.ticket });
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
await deliver({ requestId: event.requestId, error: message }).catch(() => {});
|
||||
}
|
||||
}
|
||||
|
||||
export function installBrowserProxyRendererBridge(): void {
|
||||
if (bridgeInstalled || !getIsElectron()) {
|
||||
return;
|
||||
}
|
||||
const desktop = getDesktopHost();
|
||||
if (!desktop?.events?.on || !desktop.browser?.ensureHostProxy) {
|
||||
return;
|
||||
}
|
||||
bridgeInstalled = true;
|
||||
|
||||
void desktop.events.on("browser-proxy-ticket-request", (payload) => {
|
||||
if (isTicketRequestEvent(payload)) {
|
||||
void handleTicketRequest(payload);
|
||||
}
|
||||
});
|
||||
|
||||
void desktop.events.on("browser-proxy-status", (payload) => {
|
||||
if (isStatusSnapshot(payload)) {
|
||||
setCachedStatus(payload);
|
||||
}
|
||||
});
|
||||
|
||||
const store = getHostRuntimeStore();
|
||||
store.subscribeAll(() => {
|
||||
const currentHosts = new Set(store.getHosts().map((host) => host.serverId));
|
||||
for (const serverId of trackedHostIds) {
|
||||
if (!currentHosts.has(serverId)) {
|
||||
trackedHostIds.delete(serverId);
|
||||
lastHostConnectionStatus.delete(serverId);
|
||||
statusByServerId.delete(serverId);
|
||||
notifyStatusListeners(serverId);
|
||||
void desktop.browser?.releaseHostProxy?.(serverId).catch(() => {});
|
||||
continue;
|
||||
}
|
||||
const nextConnectionStatus = store.getSnapshot(serverId)?.connectionStatus ?? "offline";
|
||||
const prevConnectionStatus = lastHostConnectionStatus.get(serverId);
|
||||
lastHostConnectionStatus.set(serverId, nextConnectionStatus);
|
||||
|
||||
const routing = readHostBrowserRouting(serverId);
|
||||
if (routing.kind === "remote" && routing.support === "supported") {
|
||||
if (prevConnectionStatus !== undefined && prevConnectionStatus !== "online") {
|
||||
// Control session just recovered after a drop; replace any half-open tunnel socket
|
||||
// immediately while keeping the fixed local SOCKS5 port and mounted webview intact.
|
||||
void ensureHostBrowserProxy({
|
||||
serverId,
|
||||
target: routing.target,
|
||||
forceReconnect: true,
|
||||
}).catch(() => {});
|
||||
} else {
|
||||
void desktop.browser
|
||||
?.updateHostProxyTarget?.({ serverId, target: routing.target })
|
||||
.catch(() => {});
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
export function readHostBrowserRouting(serverId: string): HostBrowserRouting {
|
||||
const runtimeStore = getHostRuntimeStore();
|
||||
const host = runtimeStore.getHosts().find((entry) => entry.serverId === serverId) ?? null;
|
||||
const snapshot = runtimeStore.getSnapshot(serverId);
|
||||
const serverInfo = useSessionStore.getState().sessions[serverId]?.serverInfo ?? null;
|
||||
const supportsNetworkTunnel =
|
||||
serverInfo !== null ? serverInfo.features?.networkTunnel === true : null;
|
||||
|
||||
return classifyHostBrowserRouting({
|
||||
serverId,
|
||||
connections: host?.connections ?? [],
|
||||
activeConnection: snapshot?.activeConnection ?? null,
|
||||
activeConnectionId: snapshot?.activeConnectionId ?? null,
|
||||
connectionStatus: snapshot?.connectionStatus ?? "offline",
|
||||
supportsNetworkTunnel,
|
||||
});
|
||||
}
|
||||
|
||||
export function shouldRouteWorkspaceUrlToProxiedBrowser(input: {
|
||||
serverId: string;
|
||||
url: string;
|
||||
}): boolean {
|
||||
if (!getIsElectron()) {
|
||||
return false;
|
||||
}
|
||||
const routing = readHostBrowserRouting(input.serverId);
|
||||
return shouldOpenUrlInProxiedWorkspaceBrowser({
|
||||
isElectron: true,
|
||||
url: input.url,
|
||||
routing,
|
||||
});
|
||||
}
|
||||
|
||||
export function getCachedBrowserProxyStatus(
|
||||
serverId: string,
|
||||
): DesktopBrowserProxyStatusSnapshot | null {
|
||||
return statusByServerId.get(serverId) ?? null;
|
||||
}
|
||||
|
||||
export function subscribeBrowserProxyStatus(serverId: string, listener: () => void): () => void {
|
||||
let listeners = statusListenersByServerId.get(serverId);
|
||||
if (!listeners) {
|
||||
listeners = new Set();
|
||||
statusListenersByServerId.set(serverId, listeners);
|
||||
}
|
||||
listeners.add(listener);
|
||||
return () => {
|
||||
listeners?.delete(listener);
|
||||
if (listeners && listeners.size === 0) {
|
||||
statusListenersByServerId.delete(serverId);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export async function ensureHostBrowserProxy(input: {
|
||||
serverId: string;
|
||||
target: NonNullable<
|
||||
Extract<HostBrowserRouting, { kind: "remote"; support: "supported" }>["target"]
|
||||
>;
|
||||
forceReconnect?: boolean;
|
||||
}): Promise<DesktopBrowserProxyStatusSnapshot | null> {
|
||||
installBrowserProxyRendererBridge();
|
||||
const ensureHostProxy = getDesktopHost()?.browser?.ensureHostProxy;
|
||||
if (typeof ensureHostProxy !== "function") {
|
||||
return null;
|
||||
}
|
||||
trackedHostIds.add(input.serverId);
|
||||
const currentStatus = getHostRuntimeStore().getSnapshot(input.serverId)?.connectionStatus;
|
||||
if (currentStatus) {
|
||||
lastHostConnectionStatus.set(input.serverId, currentStatus);
|
||||
}
|
||||
const snapshot = await ensureHostProxy(input);
|
||||
setCachedStatus(snapshot);
|
||||
return snapshot;
|
||||
}
|
||||
|
||||
export type PrepareHostBrowserPartitionResult =
|
||||
| { ok: true; partition: string; isRemoteHost: boolean }
|
||||
| {
|
||||
ok: false;
|
||||
reason:
|
||||
| "daemon_update_required"
|
||||
| "routed_unsupported"
|
||||
| "host_offline"
|
||||
| "host_connecting"
|
||||
| "proxy_error";
|
||||
message: string;
|
||||
};
|
||||
|
||||
export async function prepareHostBrowserPartition(
|
||||
serverId: string,
|
||||
options?: { forceReconnect?: boolean },
|
||||
): Promise<PrepareHostBrowserPartitionResult> {
|
||||
const desktop = getDesktopHost();
|
||||
const localPartition = desktop?.browser?.profilePartition;
|
||||
if (!localPartition) {
|
||||
return {
|
||||
ok: false,
|
||||
reason: "proxy_error",
|
||||
message: "Electron browser profile bridge is unavailable",
|
||||
};
|
||||
}
|
||||
|
||||
const routing = readHostBrowserRouting(serverId);
|
||||
if (routing.kind === "local") {
|
||||
return { ok: true, partition: localPartition, isRemoteHost: false };
|
||||
}
|
||||
|
||||
if (routing.support === "daemon_update_required") {
|
||||
return {
|
||||
ok: false,
|
||||
reason: "daemon_update_required",
|
||||
message: "Update this host daemon to browse through the host proxy.",
|
||||
};
|
||||
}
|
||||
if (routing.support === "routed_unsupported") {
|
||||
return {
|
||||
ok: false,
|
||||
reason: "routed_unsupported",
|
||||
message: "Browser proxying is not available for multi-hop routed hosts.",
|
||||
};
|
||||
}
|
||||
if (routing.support === "host_connecting") {
|
||||
return {
|
||||
ok: false,
|
||||
reason: "host_connecting",
|
||||
message: "Host is still connecting.",
|
||||
};
|
||||
}
|
||||
if (routing.support === "host_offline") {
|
||||
return {
|
||||
ok: false,
|
||||
reason: "host_offline",
|
||||
message: "Host is offline.",
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
const status = await ensureHostBrowserProxy({
|
||||
serverId,
|
||||
target: routing.target,
|
||||
forceReconnect: options?.forceReconnect,
|
||||
});
|
||||
if (!status) {
|
||||
return {
|
||||
ok: false,
|
||||
reason: "proxy_error",
|
||||
message: "Browser proxy bridge is unavailable in this desktop build.",
|
||||
};
|
||||
}
|
||||
if (status.status !== "ready") {
|
||||
return {
|
||||
ok: false,
|
||||
reason: "proxy_error",
|
||||
message: status.error ?? "Unable to connect browser proxy.",
|
||||
};
|
||||
}
|
||||
return { ok: true, partition: status.partition, isRemoteHost: true };
|
||||
} catch (error) {
|
||||
return {
|
||||
ok: false,
|
||||
reason: "proxy_error",
|
||||
message: error instanceof Error ? error.message : String(error),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,238 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { HostConnection } from "@/types/host-connection";
|
||||
import {
|
||||
classifyHostBrowserRouting,
|
||||
extractBrowserProxyTarget,
|
||||
isLoopbackBrowserUrl,
|
||||
isLoopbackHost,
|
||||
shouldOpenUrlInProxiedWorkspaceBrowser,
|
||||
} from "./classify";
|
||||
|
||||
describe("loopback URL classification", () => {
|
||||
it("recognizes localhost, *.localhost, 127.x, and ::1 hosts", () => {
|
||||
expect(isLoopbackHost("localhost")).toBe(true);
|
||||
expect(isLoopbackHost("LOCALHOST")).toBe(true);
|
||||
expect(isLoopbackHost("web.localhost")).toBe(true);
|
||||
expect(isLoopbackHost("api.v2.localhost")).toBe(true);
|
||||
expect(isLoopbackHost("127.0.0.1")).toBe(true);
|
||||
expect(isLoopbackHost("127.0.0.2")).toBe(true);
|
||||
expect(isLoopbackHost("::1")).toBe(true);
|
||||
expect(isLoopbackHost("[::1]")).toBe(true);
|
||||
|
||||
expect(isLoopbackHost("example.com")).toBe(false);
|
||||
expect(isLoopbackHost("localhost.example.com")).toBe(false);
|
||||
expect(isLoopbackHost("192.168.1.5")).toBe(false);
|
||||
expect(isLoopbackHost("10.0.0.1")).toBe(false);
|
||||
});
|
||||
|
||||
it("matches only http/https loopback URLs", () => {
|
||||
expect(isLoopbackBrowserUrl("http://localhost:5173")).toBe(true);
|
||||
expect(isLoopbackBrowserUrl("https://app.localhost:6767/dashboard")).toBe(true);
|
||||
expect(isLoopbackBrowserUrl("http://127.0.0.1:3000/api")).toBe(true);
|
||||
expect(isLoopbackBrowserUrl("http://[::1]:8080")).toBe(true);
|
||||
|
||||
expect(isLoopbackBrowserUrl("https://github.com/getpaseo/paseo")).toBe(false);
|
||||
expect(isLoopbackBrowserUrl("http://10.0.0.5:3000")).toBe(false);
|
||||
expect(isLoopbackBrowserUrl("ws://localhost:3000")).toBe(false);
|
||||
expect(isLoopbackBrowserUrl("not-a-url")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("classifyHostBrowserRouting", () => {
|
||||
const remoteTcp: HostConnection = {
|
||||
id: "direct:10.0.0.5:6767",
|
||||
type: "directTcp",
|
||||
endpoint: "10.0.0.5:6767",
|
||||
};
|
||||
const localTcp: HostConnection = {
|
||||
id: "direct:127.0.0.1:6767",
|
||||
type: "directTcp",
|
||||
endpoint: "127.0.0.1:6767",
|
||||
};
|
||||
const localSocket: HostConnection = {
|
||||
id: "socket:/tmp/paseo.sock",
|
||||
type: "directSocket",
|
||||
path: "/tmp/paseo.sock",
|
||||
};
|
||||
const remoteSsh: HostConnection = {
|
||||
id: "ssh:devbox",
|
||||
type: "remoteSsh",
|
||||
host: "devbox",
|
||||
sshPort: 2222,
|
||||
daemonPort: 6767,
|
||||
};
|
||||
const relayConn: HostConnection = {
|
||||
id: "relay:relay.paseo.sh",
|
||||
type: "relay",
|
||||
relayEndpoint: "relay.paseo.sh",
|
||||
useTls: true,
|
||||
daemonPublicKeyB64: "AAAA",
|
||||
minimumSecurityMode: "protected",
|
||||
};
|
||||
const routedConn: HostConnection = {
|
||||
id: "routed:origin-1",
|
||||
type: "routed",
|
||||
originServerId: "origin-1",
|
||||
};
|
||||
|
||||
it("classifies local socket, pipe, and loopback directTcp connections as local", () => {
|
||||
expect(
|
||||
classifyHostBrowserRouting({
|
||||
serverId: "local-1",
|
||||
connections: [localSocket],
|
||||
activeConnection: { type: "directSocket", endpoint: "/tmp/paseo.sock", display: "socket" },
|
||||
activeConnectionId: localSocket.id,
|
||||
connectionStatus: "online",
|
||||
supportsNetworkTunnel: true,
|
||||
}),
|
||||
).toEqual({ kind: "local" });
|
||||
|
||||
expect(
|
||||
classifyHostBrowserRouting({
|
||||
serverId: "local-2",
|
||||
connections: [localTcp],
|
||||
activeConnection: {
|
||||
type: "directTcp",
|
||||
endpoint: "127.0.0.1:6767",
|
||||
display: "127.0.0.1:6767",
|
||||
},
|
||||
activeConnectionId: localTcp.id,
|
||||
connectionStatus: "online",
|
||||
supportsNetworkTunnel: true,
|
||||
}),
|
||||
).toEqual({ kind: "local" });
|
||||
});
|
||||
|
||||
it("classifies remote directTcp, SSH, and relay hosts with networkTunnel as supported", () => {
|
||||
expect(
|
||||
classifyHostBrowserRouting({
|
||||
serverId: "remote-tcp",
|
||||
connections: [remoteTcp],
|
||||
activeConnection: {
|
||||
type: "directTcp",
|
||||
endpoint: "10.0.0.5:6767",
|
||||
display: "10.0.0.5:6767",
|
||||
},
|
||||
activeConnectionId: remoteTcp.id,
|
||||
connectionStatus: "online",
|
||||
supportsNetworkTunnel: true,
|
||||
}),
|
||||
).toEqual({
|
||||
kind: "remote",
|
||||
support: "supported",
|
||||
target: { type: "directTcp", endpoint: "10.0.0.5:6767" },
|
||||
});
|
||||
|
||||
expect(extractBrowserProxyTarget("remote-ssh", remoteSsh)).toEqual({
|
||||
type: "remoteSsh",
|
||||
host: "devbox",
|
||||
sshPort: 2222,
|
||||
daemonPort: 6767,
|
||||
});
|
||||
|
||||
expect(extractBrowserProxyTarget("remote-relay", relayConn)).toEqual({
|
||||
type: "relay",
|
||||
serverId: "remote-relay",
|
||||
relayEndpoint: "relay.paseo.sh",
|
||||
useTls: true,
|
||||
daemonPublicKeyB64: "AAAA",
|
||||
minimumSecurityMode: "protected",
|
||||
});
|
||||
});
|
||||
|
||||
it("fails closed for old daemons, routed hosts, connecting hosts, and offline remote hosts", () => {
|
||||
expect(
|
||||
classifyHostBrowserRouting({
|
||||
serverId: "old-daemon",
|
||||
connections: [remoteTcp],
|
||||
activeConnection: {
|
||||
type: "directTcp",
|
||||
endpoint: "10.0.0.5:6767",
|
||||
display: "10.0.0.5:6767",
|
||||
},
|
||||
activeConnectionId: remoteTcp.id,
|
||||
connectionStatus: "online",
|
||||
supportsNetworkTunnel: false,
|
||||
}),
|
||||
).toEqual({ kind: "remote", support: "daemon_update_required" });
|
||||
|
||||
expect(
|
||||
classifyHostBrowserRouting({
|
||||
serverId: "routed-host",
|
||||
connections: [routedConn],
|
||||
activeConnection: { type: "routed", endpoint: "origin-1", display: "via origin-1" },
|
||||
activeConnectionId: routedConn.id,
|
||||
connectionStatus: "online",
|
||||
supportsNetworkTunnel: true,
|
||||
}),
|
||||
).toEqual({ kind: "remote", support: "routed_unsupported" });
|
||||
|
||||
expect(
|
||||
classifyHostBrowserRouting({
|
||||
serverId: "offline-remote",
|
||||
connections: [remoteSsh],
|
||||
activeConnection: null,
|
||||
activeConnectionId: null,
|
||||
connectionStatus: "offline",
|
||||
supportsNetworkTunnel: null,
|
||||
}),
|
||||
).toEqual({ kind: "remote", support: "host_offline" });
|
||||
|
||||
expect(
|
||||
classifyHostBrowserRouting({
|
||||
serverId: "connecting-remote",
|
||||
connections: [relayConn],
|
||||
activeConnection: null,
|
||||
activeConnectionId: null,
|
||||
connectionStatus: "connecting",
|
||||
supportsNetworkTunnel: null,
|
||||
}),
|
||||
).toEqual({ kind: "remote", support: "host_connecting" });
|
||||
});
|
||||
|
||||
it("routes only loopback URLs on supported remote hosts in Electron to a proxied browser tab", () => {
|
||||
const supportedRemote = {
|
||||
kind: "remote" as const,
|
||||
support: "supported" as const,
|
||||
target: { type: "directTcp" as const, endpoint: "10.0.0.5:6767" },
|
||||
};
|
||||
const oldRemote = { kind: "remote" as const, support: "daemon_update_required" as const };
|
||||
const local = { kind: "local" as const };
|
||||
|
||||
expect(
|
||||
shouldOpenUrlInProxiedWorkspaceBrowser({
|
||||
isElectron: true,
|
||||
url: "http://localhost:5173",
|
||||
routing: supportedRemote,
|
||||
}),
|
||||
).toBe(true);
|
||||
expect(
|
||||
shouldOpenUrlInProxiedWorkspaceBrowser({
|
||||
isElectron: true,
|
||||
url: "https://github.com/getpaseo/paseo",
|
||||
routing: supportedRemote,
|
||||
}),
|
||||
).toBe(false);
|
||||
expect(
|
||||
shouldOpenUrlInProxiedWorkspaceBrowser({
|
||||
isElectron: true,
|
||||
url: "http://localhost:5173",
|
||||
routing: oldRemote,
|
||||
}),
|
||||
).toBe(false);
|
||||
expect(
|
||||
shouldOpenUrlInProxiedWorkspaceBrowser({
|
||||
isElectron: true,
|
||||
url: "http://localhost:5173",
|
||||
routing: local,
|
||||
}),
|
||||
).toBe(false);
|
||||
expect(
|
||||
shouldOpenUrlInProxiedWorkspaceBrowser({
|
||||
isElectron: false,
|
||||
url: "http://localhost:5173",
|
||||
routing: supportedRemote,
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,196 @@
|
||||
import { parseHostPort } from "@getpaseo/protocol/daemon-endpoints";
|
||||
import type { DesktopBrowserProxyTarget } from "@/desktop/host";
|
||||
import type { ActiveConnection, HostRuntimeConnectionStatus } from "@/runtime/host-runtime";
|
||||
import type { HostConnection } from "@/types/host-connection";
|
||||
|
||||
const IPV4_LOOPBACK_PATTERN = /^127(?:\.(?:25[0-5]|2[0-4]\d|1?\d?\d)){3}$/;
|
||||
|
||||
export function isLoopbackHost(host: string): boolean {
|
||||
const normalized = host
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
.replace(/^\[|\]$/g, "");
|
||||
if (!normalized) return false;
|
||||
return (
|
||||
normalized === "localhost" ||
|
||||
normalized.endsWith(".localhost") ||
|
||||
normalized === "::1" ||
|
||||
IPV4_LOOPBACK_PATTERN.test(normalized)
|
||||
);
|
||||
}
|
||||
|
||||
export function isLoopbackBrowserUrl(url: string): boolean {
|
||||
try {
|
||||
const parsed = new URL(url);
|
||||
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
|
||||
return false;
|
||||
}
|
||||
return isLoopbackHost(parsed.hostname);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function isLoopbackDirectTcpEndpoint(endpoint: string): boolean {
|
||||
try {
|
||||
const { host } = parseHostPort(endpoint);
|
||||
return isLoopbackHost(host);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export function isLocalHostConnection(connection: HostConnection | ActiveConnection): boolean {
|
||||
if (connection.type === "directSocket" || connection.type === "directPipe") {
|
||||
return true;
|
||||
}
|
||||
if (connection.type === "directTcp") {
|
||||
return isLoopbackDirectTcpEndpoint(connection.endpoint);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
export function extractBrowserProxyTarget(
|
||||
serverId: string,
|
||||
connection: HostConnection,
|
||||
): DesktopBrowserProxyTarget | null {
|
||||
if (connection.type === "directTcp") {
|
||||
if (isLoopbackDirectTcpEndpoint(connection.endpoint)) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
type: "directTcp",
|
||||
endpoint: connection.endpoint,
|
||||
...(connection.useTls !== undefined ? { useTls: connection.useTls } : {}),
|
||||
};
|
||||
}
|
||||
if (connection.type === "remoteSsh") {
|
||||
return {
|
||||
type: "remoteSsh",
|
||||
host: connection.host,
|
||||
...(connection.sshPort !== undefined ? { sshPort: connection.sshPort } : {}),
|
||||
...(connection.daemonPort !== undefined ? { daemonPort: connection.daemonPort } : {}),
|
||||
};
|
||||
}
|
||||
if (connection.type === "relay") {
|
||||
return {
|
||||
type: "relay",
|
||||
serverId,
|
||||
relayEndpoint: connection.relayEndpoint,
|
||||
...(connection.useTls !== undefined ? { useTls: connection.useTls } : {}),
|
||||
daemonPublicKeyB64: connection.daemonPublicKeyB64,
|
||||
...(connection.minimumSecurityMode === "protected"
|
||||
? { minimumSecurityMode: "protected" }
|
||||
: {}),
|
||||
};
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export type HostBrowserRouting =
|
||||
| { kind: "local" }
|
||||
| { kind: "remote"; support: "supported"; target: DesktopBrowserProxyTarget }
|
||||
| { kind: "remote"; support: "daemon_update_required" }
|
||||
| { kind: "remote"; support: "routed_unsupported" }
|
||||
| { kind: "remote"; support: "host_connecting" }
|
||||
| { kind: "remote"; support: "host_offline" };
|
||||
|
||||
export interface ClassifyHostBrowserRoutingInput {
|
||||
serverId: string;
|
||||
connections: readonly HostConnection[];
|
||||
activeConnection: ActiveConnection | null;
|
||||
activeConnectionId: string | null;
|
||||
connectionStatus: HostRuntimeConnectionStatus;
|
||||
supportsNetworkTunnel: boolean | null;
|
||||
}
|
||||
|
||||
function findMatchingHostConnection(
|
||||
connections: readonly HostConnection[],
|
||||
activeConnectionId: string | null,
|
||||
activeConnection: ActiveConnection | null,
|
||||
): HostConnection | null {
|
||||
if (activeConnectionId) {
|
||||
const byId = connections.find((conn) => conn.id === activeConnectionId);
|
||||
if (byId) return byId;
|
||||
}
|
||||
if (activeConnection) {
|
||||
const byType = connections.find((conn) => {
|
||||
if (conn.type !== activeConnection.type) return false;
|
||||
if (conn.type === "directTcp") return conn.endpoint === activeConnection.endpoint;
|
||||
if (conn.type === "remoteSsh") return conn.host === activeConnection.endpoint;
|
||||
if (conn.type === "relay") return conn.relayEndpoint === activeConnection.endpoint;
|
||||
if (conn.type === "routed") return conn.originServerId === activeConnection.endpoint;
|
||||
return true;
|
||||
});
|
||||
if (byType) return byType;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export function classifyHostBrowserRouting(
|
||||
input: ClassifyHostBrowserRoutingInput,
|
||||
): HostBrowserRouting {
|
||||
const {
|
||||
serverId,
|
||||
connections,
|
||||
activeConnection,
|
||||
activeConnectionId,
|
||||
connectionStatus,
|
||||
supportsNetworkTunnel,
|
||||
} = input;
|
||||
|
||||
if (activeConnection) {
|
||||
if (isLocalHostConnection(activeConnection)) {
|
||||
return { kind: "local" };
|
||||
}
|
||||
if (activeConnection.type === "routed") {
|
||||
return { kind: "remote", support: "routed_unsupported" };
|
||||
}
|
||||
} else {
|
||||
// No active connection yet (connecting/offline). Distinguish local hosts from remote
|
||||
// hosts using saved connection definitions so remote tabs fail closed during startup.
|
||||
if (connections.length === 0 || connections.some(isLocalHostConnection)) {
|
||||
return { kind: "local" };
|
||||
}
|
||||
if (connections.every((conn) => conn.type === "routed")) {
|
||||
return { kind: "remote", support: "routed_unsupported" };
|
||||
}
|
||||
}
|
||||
|
||||
if (connectionStatus === "connecting" || connectionStatus === "idle") {
|
||||
return { kind: "remote", support: "host_connecting" };
|
||||
}
|
||||
if (connectionStatus !== "online") {
|
||||
return { kind: "remote", support: "host_offline" };
|
||||
}
|
||||
|
||||
// COMPAT(networkTunnel): added in v0.18.0, remove after 2027-05-26 once daemon floor >= v0.18.0.
|
||||
if (supportsNetworkTunnel !== true) {
|
||||
return { kind: "remote", support: "daemon_update_required" };
|
||||
}
|
||||
|
||||
const matchedConnection = findMatchingHostConnection(
|
||||
connections,
|
||||
activeConnectionId,
|
||||
activeConnection,
|
||||
);
|
||||
const target = matchedConnection ? extractBrowserProxyTarget(serverId, matchedConnection) : null;
|
||||
if (!target) {
|
||||
return { kind: "remote", support: "host_offline" };
|
||||
}
|
||||
|
||||
return { kind: "remote", support: "supported", target };
|
||||
}
|
||||
|
||||
export function shouldOpenUrlInProxiedWorkspaceBrowser(input: {
|
||||
isElectron: boolean;
|
||||
url: string;
|
||||
routing: HostBrowserRouting;
|
||||
}): boolean {
|
||||
return (
|
||||
input.isElectron &&
|
||||
isLoopbackBrowserUrl(input.url) &&
|
||||
input.routing.kind === "remote" &&
|
||||
input.routing.support === "supported"
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { resolveBrowserProxyPaneState } from "./use-host-browser-proxy";
|
||||
|
||||
const noop = () => {};
|
||||
|
||||
describe("resolveBrowserProxyPaneState", () => {
|
||||
it("fails closed while connecting or offline before a host partition has been prepared", () => {
|
||||
expect(
|
||||
resolveBrowserProxyPaneState({
|
||||
routing: { kind: "remote", support: "host_connecting" },
|
||||
effectiveRoutingMode: "host",
|
||||
localPartition: "persist:paseo-browser",
|
||||
hostLabel: "devbox",
|
||||
proxyStatusSnapshot: null,
|
||||
ensureError: null,
|
||||
onRetry: noop,
|
||||
}),
|
||||
).toEqual({
|
||||
kind: "connecting",
|
||||
isRemoteHost: true,
|
||||
effectiveRoutingMode: "host",
|
||||
hostLabel: "devbox",
|
||||
isReconnecting: false,
|
||||
});
|
||||
|
||||
expect(
|
||||
resolveBrowserProxyPaneState({
|
||||
routing: { kind: "remote", support: "host_offline" },
|
||||
effectiveRoutingMode: "host",
|
||||
localPartition: "persist:paseo-browser",
|
||||
hostLabel: "devbox",
|
||||
proxyStatusSnapshot: {
|
||||
serverId: "srv-remote",
|
||||
partition: "persist:paseo-browser-host-0123456789abcdef",
|
||||
status: "connecting",
|
||||
error: null,
|
||||
socksPort: null,
|
||||
},
|
||||
ensureError: null,
|
||||
onRetry: noop,
|
||||
}),
|
||||
).toEqual({
|
||||
kind: "host_offline",
|
||||
isRemoteHost: true,
|
||||
effectiveRoutingMode: "host",
|
||||
hostLabel: "devbox",
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps the prepared host partition mounted across transient host disconnects and reconnects", () => {
|
||||
const preparedSnapshot = {
|
||||
serverId: "srv-remote",
|
||||
partition: "persist:paseo-browser-host-0123456789abcdef",
|
||||
status: "ready" as const,
|
||||
error: null,
|
||||
socksPort: 41234,
|
||||
};
|
||||
|
||||
expect(
|
||||
resolveBrowserProxyPaneState({
|
||||
routing: { kind: "remote", support: "host_offline" },
|
||||
effectiveRoutingMode: "host",
|
||||
localPartition: "persist:paseo-browser",
|
||||
hostLabel: "devbox",
|
||||
proxyStatusSnapshot: preparedSnapshot,
|
||||
ensureError: null,
|
||||
onRetry: noop,
|
||||
}),
|
||||
).toEqual({
|
||||
kind: "ready",
|
||||
partition: preparedSnapshot.partition,
|
||||
isRemoteHost: true,
|
||||
effectiveRoutingMode: "host",
|
||||
hostLabel: "devbox",
|
||||
proxyStatus: "reconnecting",
|
||||
});
|
||||
|
||||
expect(
|
||||
resolveBrowserProxyPaneState({
|
||||
routing: { kind: "remote", support: "host_connecting" },
|
||||
effectiveRoutingMode: "host",
|
||||
localPartition: "persist:paseo-browser",
|
||||
hostLabel: "devbox",
|
||||
proxyStatusSnapshot: preparedSnapshot,
|
||||
ensureError: null,
|
||||
onRetry: noop,
|
||||
}),
|
||||
).toEqual({
|
||||
kind: "ready",
|
||||
partition: preparedSnapshot.partition,
|
||||
isRemoteHost: true,
|
||||
effectiveRoutingMode: "host",
|
||||
hostLabel: "devbox",
|
||||
proxyStatus: "reconnecting",
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps the prepared host partition mounted when a background poll left cached status in error as host returns online", () => {
|
||||
const supportedRouting = {
|
||||
kind: "remote" as const,
|
||||
support: "supported" as const,
|
||||
target: { type: "directTcp" as const, endpoint: "10.0.0.5:6767" },
|
||||
};
|
||||
|
||||
expect(
|
||||
resolveBrowserProxyPaneState({
|
||||
routing: supportedRouting,
|
||||
effectiveRoutingMode: "host",
|
||||
localPartition: "persist:paseo-browser",
|
||||
hostLabel: "devbox",
|
||||
proxyStatusSnapshot: {
|
||||
serverId: "srv-remote",
|
||||
partition: "persist:paseo-browser-host-0123456789abcdef",
|
||||
status: "error",
|
||||
error: "Host disconnected",
|
||||
socksPort: 41234,
|
||||
},
|
||||
ensureError: null,
|
||||
onRetry: noop,
|
||||
}),
|
||||
).toEqual({
|
||||
kind: "ready",
|
||||
partition: "persist:paseo-browser-host-0123456789abcdef",
|
||||
isRemoteHost: true,
|
||||
effectiveRoutingMode: "host",
|
||||
hostLabel: "devbox",
|
||||
proxyStatus: "error",
|
||||
});
|
||||
|
||||
// Once the live snapshot recovers to ready, a stale hook-local ensureError
|
||||
// must not pin the prepared pill dot to error.
|
||||
expect(
|
||||
resolveBrowserProxyPaneState({
|
||||
routing: supportedRouting,
|
||||
effectiveRoutingMode: "host",
|
||||
localPartition: "persist:paseo-browser",
|
||||
hostLabel: "devbox",
|
||||
proxyStatusSnapshot: {
|
||||
serverId: "srv-remote",
|
||||
partition: "persist:paseo-browser-host-0123456789abcdef",
|
||||
status: "ready",
|
||||
error: null,
|
||||
socksPort: 41234,
|
||||
},
|
||||
ensureError: "Unable to create ticket",
|
||||
onRetry: noop,
|
||||
}),
|
||||
).toEqual({
|
||||
kind: "ready",
|
||||
partition: "persist:paseo-browser-host-0123456789abcdef",
|
||||
isRemoteHost: true,
|
||||
effectiveRoutingMode: "host",
|
||||
hostLabel: "devbox",
|
||||
proxyStatus: "ready",
|
||||
});
|
||||
|
||||
// Unprepared partition (socksPort === null) still fails closed with proxy_error.
|
||||
expect(
|
||||
resolveBrowserProxyPaneState({
|
||||
routing: supportedRouting,
|
||||
effectiveRoutingMode: "host",
|
||||
localPartition: "persist:paseo-browser",
|
||||
hostLabel: "devbox",
|
||||
proxyStatusSnapshot: {
|
||||
serverId: "srv-remote",
|
||||
partition: "persist:paseo-browser-host-0123456789abcdef",
|
||||
status: "error",
|
||||
error: "Unable to create ticket",
|
||||
socksPort: null,
|
||||
},
|
||||
ensureError: null,
|
||||
onRetry: noop,
|
||||
}),
|
||||
).toEqual({
|
||||
kind: "proxy_error",
|
||||
isRemoteHost: true,
|
||||
effectiveRoutingMode: "host",
|
||||
hostLabel: "devbox",
|
||||
message: "Unable to create ticket",
|
||||
retry: noop,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,292 @@
|
||||
import { useCallback, useEffect, useMemo, useState, useSyncExternalStore } from "react";
|
||||
import { getIsElectron } from "@/constants/platform";
|
||||
import { getDesktopHost, type DesktopBrowserProxyStatus } from "@/desktop/host";
|
||||
import { resolveBrowserRoutingMode, type BrowserRoutingMode } from "@/desktop/browser/store";
|
||||
import { useHostRuntimeSnapshot, useHosts } from "@/runtime/host-runtime";
|
||||
import { useSessionStore } from "@/stores/session-store";
|
||||
import { normalizeHostLabel } from "@/types/host-connection";
|
||||
import {
|
||||
ensureHostBrowserProxy,
|
||||
getCachedBrowserProxyStatus,
|
||||
installBrowserProxyRendererBridge,
|
||||
subscribeBrowserProxyStatus,
|
||||
} from "./bridge";
|
||||
import { classifyHostBrowserRouting } from "./classify";
|
||||
|
||||
export type BrowserProxyPaneState =
|
||||
| {
|
||||
kind: "ready";
|
||||
partition: string;
|
||||
isRemoteHost: boolean;
|
||||
effectiveRoutingMode: BrowserRoutingMode;
|
||||
hostLabel: string;
|
||||
proxyStatus: DesktopBrowserProxyStatus | null;
|
||||
}
|
||||
| {
|
||||
kind: "connecting";
|
||||
isRemoteHost: true;
|
||||
effectiveRoutingMode: "host";
|
||||
hostLabel: string;
|
||||
isReconnecting: boolean;
|
||||
}
|
||||
| {
|
||||
kind: "daemon_update_required";
|
||||
isRemoteHost: true;
|
||||
effectiveRoutingMode: "host";
|
||||
hostLabel: string;
|
||||
}
|
||||
| {
|
||||
kind: "routed_unsupported";
|
||||
isRemoteHost: true;
|
||||
effectiveRoutingMode: "host";
|
||||
hostLabel: string;
|
||||
}
|
||||
| {
|
||||
kind: "host_offline";
|
||||
isRemoteHost: true;
|
||||
effectiveRoutingMode: "host";
|
||||
hostLabel: string;
|
||||
}
|
||||
| {
|
||||
kind: "proxy_error";
|
||||
isRemoteHost: true;
|
||||
effectiveRoutingMode: "host";
|
||||
hostLabel: string;
|
||||
message: string;
|
||||
retry: () => void;
|
||||
};
|
||||
|
||||
function hasPreparedHostPartition(
|
||||
snapshot: ReturnType<typeof getCachedBrowserProxyStatus>,
|
||||
): snapshot is NonNullable<ReturnType<typeof getCachedBrowserProxyStatus>> & {
|
||||
partition: string;
|
||||
socksPort: number;
|
||||
} {
|
||||
return Boolean(snapshot?.partition && snapshot.socksPort !== null);
|
||||
}
|
||||
|
||||
function resolveRemoteUnavailablePaneState(
|
||||
support: Exclude<
|
||||
Extract<ReturnType<typeof classifyHostBrowserRouting>, { kind: "remote" }>["support"],
|
||||
"supported"
|
||||
>,
|
||||
hostLabel: string,
|
||||
proxyStatusSnapshot: ReturnType<typeof getCachedBrowserProxyStatus>,
|
||||
): BrowserProxyPaneState {
|
||||
// Once Electron main has verified and bound this host's fixed SOCKS5 partition,
|
||||
// keep the webview mounted across transient host disconnects/reconnects so SPA
|
||||
// state, forms, scroll, and DevTools survive. Requests still fail closed at the
|
||||
// local SOCKS5 listener while the tunnel is down.
|
||||
const isTransientDisconnect = support === "host_connecting" || support === "host_offline";
|
||||
if (isTransientDisconnect && hasPreparedHostPartition(proxyStatusSnapshot)) {
|
||||
return {
|
||||
kind: "ready",
|
||||
partition: proxyStatusSnapshot.partition,
|
||||
isRemoteHost: true,
|
||||
effectiveRoutingMode: "host",
|
||||
hostLabel,
|
||||
proxyStatus: "reconnecting",
|
||||
};
|
||||
}
|
||||
if (support === "host_connecting") {
|
||||
return {
|
||||
kind: "connecting",
|
||||
isRemoteHost: true,
|
||||
effectiveRoutingMode: "host",
|
||||
hostLabel,
|
||||
isReconnecting: false,
|
||||
};
|
||||
}
|
||||
return {
|
||||
kind: support,
|
||||
isRemoteHost: true,
|
||||
effectiveRoutingMode: "host",
|
||||
hostLabel,
|
||||
};
|
||||
}
|
||||
|
||||
function resolvePreparedHostPaneStatus(
|
||||
status: DesktopBrowserProxyStatus,
|
||||
): DesktopBrowserProxyStatus {
|
||||
if (status === "ready" || status === "error") {
|
||||
return status;
|
||||
}
|
||||
return "reconnecting";
|
||||
}
|
||||
|
||||
export function resolveBrowserProxyPaneState(input: {
|
||||
routing: ReturnType<typeof classifyHostBrowserRouting>;
|
||||
effectiveRoutingMode: BrowserRoutingMode;
|
||||
localPartition: string;
|
||||
hostLabel: string;
|
||||
proxyStatusSnapshot: ReturnType<typeof getCachedBrowserProxyStatus>;
|
||||
ensureError: string | null;
|
||||
onRetry: () => void;
|
||||
}): BrowserProxyPaneState {
|
||||
const {
|
||||
routing,
|
||||
effectiveRoutingMode,
|
||||
localPartition,
|
||||
hostLabel,
|
||||
proxyStatusSnapshot,
|
||||
ensureError,
|
||||
onRetry,
|
||||
} = input;
|
||||
|
||||
if (routing.kind === "local" || effectiveRoutingMode === "local") {
|
||||
return {
|
||||
kind: "ready",
|
||||
partition: localPartition,
|
||||
isRemoteHost: routing.kind === "remote",
|
||||
effectiveRoutingMode: "local",
|
||||
hostLabel,
|
||||
proxyStatus: null,
|
||||
};
|
||||
}
|
||||
|
||||
if (routing.support !== "supported") {
|
||||
return resolveRemoteUnavailablePaneState(routing.support, hostLabel, proxyStatusSnapshot);
|
||||
}
|
||||
|
||||
// Once the fixed-port SOCKS5 session partition is verified (socksPort !== null),
|
||||
// keep the webview mounted even if a background poll (e.g. HMR) left the cached
|
||||
// tunnel status in "error" or "reconnecting" while the host reconnects.
|
||||
if (hasPreparedHostPartition(proxyStatusSnapshot)) {
|
||||
return {
|
||||
kind: "ready",
|
||||
partition: proxyStatusSnapshot.partition,
|
||||
isRemoteHost: true,
|
||||
effectiveRoutingMode: "host",
|
||||
hostLabel,
|
||||
proxyStatus: resolvePreparedHostPaneStatus(proxyStatusSnapshot.status),
|
||||
};
|
||||
}
|
||||
|
||||
const errorMessage =
|
||||
ensureError ?? (proxyStatusSnapshot?.status === "error" ? proxyStatusSnapshot.error : null);
|
||||
if (errorMessage) {
|
||||
return {
|
||||
kind: "proxy_error",
|
||||
isRemoteHost: true,
|
||||
effectiveRoutingMode: "host",
|
||||
hostLabel,
|
||||
message: errorMessage,
|
||||
retry: onRetry,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
kind: "connecting",
|
||||
isRemoteHost: true,
|
||||
effectiveRoutingMode: "host",
|
||||
hostLabel,
|
||||
isReconnecting: false,
|
||||
};
|
||||
}
|
||||
|
||||
export function useHostBrowserProxy(input: {
|
||||
serverId: string;
|
||||
routingMode?: BrowserRoutingMode;
|
||||
}): BrowserProxyPaneState {
|
||||
const { serverId, routingMode } = input;
|
||||
const hosts = useHosts();
|
||||
const host = useMemo(
|
||||
() => hosts.find((entry) => entry.serverId === serverId) ?? null,
|
||||
[hosts, serverId],
|
||||
);
|
||||
const hostLabel = normalizeHostLabel(host?.label, serverId);
|
||||
const runtimeSnapshot = useHostRuntimeSnapshot(serverId);
|
||||
const supportsNetworkTunnel = useSessionStore((state) => {
|
||||
const serverInfo = state.sessions[serverId]?.serverInfo ?? null;
|
||||
return serverInfo !== null ? serverInfo.features?.networkTunnel === true : null;
|
||||
});
|
||||
|
||||
const proxyStatusSnapshot = useSyncExternalStore(
|
||||
useCallback((onChange) => subscribeBrowserProxyStatus(serverId, onChange), [serverId]),
|
||||
() => getCachedBrowserProxyStatus(serverId),
|
||||
() => getCachedBrowserProxyStatus(serverId),
|
||||
);
|
||||
|
||||
const [retryCounter, setRetryCounter] = useState(0);
|
||||
const [ensureError, setEnsureError] = useState<string | null>(null);
|
||||
|
||||
const routing = useMemo(
|
||||
() =>
|
||||
classifyHostBrowserRouting({
|
||||
serverId,
|
||||
connections: host?.connections ?? [],
|
||||
activeConnection: runtimeSnapshot?.activeConnection ?? null,
|
||||
activeConnectionId: runtimeSnapshot?.activeConnectionId ?? null,
|
||||
connectionStatus: runtimeSnapshot?.connectionStatus ?? "offline",
|
||||
supportsNetworkTunnel,
|
||||
}),
|
||||
[
|
||||
host?.connections,
|
||||
runtimeSnapshot?.activeConnection,
|
||||
runtimeSnapshot?.activeConnectionId,
|
||||
runtimeSnapshot?.connectionStatus,
|
||||
serverId,
|
||||
supportsNetworkTunnel,
|
||||
],
|
||||
);
|
||||
|
||||
const effectiveRoutingMode = resolveBrowserRoutingMode(
|
||||
{ routingMode },
|
||||
routing.kind === "remote",
|
||||
);
|
||||
const supportedTarget =
|
||||
routing.kind === "remote" && routing.support === "supported" ? routing.target : null;
|
||||
const targetKey = supportedTarget ? JSON.stringify(supportedTarget) : null;
|
||||
|
||||
const handleRetry = useCallback(() => {
|
||||
setEnsureError(null);
|
||||
setRetryCounter((count) => count + 1);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!getIsElectron() || effectiveRoutingMode !== "host" || !supportedTarget) {
|
||||
setEnsureError(null);
|
||||
return;
|
||||
}
|
||||
|
||||
let cancelled = false;
|
||||
installBrowserProxyRendererBridge();
|
||||
setEnsureError(null);
|
||||
|
||||
void ensureHostBrowserProxy({
|
||||
serverId,
|
||||
target: supportedTarget,
|
||||
forceReconnect: retryCounter > 0,
|
||||
})
|
||||
.then((snapshot) => {
|
||||
if (cancelled) return undefined;
|
||||
if (!snapshot) {
|
||||
setEnsureError("Browser proxy bridge is unavailable.");
|
||||
} else if (snapshot.status === "error") {
|
||||
setEnsureError(snapshot.error ?? "Unable to connect browser proxy.");
|
||||
}
|
||||
return undefined;
|
||||
})
|
||||
.catch((error) => {
|
||||
if (cancelled) return;
|
||||
setEnsureError(error instanceof Error ? error.message : String(error));
|
||||
});
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
// targetKey serializes supportedTarget deterministically.
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [effectiveRoutingMode, retryCounter, serverId, targetKey]);
|
||||
|
||||
const localPartition = getDesktopHost()?.browser?.profilePartition ?? "persist:paseo-browser";
|
||||
return resolveBrowserProxyPaneState({
|
||||
routing,
|
||||
effectiveRoutingMode,
|
||||
localPartition,
|
||||
hostLabel,
|
||||
proxyStatusSnapshot,
|
||||
ensureError,
|
||||
onRetry: handleRetry,
|
||||
});
|
||||
}
|
||||
@@ -299,12 +299,14 @@ export function prepareBrowserWebview(
|
||||
browserId: string;
|
||||
workspaceId: string;
|
||||
initialUrl?: string | null;
|
||||
partition?: string;
|
||||
profileHost?: BrowserWebviewProfileHost;
|
||||
},
|
||||
): void {
|
||||
const browser = getBrowserBridge(input.profileHost);
|
||||
const targetPartition = input.partition ?? browser.profilePartition;
|
||||
webview.setAttribute(BROWSER_ID_ATTRIBUTE, input.browserId);
|
||||
webview.setAttribute("partition", browser.profilePartition);
|
||||
webview.setAttribute("partition", targetPartition);
|
||||
webview.setAttribute("allowpopups", "true");
|
||||
webview.setAttribute("spellcheck", "false");
|
||||
webview.setAttribute("autosize", "on");
|
||||
@@ -314,10 +316,15 @@ export function prepareBrowserWebview(
|
||||
registerBrowserWhenAttached(webview as BrowserWebviewElement, input, browser);
|
||||
}
|
||||
|
||||
export function getResidentBrowserWebviewPartition(webview: HTMLElement): string | null {
|
||||
return trimNonEmpty(webview.getAttribute("partition"));
|
||||
}
|
||||
|
||||
export function ensureResidentBrowserWebview(input: {
|
||||
browserId: string;
|
||||
workspaceId: string;
|
||||
url: string;
|
||||
partition?: string;
|
||||
profileHost?: BrowserWebviewProfileHost;
|
||||
}): HTMLElement | null {
|
||||
const browserId = trimNonEmpty(input.browserId);
|
||||
@@ -329,18 +336,27 @@ export function ensureResidentBrowserWebview(input: {
|
||||
return null;
|
||||
}
|
||||
|
||||
const browser = getBrowserBridge(input.profileHost);
|
||||
const desiredPartition = input.partition ?? browser.profilePartition;
|
||||
|
||||
const resident = residentWebviewsByBrowserId.get(browserId) ?? null;
|
||||
if (resident?.isConnected) {
|
||||
releaseResidentBrowserWebview(browserId, resident);
|
||||
return resident;
|
||||
if (getResidentBrowserWebviewPartition(resident) === desiredPartition) {
|
||||
releaseResidentBrowserWebview(browserId, resident);
|
||||
return resident;
|
||||
}
|
||||
removeResidentBrowserWebview(browserId);
|
||||
}
|
||||
|
||||
const existing = findBrowserWebview(browserId, ownerDocument);
|
||||
if (existing) {
|
||||
if (existing.parentElement?.id === RESIDENT_BROWSER_HOST_ID) {
|
||||
releaseResidentBrowserWebview(browserId, existing);
|
||||
if (getResidentBrowserWebviewPartition(existing) === desiredPartition) {
|
||||
if (existing.parentElement?.id === RESIDENT_BROWSER_HOST_ID) {
|
||||
releaseResidentBrowserWebview(browserId, existing);
|
||||
}
|
||||
return existing;
|
||||
}
|
||||
return existing;
|
||||
existing.remove();
|
||||
}
|
||||
|
||||
const webview = ownerDocument.createElement("webview") as BrowserWebviewElement;
|
||||
@@ -348,7 +364,8 @@ export function ensureResidentBrowserWebview(input: {
|
||||
browserId,
|
||||
workspaceId: input.workspaceId,
|
||||
initialUrl: input.url,
|
||||
profileHost: input.profileHost,
|
||||
partition: desiredPartition,
|
||||
profileHost: browser,
|
||||
});
|
||||
releaseResidentBrowserWebview(browserId, webview);
|
||||
return webview;
|
||||
|
||||
@@ -6,6 +6,7 @@ import { useToast } from "@/contexts/toast-context";
|
||||
import { getDesktopHost } from "@/desktop/host";
|
||||
import { SettingsSection } from "@/components/settings/headings/settings-section";
|
||||
import { useBrowserStore } from "@/desktop/browser/store";
|
||||
import { getHostRuntimeStore } from "@/runtime/host-runtime";
|
||||
import { settingsStyles } from "@/styles/settings";
|
||||
import { confirmDialog } from "@/utils/confirm-dialog";
|
||||
|
||||
@@ -39,7 +40,10 @@ export function BrowserDataSection() {
|
||||
throw new Error("Electron browser profile bridge is unavailable");
|
||||
}
|
||||
|
||||
await clearProfile(Object.keys(useBrowserStore.getState().browsersById));
|
||||
const hostServerIds = getHostRuntimeStore()
|
||||
.getHosts()
|
||||
.map((host) => host.serverId);
|
||||
await clearProfile(Object.keys(useBrowserStore.getState().browsersById), hostServerIds);
|
||||
toast.show(t("settings.general.browserData.success"), { variant: "success" });
|
||||
} catch {
|
||||
toast.error(t("settings.general.browserData.error"));
|
||||
|
||||
@@ -9,26 +9,31 @@ import {
|
||||
type BrowserIndexState,
|
||||
type BrowserRecord,
|
||||
type BrowserRecordPatch,
|
||||
type BrowserRoutingMode,
|
||||
type BrowserViewport,
|
||||
createBrowserRecord,
|
||||
normalizeBrowserIndexState,
|
||||
normalizeBrowserUrl,
|
||||
removeBrowserFromIndex,
|
||||
resolveBrowserRoutingMode,
|
||||
sanitizeBrowsersForPersist,
|
||||
trimNonEmpty,
|
||||
} from "./state";
|
||||
|
||||
export {
|
||||
createFixedBrowserViewport,
|
||||
resolveBrowserRoutingMode,
|
||||
RESPONSIVE_BROWSER_VIEWPORT,
|
||||
type BrowserRecord,
|
||||
type BrowserRoutingMode,
|
||||
type BrowserViewport,
|
||||
} from "./state";
|
||||
|
||||
interface BrowserStoreState extends BrowserIndexState {
|
||||
createBrowser: (input?: { initialUrl?: string }) => string;
|
||||
createBrowser: (input?: { initialUrl?: string; routingMode?: BrowserRoutingMode }) => string;
|
||||
updateBrowser: (browserId: string, patch: BrowserRecordPatch) => void;
|
||||
setBrowserViewport: (browserId: string, viewport: BrowserViewport) => void;
|
||||
setBrowserRoutingMode: (browserId: string, routingMode: BrowserRoutingMode) => void;
|
||||
removeBrowser: (browserId: string) => void;
|
||||
}
|
||||
|
||||
@@ -52,6 +57,7 @@ export const useBrowserStore = create<BrowserStoreState>()(
|
||||
const record = createBrowserRecord({
|
||||
browserId,
|
||||
initialUrl: input?.initialUrl,
|
||||
routingMode: input?.routingMode,
|
||||
now: Date.now(),
|
||||
});
|
||||
|
||||
@@ -70,6 +76,9 @@ export const useBrowserStore = create<BrowserStoreState>()(
|
||||
setBrowserViewport: (browserId, viewport) => {
|
||||
set((state) => applyBrowserPatch(state, browserId, { viewport }));
|
||||
},
|
||||
setBrowserRoutingMode: (browserId, routingMode) => {
|
||||
set((state) => applyBrowserPatch(state, browserId, { routingMode }));
|
||||
},
|
||||
removeBrowser: (browserId) => {
|
||||
set((state) => removeBrowserFromIndex(state, browserId));
|
||||
},
|
||||
@@ -94,7 +103,10 @@ export function getBrowserRecord(browserId: string): BrowserRecord | null {
|
||||
return useBrowserStore.getState().browsersById[normalizedBrowserId] ?? null;
|
||||
}
|
||||
|
||||
export function createWorkspaceBrowser(input?: { initialUrl?: string }): {
|
||||
export function createWorkspaceBrowser(input?: {
|
||||
initialUrl?: string;
|
||||
routingMode?: BrowserRoutingMode;
|
||||
}): {
|
||||
browserId: string;
|
||||
url: string;
|
||||
} {
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
normalizeBrowserIndexState,
|
||||
normalizeBrowserUrl,
|
||||
removeBrowserFromIndex,
|
||||
resolveBrowserRoutingMode,
|
||||
sanitizeBrowsersForPersist,
|
||||
} from "./state";
|
||||
|
||||
@@ -188,4 +189,23 @@ describe("normalizeBrowserIndexState", () => {
|
||||
normalizeBrowserIndexState({ browsersById: { b1: legacy } }).browsersById.b1?.viewport,
|
||||
).toEqual({ mode: "responsive" });
|
||||
});
|
||||
|
||||
it("supports optional routingMode and defaults to host for remote workspaces and local for local workspaces", () => {
|
||||
const legacy = createBrowserRecord({
|
||||
browserId: "b1",
|
||||
initialUrl: "http://localhost:3000",
|
||||
now: 0,
|
||||
});
|
||||
expect(legacy.routingMode).toBeUndefined();
|
||||
expect(resolveBrowserRoutingMode(legacy, true)).toBe("host");
|
||||
expect(resolveBrowserRoutingMode(legacy, false)).toBe("local");
|
||||
|
||||
const updated = applyBrowserPatch(withRecords([legacy]), "b1", { routingMode: "local" });
|
||||
expect(updated.browsersById.b1?.routingMode).toBe("local");
|
||||
expect(resolveBrowserRoutingMode(updated.browsersById.b1, true)).toBe("local");
|
||||
|
||||
const persisted = sanitizeBrowsersForPersist(updated);
|
||||
const rehydrated = normalizeBrowserIndexState(persisted);
|
||||
expect(rehydrated.browsersById.b1?.routingMode).toBe("local");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -4,6 +4,8 @@ export type BrowserViewport =
|
||||
| { mode: "responsive" }
|
||||
| { mode: "fixed"; width: number; height: number };
|
||||
|
||||
export type BrowserRoutingMode = "host" | "local";
|
||||
|
||||
export const RESPONSIVE_BROWSER_VIEWPORT: BrowserViewport = { mode: "responsive" };
|
||||
|
||||
export interface BrowserRecord {
|
||||
@@ -16,6 +18,7 @@ export interface BrowserRecord {
|
||||
faviconUrl: string | null;
|
||||
lastError: string | null;
|
||||
viewport: BrowserViewport;
|
||||
routingMode?: BrowserRoutingMode;
|
||||
createdAt: number;
|
||||
}
|
||||
|
||||
@@ -34,6 +37,8 @@ const BrowserViewportSchema = z.discriminatedUnion("mode", [
|
||||
}),
|
||||
]);
|
||||
|
||||
const BrowserRoutingModeSchema = z.enum(["host", "local"]);
|
||||
|
||||
const BrowserRecordSchema = z.strictObject({
|
||||
browserId: z.string(),
|
||||
url: z.string(),
|
||||
@@ -44,6 +49,7 @@ const BrowserRecordSchema = z.strictObject({
|
||||
faviconUrl: z.string().nullable(),
|
||||
lastError: z.string().nullable(),
|
||||
viewport: BrowserViewportSchema.optional().default(RESPONSIVE_BROWSER_VIEWPORT),
|
||||
routingMode: BrowserRoutingModeSchema.optional(),
|
||||
createdAt: z.number(),
|
||||
});
|
||||
|
||||
@@ -104,9 +110,20 @@ export function normalizeBrowserUrl(value: string | null | undefined): string {
|
||||
return `https://${trimmed}`;
|
||||
}
|
||||
|
||||
export function resolveBrowserRoutingMode(
|
||||
record: Pick<BrowserRecord, "routingMode"> | null | undefined,
|
||||
isRemoteHost: boolean,
|
||||
): BrowserRoutingMode {
|
||||
if (!isRemoteHost) {
|
||||
return "local";
|
||||
}
|
||||
return record?.routingMode === "local" ? "local" : "host";
|
||||
}
|
||||
|
||||
export function createBrowserRecord(input: {
|
||||
browserId: string;
|
||||
initialUrl: string | null | undefined;
|
||||
routingMode?: BrowserRoutingMode;
|
||||
now: number;
|
||||
}): BrowserRecord {
|
||||
return {
|
||||
@@ -119,6 +136,7 @@ export function createBrowserRecord(input: {
|
||||
faviconUrl: null,
|
||||
lastError: null,
|
||||
viewport: RESPONSIVE_BROWSER_VIEWPORT,
|
||||
...(input.routingMode ? { routingMode: input.routingMode } : {}),
|
||||
createdAt: input.now,
|
||||
};
|
||||
}
|
||||
@@ -155,6 +173,7 @@ export function applyBrowserPatch<S extends BrowserIndexState>(
|
||||
nextRecord.canGoForward === existing.canGoForward &&
|
||||
nextRecord.faviconUrl === existing.faviconUrl &&
|
||||
nextRecord.lastError === existing.lastError &&
|
||||
nextRecord.routingMode === existing.routingMode &&
|
||||
browserViewportsEqual(nextRecord.viewport, existing.viewport)
|
||||
) {
|
||||
return state;
|
||||
|
||||
@@ -17,7 +17,7 @@ const ThemedRotateCw = withUnistyles(RotateCw, (theme) => ({
|
||||
color: theme.colors.foregroundMuted,
|
||||
}));
|
||||
|
||||
export function DesktopNotificationsSection() {
|
||||
export function DesktopNotificationsSection({ title }: { title?: string } = {}) {
|
||||
const { t } = useTranslation();
|
||||
const { settings, isSaving, updateSettings } = useDesktopSettings();
|
||||
const {
|
||||
@@ -85,7 +85,10 @@ export function DesktopNotificationsSection() {
|
||||
const notificationsGranted = snapshot?.notifications.state === "granted";
|
||||
|
||||
return (
|
||||
<SettingsSection title={t("settings.notifications.title")} trailing={refreshButton}>
|
||||
<SettingsSection
|
||||
title={title ?? t("settings.notifications.desktop.title")}
|
||||
trailing={refreshButton}
|
||||
>
|
||||
<View style={settingsStyles.card}>
|
||||
<DesktopPermissionRow
|
||||
title={t("settings.notifications.permission")}
|
||||
|
||||
@@ -144,6 +144,42 @@ export interface DesktopAttachedBrowserRegistration {
|
||||
webContentsId: number;
|
||||
}
|
||||
|
||||
export type DesktopBrowserProxyTarget =
|
||||
| {
|
||||
type: "directTcp";
|
||||
endpoint: string;
|
||||
useTls?: boolean;
|
||||
}
|
||||
| {
|
||||
type: "remoteSsh";
|
||||
host: string;
|
||||
sshPort?: number;
|
||||
daemonPort?: number;
|
||||
}
|
||||
| {
|
||||
type: "relay";
|
||||
serverId: string;
|
||||
relayEndpoint: string;
|
||||
useTls?: boolean;
|
||||
daemonPublicKeyB64: string;
|
||||
minimumSecurityMode?: "protected";
|
||||
};
|
||||
|
||||
export type DesktopBrowserProxyStatus = "idle" | "connecting" | "ready" | "reconnecting" | "error";
|
||||
|
||||
export interface DesktopBrowserProxyStatusSnapshot {
|
||||
serverId: string;
|
||||
partition: string;
|
||||
status: DesktopBrowserProxyStatus;
|
||||
error: string | null;
|
||||
socksPort: number | null;
|
||||
}
|
||||
|
||||
export interface DesktopBrowserProxyTicketRequestEvent {
|
||||
requestId: string;
|
||||
serverId: string;
|
||||
}
|
||||
|
||||
export interface DesktopBrowserBridge {
|
||||
setShortcutPolicy?: (input: BrowserKeyboardPolicy) => Promise<void>;
|
||||
readonly profilePartition?: string;
|
||||
@@ -155,7 +191,23 @@ export interface DesktopBrowserBridge {
|
||||
}) => Promise<void>;
|
||||
focus?: (browserId: string) => Promise<boolean>;
|
||||
openDevTools?: (browserId: string) => Promise<unknown>;
|
||||
clearProfile?: (legacyBrowserIds: string[]) => Promise<void>;
|
||||
clearProfile?: (legacyBrowserIds: string[], hostServerIds?: string[]) => Promise<void>;
|
||||
ensureHostProxy?: (input: {
|
||||
serverId: string;
|
||||
target: DesktopBrowserProxyTarget;
|
||||
forceReconnect?: boolean;
|
||||
}) => Promise<DesktopBrowserProxyStatusSnapshot>;
|
||||
updateHostProxyTarget?: (input: {
|
||||
serverId: string;
|
||||
target: DesktopBrowserProxyTarget;
|
||||
}) => Promise<void>;
|
||||
getHostProxyStatus?: (serverId: string) => Promise<DesktopBrowserProxyStatusSnapshot | null>;
|
||||
releaseHostProxy?: (serverId: string) => Promise<void>;
|
||||
deliverProxyTicket?: (input: {
|
||||
requestId: string;
|
||||
ticket?: string;
|
||||
error?: string;
|
||||
}) => Promise<void>;
|
||||
executeAutomationCommand?: (
|
||||
request: BrowserAutomationExecuteRequest,
|
||||
) => Promise<BrowserAutomationExecuteResponse["payload"]>;
|
||||
|
||||
@@ -60,6 +60,7 @@ export interface UseAgentFormStateResult {
|
||||
setModelFromUser: (modelId: string) => void;
|
||||
selectedThinkingOptionId: string;
|
||||
setThinkingOptionFromUser: (thinkingOptionId: string, retainedOptions?: ProviderOptions) => void;
|
||||
selectedSystemPrompt: string;
|
||||
workingDir: string;
|
||||
providerDefinitions: AgentProviderDefinition[];
|
||||
providerDefinitionMap: Map<AgentProvider, AgentProviderDefinition>;
|
||||
@@ -345,6 +346,7 @@ export function useAgentFormState(options: UseAgentFormStateOptions): UseAgentFo
|
||||
modelId: profile.modelId,
|
||||
modeId: profile.modeId,
|
||||
thinkingOptionId: profile.thinkingOptionId,
|
||||
systemPrompt: profile.systemPrompt,
|
||||
providerDef,
|
||||
providerModels,
|
||||
providerPrefs,
|
||||
@@ -495,6 +497,7 @@ export function useAgentFormState(options: UseAgentFormStateOptions): UseAgentFo
|
||||
setModelFromUser,
|
||||
selectedThinkingOptionId: formState.thinkingOptionId,
|
||||
setThinkingOptionFromUser,
|
||||
selectedSystemPrompt: formState.systemPrompt,
|
||||
workingDir,
|
||||
providerDefinitions,
|
||||
providerDefinitionMap,
|
||||
@@ -524,6 +527,7 @@ export function useAgentFormState(options: UseAgentFormStateOptions): UseAgentFo
|
||||
formState.modeId,
|
||||
formState.model,
|
||||
formState.thinkingOptionId,
|
||||
formState.systemPrompt,
|
||||
workingDir,
|
||||
setModeFromUser,
|
||||
setModelFromUser,
|
||||
|
||||
@@ -55,6 +55,10 @@ import {
|
||||
type WorkspaceTitleSource,
|
||||
} from "./storage";
|
||||
|
||||
export {
|
||||
DEFAULT_NOTIFICATION_PREFERENCES,
|
||||
type NotificationPreferences,
|
||||
} from "@getpaseo/protocol/notification-preferences";
|
||||
export {
|
||||
APP_SETTINGS_KEY,
|
||||
DEFAULT_APP_SETTINGS,
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { QueryClient } from "@tanstack/react-query";
|
||||
import { DEFAULT_NOTIFICATION_PREFERENCES } from "@getpaseo/protocol/notification-preferences";
|
||||
import {
|
||||
APP_SETTINGS_KEY,
|
||||
APP_SETTINGS_QUERY_KEY,
|
||||
@@ -1213,3 +1214,68 @@ describe("font family CSS safety", () => {
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
describe("notification preferences storage", () => {
|
||||
it("defaults notifications to DEFAULT_NOTIFICATION_PREFERENCES when storage is empty", async () => {
|
||||
const deps = makeDeps();
|
||||
const settings = await loadAppSettingsFromStorage(deps);
|
||||
expect(settings.notifications).toEqual(DEFAULT_NOTIFICATION_PREFERENCES);
|
||||
});
|
||||
|
||||
it("persists and reloads custom notification preferences", async () => {
|
||||
const deps = makeDeps();
|
||||
const queryClient = new QueryClient();
|
||||
const notifications = {
|
||||
enabled: true,
|
||||
events: {
|
||||
agentPermission: true,
|
||||
agentError: false,
|
||||
agentFinished: true,
|
||||
terminalNeedsInput: false,
|
||||
terminalFinished: true,
|
||||
},
|
||||
plugins: {
|
||||
enabled: true,
|
||||
muted: ["ci-bot", "deploy-bot"],
|
||||
},
|
||||
};
|
||||
|
||||
await saveAppSettings({ queryClient, deps, updates: { notifications } });
|
||||
expect((await loadAppSettingsFromStorage(deps)).notifications).toEqual(notifications);
|
||||
});
|
||||
|
||||
it("normalizes partial and malformed notification preferences on load", async () => {
|
||||
const deps = makeDeps({
|
||||
storage: createInMemoryKeyValueStorage({
|
||||
[APP_SETTINGS_KEY]: JSON.stringify({
|
||||
vimKeybindings: true,
|
||||
notifications: {
|
||||
enabled: "invalid",
|
||||
events: {
|
||||
agentFinished: true,
|
||||
agentError: "nope",
|
||||
},
|
||||
plugins: {
|
||||
enabled: true,
|
||||
muted: [" zeta ", "", 42, "alpha", "zeta"],
|
||||
},
|
||||
},
|
||||
}),
|
||||
}),
|
||||
});
|
||||
|
||||
const settings = await loadAppSettingsFromStorage(deps);
|
||||
expect(settings.vimKeybindings).toBe(true);
|
||||
expect(settings.notifications).toEqual({
|
||||
enabled: true,
|
||||
events: {
|
||||
...DEFAULT_NOTIFICATION_PREFERENCES.events,
|
||||
agentFinished: true,
|
||||
},
|
||||
plugins: {
|
||||
enabled: true,
|
||||
muted: ["alpha", "zeta"],
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
import { isSyntaxThemeId, type SyntaxThemeId } from "@getpaseo/highlight";
|
||||
import type { ActiveTurnBehavior } from "@getpaseo/protocol/messages";
|
||||
import {
|
||||
DEFAULT_NOTIFICATION_PREFERENCES,
|
||||
normalizeNotificationPreferences,
|
||||
type NotificationPreferences,
|
||||
} from "@getpaseo/protocol/notification-preferences";
|
||||
import type { QueryClient } from "@tanstack/react-query";
|
||||
import type { DesktopSettings } from "@/desktop/settings/desktop-settings";
|
||||
import type { AppLanguage } from "@/i18n/locales";
|
||||
@@ -116,6 +121,7 @@ export interface AppSettings {
|
||||
/** Desktop-only preferences for implicit opens into the ordinary side pane. */
|
||||
openInSidePane: OpenInSidePanePreferences;
|
||||
pullRequestOpenLocation: PullRequestOpenLocation;
|
||||
notifications: NotificationPreferences;
|
||||
}
|
||||
|
||||
export type AppSettingsUpdate =
|
||||
@@ -173,6 +179,7 @@ export const DEFAULT_CLIENT_SETTINGS: AppSettings = {
|
||||
filePanelAssociations: {},
|
||||
openInSidePane: DEFAULT_OPEN_IN_SIDE_PANE_PREFERENCES,
|
||||
pullRequestOpenLocation: "explorer",
|
||||
notifications: DEFAULT_NOTIFICATION_PREFERENCES,
|
||||
};
|
||||
|
||||
export const DEFAULT_APP_SETTINGS: Settings = {
|
||||
@@ -302,6 +309,10 @@ const StoredAppSettingsSchema = z
|
||||
legacyPullRequestsInSidePane: undefined,
|
||||
}),
|
||||
pullRequestOpenLocation: z.enum(["main", "side", "explorer"]).optional(),
|
||||
notifications: z
|
||||
.unknown()
|
||||
.transform((value) => normalizeNotificationPreferences(value))
|
||||
.catch(DEFAULT_NOTIFICATION_PREFERENCES),
|
||||
// COMPAT(explorerSidebarRouting): replaced by source-specific side-pane preferences in v0.6.
|
||||
openSupportingTabsInSidePanel: z.boolean().optional().catch(undefined),
|
||||
// COMPAT(rendererDesktopSettings): these fields used to share this renderer-owned key.
|
||||
|
||||
@@ -656,6 +656,24 @@ export const ar: TranslationResources = {
|
||||
invalidUrl: "متصفح غير صالح URL",
|
||||
unsupportedProtocol: "متصفح محظور غير مدعوم URL:{{protocol}}",
|
||||
},
|
||||
routing: {
|
||||
tooltipHost: "التصفح عبر {{hostName}}. انقر للتصفح محلياً.",
|
||||
tooltipLocal: "التصفح محلياً. انقر للتصفح عبر {{hostName}}.",
|
||||
switchToLocal: "تبديل توجيه المتصفح من {{hostName}} إلى محلي",
|
||||
switchToHost: "تبديل توجيه المتصفح من محلي إلى {{hostName}}",
|
||||
},
|
||||
proxy: {
|
||||
connecting: "جارٍ الاتصال بـ {{hostName}}...",
|
||||
reconnecting: "جارٍ إعادة الاتصال بـ {{hostName}}...",
|
||||
updateTitle: "حدّث {{hostName}} للتصفح عبر هذا المضيف",
|
||||
updateDescription: "لا يدعم هذا المضيف وكيل المتصفح بعد.",
|
||||
routedTitle: "وكيل المتصفح غير متاح للمضيفين الموجَّهين",
|
||||
routedDescription: "اتصل مباشرة بهذا المضيف أو تصفح محلياً.",
|
||||
offlineTitle: "{{hostName}} غير متصل",
|
||||
offlineDescription: "انتظر إعادة اتصال المضيف أو تصفح محلياً.",
|
||||
errorTitle: "تعذر الاتصال بوكيل المتصفح",
|
||||
browseLocally: "التصفح محلياً",
|
||||
},
|
||||
},
|
||||
terminal: {
|
||||
hostDisconnected: "Host غير متصل",
|
||||
@@ -2476,6 +2494,47 @@ export const ar: TranslationResources = {
|
||||
},
|
||||
notifications: {
|
||||
title: "الإشعارات",
|
||||
enabled: {
|
||||
label: "تفعيل الإشعارات",
|
||||
description: "تلقّي الإشعارات من الوكلاء والطرفيات والإضافات على هذا الجهاز",
|
||||
pausedDescription: "جميع الإشعارات، بما في ذلك الإضافات، متوقفة مؤقتًا على هذا الجهاز",
|
||||
},
|
||||
events: {
|
||||
title: "الأحداث",
|
||||
agentPermission: {
|
||||
label: "الوكيل يحتاج إلى إذن",
|
||||
description: "الموافقات والخطط والأسئلة",
|
||||
},
|
||||
agentError: {
|
||||
label: "تعطّل الوكيل بخطأ",
|
||||
description: "عندما يتوقف الوكيل بسبب خطأ",
|
||||
},
|
||||
agentFinished: {
|
||||
label: "انتهى الوكيل",
|
||||
description: "عندما يكمل الوكيل دورة عمل",
|
||||
},
|
||||
terminalNeedsInput: {
|
||||
label: "الطرفية تنتظر إدخالًا",
|
||||
description: "عندما ينتظر أمر الطرفية إدخالًا",
|
||||
},
|
||||
terminalFinished: {
|
||||
label: "انتهى أمر الطرفية",
|
||||
description: "عندما ينتهي أمر في الطرفية",
|
||||
},
|
||||
},
|
||||
plugins: {
|
||||
title: "الإضافات",
|
||||
enabled: {
|
||||
label: "إشعارات الإضافات",
|
||||
description: "السماح للإضافات المثبتة بإرسال إشعارات",
|
||||
},
|
||||
empty: "تظهر الإضافات المثبتة هنا لكتمها بشكل فردي",
|
||||
},
|
||||
legacyHostTitle: "حدّث المضيف لتفضيلات الإشعارات الفورية",
|
||||
legacyHostHint: "حدّث المضيفين المتصلين لمزامنة تفضيلات الإشعارات المخصصة من هذا الجهاز",
|
||||
desktop: {
|
||||
title: "النظام",
|
||||
},
|
||||
permission: "إذن الإشعارات",
|
||||
refreshAccessibility: "تحديث إذن الإشعارات",
|
||||
playSound: "تشغيل صوت",
|
||||
@@ -3111,6 +3170,8 @@ export const ar: TranslationResources = {
|
||||
},
|
||||
agentProfiles: {
|
||||
sectionTitle: "ملفات تعريف الوكيل",
|
||||
sectionDescription:
|
||||
"احفظ إعدادات الوكيل لاختيارها بسرعة ولكي يستخدمها الوكلاء عند تفويض العمل",
|
||||
unavailable: "اتصل بهذا المضيف لإدارة ملفات تعريف الوكيل",
|
||||
unsupported: "يشغّل هذا المضيف نسخة Daemon لا تدعم ملفات تعريف الوكيل بعد",
|
||||
emptyState: "لا توجد ملفات تعريف بعد. أضف واحدًا لبدء الوكلاء من مزود ونموذج محفوظين.",
|
||||
@@ -3134,6 +3195,9 @@ export const ar: TranslationResources = {
|
||||
featuresLabel: "السمات",
|
||||
featureCount: "{{count}} سمة",
|
||||
featureCountOne: "{{count}} سمة",
|
||||
systemPromptLabel: "موجه النظام",
|
||||
systemPromptPlaceholder: "ركز على التخطيط وإمكانية الوصول ورموز التصميم.",
|
||||
systemPromptHint: "ينطبق على الوكلاء الجدد فقط",
|
||||
notesLabel: "متى يُستخدم",
|
||||
notesPlaceholder: "استخدمه لعمل الواجهة — المكونات والتخطيط ورموز التصميم.",
|
||||
notesHint: "يساعد الوكلاء على اختيار ملف التعريف هذا عند بدء وكيل آخر.",
|
||||
|
||||
@@ -655,6 +655,24 @@ export const en = {
|
||||
invalidUrl: "Invalid browser URL",
|
||||
unsupportedProtocol: "Blocked unsupported browser URL: {{protocol}}",
|
||||
},
|
||||
routing: {
|
||||
tooltipHost: "Browsing through {{hostName}}. Click to browse locally.",
|
||||
tooltipLocal: "Browsing locally. Click to browse through {{hostName}}.",
|
||||
switchToLocal: "Switch browser routing from {{hostName}} to Local",
|
||||
switchToHost: "Switch browser routing from Local to {{hostName}}",
|
||||
},
|
||||
proxy: {
|
||||
connecting: "Connecting to {{hostName}}...",
|
||||
reconnecting: "Reconnecting to {{hostName}}...",
|
||||
updateTitle: "Update {{hostName}} to browse through this host",
|
||||
updateDescription: "This host does not support browser proxying yet.",
|
||||
routedTitle: "Browser proxy is not available for routed hosts",
|
||||
routedDescription: "Connect directly to this host or browse locally.",
|
||||
offlineTitle: "{{hostName}} is offline",
|
||||
offlineDescription: "Wait for the host to reconnect or browse locally.",
|
||||
errorTitle: "Could not connect browser proxy",
|
||||
browseLocally: "Browse locally",
|
||||
},
|
||||
},
|
||||
terminal: {
|
||||
hostDisconnected: "Host is not connected",
|
||||
@@ -2508,6 +2526,48 @@ export const en = {
|
||||
},
|
||||
notifications: {
|
||||
title: "Notifications",
|
||||
enabled: {
|
||||
label: "Enable notifications",
|
||||
description: "Receive notifications from agents, terminals, and plugins on this device",
|
||||
pausedDescription: "All notifications, including plugins, are paused on this device",
|
||||
},
|
||||
events: {
|
||||
title: "Events",
|
||||
agentPermission: {
|
||||
label: "Agent needs permission",
|
||||
description: "Approvals, plans, and questions",
|
||||
},
|
||||
agentError: {
|
||||
label: "Agent errored",
|
||||
description: "When an agent stops with an error",
|
||||
},
|
||||
agentFinished: {
|
||||
label: "Agent finished",
|
||||
description: "When an agent completes a turn",
|
||||
},
|
||||
terminalNeedsInput: {
|
||||
label: "Terminal needs input",
|
||||
description: "When a terminal command is waiting for input",
|
||||
},
|
||||
terminalFinished: {
|
||||
label: "Terminal finished",
|
||||
description: "When a terminal command finishes",
|
||||
},
|
||||
},
|
||||
plugins: {
|
||||
title: "Plugins",
|
||||
enabled: {
|
||||
label: "Plugin notifications",
|
||||
description: "Allow installed plugins to send notifications",
|
||||
},
|
||||
empty: "Installed plugins appear here so you can mute them individually",
|
||||
},
|
||||
legacyHostTitle: "Update host for push preferences",
|
||||
legacyHostHint:
|
||||
"Update connected hosts to sync custom push notification preferences from this device",
|
||||
desktop: {
|
||||
title: "System",
|
||||
},
|
||||
permission: "Notification permission",
|
||||
refreshAccessibility: "Refresh notification permission",
|
||||
playSound: "Play sound",
|
||||
@@ -3210,6 +3270,8 @@ export const en = {
|
||||
},
|
||||
agentProfiles: {
|
||||
sectionTitle: "Agent profiles",
|
||||
sectionDescription:
|
||||
"Save agent settings that you can pick quickly and that agents can use to delegate work",
|
||||
unavailable: "Connect to this host to manage agent profiles",
|
||||
unsupported: "This host runs a daemon that does not support agent profiles yet",
|
||||
emptyState: "No profiles yet. Add one to start agents from a saved provider and model.",
|
||||
@@ -3233,6 +3295,9 @@ export const en = {
|
||||
featuresLabel: "Features",
|
||||
featureCount: "{{count}} features",
|
||||
featureCountOne: "{{count}} feature",
|
||||
systemPromptLabel: "System prompt",
|
||||
systemPromptPlaceholder: "Focus on layout, accessibility, and design tokens.",
|
||||
systemPromptHint: "Applies to new agents only",
|
||||
notesLabel: "When to use",
|
||||
notesPlaceholder: "Use for UI work — components, layout and design tokens.",
|
||||
notesHint: "Tells agents when to pick this profile",
|
||||
|
||||
@@ -662,6 +662,24 @@ export const es: TranslationResources = {
|
||||
invalidUrl: "Navegador no válidoURL",
|
||||
unsupportedProtocol: "Navegador bloqueado no compatibleURL:{{protocol}}",
|
||||
},
|
||||
routing: {
|
||||
tooltipHost: "Navegando a través de {{hostName}}. Haz clic para navegar localmente.",
|
||||
tooltipLocal: "Navegando localmente. Haz clic para navegar a través de {{hostName}}.",
|
||||
switchToLocal: "Cambiar el enrutamiento del navegador de {{hostName}} a Local",
|
||||
switchToHost: "Cambiar el enrutamiento del navegador de Local a {{hostName}}",
|
||||
},
|
||||
proxy: {
|
||||
connecting: "Conectando con {{hostName}}...",
|
||||
reconnecting: "Reconectando con {{hostName}}...",
|
||||
updateTitle: "Actualiza {{hostName}} para navegar a través de este host",
|
||||
updateDescription: "Este host todavía no admite el proxy del navegador.",
|
||||
routedTitle: "El proxy del navegador no está disponible para hosts enrutados",
|
||||
routedDescription: "Conéctate directamente a este host o navega localmente.",
|
||||
offlineTitle: "{{hostName}} está desconectado",
|
||||
offlineDescription: "Espera a que el host se reconecte o navega localmente.",
|
||||
errorTitle: "No se pudo conectar el proxy del navegador",
|
||||
browseLocally: "Navegar localmente",
|
||||
},
|
||||
},
|
||||
terminal: {
|
||||
hostDisconnected: "Hostno está conectado",
|
||||
@@ -2496,6 +2514,49 @@ export const es: TranslationResources = {
|
||||
},
|
||||
notifications: {
|
||||
title: "Notificaciones",
|
||||
enabled: {
|
||||
label: "Activar notificaciones",
|
||||
description: "Recibe notificaciones de agentes, terminales y plugins en este dispositivo",
|
||||
pausedDescription:
|
||||
"Todas las notificaciones, incluidas las de plugins, están en pausa en este dispositivo",
|
||||
},
|
||||
events: {
|
||||
title: "Eventos",
|
||||
agentPermission: {
|
||||
label: "El agente necesita permiso",
|
||||
description: "Aprobaciones, planes y preguntas",
|
||||
},
|
||||
agentError: {
|
||||
label: "Error del agente",
|
||||
description: "Cuando un agente se detiene con un error",
|
||||
},
|
||||
agentFinished: {
|
||||
label: "El agente terminó",
|
||||
description: "Cuando un agente completa un turno",
|
||||
},
|
||||
terminalNeedsInput: {
|
||||
label: "La terminal necesita entrada",
|
||||
description: "Cuando un comando de terminal espera entrada",
|
||||
},
|
||||
terminalFinished: {
|
||||
label: "La terminal terminó",
|
||||
description: "Cuando finaliza un comando de terminal",
|
||||
},
|
||||
},
|
||||
plugins: {
|
||||
title: "Plugins",
|
||||
enabled: {
|
||||
label: "Notificaciones de plugins",
|
||||
description: "Permitir que los plugins instalados envíen notificaciones",
|
||||
},
|
||||
empty: "Los plugins instalados aparecen aquí para que puedas silenciarlos individualmente",
|
||||
},
|
||||
legacyHostTitle: "Actualiza el host para preferencias push",
|
||||
legacyHostHint:
|
||||
"Actualiza los hosts conectados para sincronizar preferencias de notificaciones push desde este dispositivo",
|
||||
desktop: {
|
||||
title: "Sistema",
|
||||
},
|
||||
permission: "Permiso de notificaciones",
|
||||
refreshAccessibility: "Actualizar permiso de notificaciones",
|
||||
playSound: "Reproducir sonido",
|
||||
@@ -3142,6 +3203,8 @@ export const es: TranslationResources = {
|
||||
},
|
||||
agentProfiles: {
|
||||
sectionTitle: "Perfiles de agente",
|
||||
sectionDescription:
|
||||
"Guarda configuraciones de agente que puedes elegir rápido y que los agentes pueden usar para delegar trabajo",
|
||||
unavailable: "Conéctese a este host para administrar perfiles de agente",
|
||||
unsupported: "Este host ejecuta un daemon que aún no admite perfiles de agente",
|
||||
emptyState:
|
||||
@@ -3166,6 +3229,9 @@ export const es: TranslationResources = {
|
||||
featuresLabel: "Características",
|
||||
featureCount: "{{count}} características",
|
||||
featureCountOne: "{{count}} característica",
|
||||
systemPromptLabel: "Aviso del sistema",
|
||||
systemPromptPlaceholder: "Enfócate en el diseño, la accesibilidad y los tokens de diseño.",
|
||||
systemPromptHint: "Solo se aplica a agentes nuevos",
|
||||
notesLabel: "Cuándo usarlo",
|
||||
notesPlaceholder: "Úselo para trabajo de UI: componentes, diseño y tokens de diseño.",
|
||||
notesHint: "Ayuda a los agentes a elegir este perfil al iniciar otro agente.",
|
||||
|
||||
@@ -662,6 +662,24 @@ export const fr: TranslationResources = {
|
||||
invalidUrl: "URL du navigateur invalide",
|
||||
unsupportedProtocol: "URL bloquée, protocole non pris en charge : {{protocol}}",
|
||||
},
|
||||
routing: {
|
||||
tooltipHost: "Navigation via {{hostName}}. Cliquez pour naviguer en local.",
|
||||
tooltipLocal: "Navigation locale. Cliquez pour naviguer via {{hostName}}.",
|
||||
switchToLocal: "Basculer le routage du navigateur de {{hostName}} vers Local",
|
||||
switchToHost: "Basculer le routage du navigateur de Local vers {{hostName}}",
|
||||
},
|
||||
proxy: {
|
||||
connecting: "Connexion à {{hostName}}...",
|
||||
reconnecting: "Reconnexion à {{hostName}}...",
|
||||
updateTitle: "Mettez à jour {{hostName}} pour naviguer via cet hôte",
|
||||
updateDescription: "Cet hôte ne prend pas encore en charge le proxy du navigateur.",
|
||||
routedTitle: "Le proxy du navigateur n’est pas disponible pour les hôtes routés",
|
||||
routedDescription: "Connectez-vous directement à cet hôte ou naviguez en local.",
|
||||
offlineTitle: "{{hostName}} est hors ligne",
|
||||
offlineDescription: "Attendez la reconnexion de l’hôte ou naviguez en local.",
|
||||
errorTitle: "Impossible de connecter le proxy du navigateur",
|
||||
browseLocally: "Naviguer en local",
|
||||
},
|
||||
},
|
||||
terminal: {
|
||||
hostDisconnected: "L’hôte n’est pas connecté",
|
||||
@@ -2495,6 +2513,50 @@ export const fr: TranslationResources = {
|
||||
},
|
||||
notifications: {
|
||||
title: "Notifications",
|
||||
enabled: {
|
||||
label: "Activer les notifications",
|
||||
description: "Recevoir les notifications des agents, terminaux et plugins sur cet appareil",
|
||||
pausedDescription:
|
||||
"Toutes les notifications, y compris celles des plugins, sont suspendues sur cet appareil",
|
||||
},
|
||||
events: {
|
||||
title: "Événements",
|
||||
agentPermission: {
|
||||
label: "L’agent demande une autorisation",
|
||||
description: "Approbations, plans et questions",
|
||||
},
|
||||
agentError: {
|
||||
label: "Erreur de l’agent",
|
||||
description: "Quand un agent s’arrête avec une erreur",
|
||||
},
|
||||
agentFinished: {
|
||||
label: "L’agent a terminé",
|
||||
description: "Quand un agent termine un tour",
|
||||
},
|
||||
terminalNeedsInput: {
|
||||
label: "Le terminal attend une saisie",
|
||||
description: "Quand une commande de terminal attend une saisie",
|
||||
},
|
||||
terminalFinished: {
|
||||
label: "Le terminal a terminé",
|
||||
description: "Quand une commande de terminal se termine",
|
||||
},
|
||||
},
|
||||
plugins: {
|
||||
title: "Plugins",
|
||||
enabled: {
|
||||
label: "Notifications des plugins",
|
||||
description: "Autoriser les plugins installés à envoyer des notifications",
|
||||
},
|
||||
empty:
|
||||
"Les plugins installés apparaissent ici pour les mettre en sourdine individuellement",
|
||||
},
|
||||
legacyHostTitle: "Mettez à jour l’hôte pour les préférences push",
|
||||
legacyHostHint:
|
||||
"Mettez à jour les hôtes connectés pour synchroniser les préférences de notifications push de cet appareil",
|
||||
desktop: {
|
||||
title: "Système",
|
||||
},
|
||||
permission: "Autorisation des notifications",
|
||||
refreshAccessibility: "Actualiser l’autorisation des notifications",
|
||||
playSound: "Émettre un son",
|
||||
@@ -3144,6 +3206,8 @@ export const fr: TranslationResources = {
|
||||
},
|
||||
agentProfiles: {
|
||||
sectionTitle: "Profils d’agent",
|
||||
sectionDescription:
|
||||
"Enregistrez des réglages d’agent à sélectionner rapidement et utilisables par les agents pour déléguer du travail",
|
||||
unavailable: "Connectez-vous à cet hôte pour gérer les profils d’agent",
|
||||
unsupported: "Le daemon de cet hôte ne prend pas encore en charge les profils d’agent",
|
||||
emptyState:
|
||||
@@ -3168,6 +3232,10 @@ export const fr: TranslationResources = {
|
||||
featuresLabel: "Fonctionnalités",
|
||||
featureCount: "{{count}} fonctionnalités",
|
||||
featureCountOne: "{{count}} fonctionnalité",
|
||||
systemPromptLabel: "Prompt système",
|
||||
systemPromptPlaceholder:
|
||||
"Concentre-toi sur la mise en page, l’accessibilité et les jetons de design.",
|
||||
systemPromptHint: "S’applique uniquement aux nouveaux agents",
|
||||
notesLabel: "Quand l’utiliser",
|
||||
notesPlaceholder:
|
||||
"À utiliser pour le travail sur l’UI : composants, mise en page et design tokens.",
|
||||
|
||||
@@ -662,6 +662,24 @@ export const ja: TranslationResources = {
|
||||
invalidUrl: "無効なブラウザURL",
|
||||
unsupportedProtocol: "サポートされていないブラウザURLをブロック: {{protocol}}",
|
||||
},
|
||||
routing: {
|
||||
tooltipHost: "{{hostName}} 経由で閲覧中。クリックしてローカルで閲覧。",
|
||||
tooltipLocal: "ローカルで閲覧中。クリックして {{hostName}} 経由で閲覧。",
|
||||
switchToLocal: "ブラウザルーティングを {{hostName}} からローカルに切り替え",
|
||||
switchToHost: "ブラウザルーティングをローカルから {{hostName}} に切り替え",
|
||||
},
|
||||
proxy: {
|
||||
connecting: "{{hostName}} に接続中...",
|
||||
reconnecting: "{{hostName}} に再接続中...",
|
||||
updateTitle: "このホスト経由で閲覧するには {{hostName}} を更新してください",
|
||||
updateDescription: "このホストはまだブラウザプロキシに対応していません。",
|
||||
routedTitle: "ルーティングされたホストではブラウザプロキシを利用できません",
|
||||
routedDescription: "このホストに直接接続するか、ローカルで閲覧してください。",
|
||||
offlineTitle: "{{hostName}} はオフラインです",
|
||||
offlineDescription: "ホストの再接続を待つか、ローカルで閲覧してください。",
|
||||
errorTitle: "ブラウザプロキシに接続できませんでした",
|
||||
browseLocally: "ローカルで閲覧",
|
||||
},
|
||||
},
|
||||
terminal: {
|
||||
hostDisconnected: "ホストが接続されていません",
|
||||
@@ -2465,6 +2483,48 @@ export const ja: TranslationResources = {
|
||||
},
|
||||
notifications: {
|
||||
title: "通知",
|
||||
enabled: {
|
||||
label: "通知を有効にする",
|
||||
description: "このデバイスでエージェント、ターミナル、プラグインからの通知を受け取ります",
|
||||
pausedDescription: "プラグインを含むすべての通知がこのデバイスで一時停止されています",
|
||||
},
|
||||
events: {
|
||||
title: "イベント",
|
||||
agentPermission: {
|
||||
label: "エージェントが権限を要求",
|
||||
description: "承認、プラン、質問",
|
||||
},
|
||||
agentError: {
|
||||
label: "エージェントのエラー",
|
||||
description: "エージェントがエラーで停止したとき",
|
||||
},
|
||||
agentFinished: {
|
||||
label: "エージェントが完了",
|
||||
description: "エージェントがターンを完了したとき",
|
||||
},
|
||||
terminalNeedsInput: {
|
||||
label: "ターミナルが入力を待機",
|
||||
description: "ターミナルコマンドが入力を待っているとき",
|
||||
},
|
||||
terminalFinished: {
|
||||
label: "ターミナルが完了",
|
||||
description: "ターミナルコマンドが完了したとき",
|
||||
},
|
||||
},
|
||||
plugins: {
|
||||
title: "プラグイン",
|
||||
enabled: {
|
||||
label: "プラグイン通知",
|
||||
description: "インストール済みプラグインによる通知の送信を許可します",
|
||||
},
|
||||
empty: "インストールされたプラグインがここに表示され、個別にミュートできます",
|
||||
},
|
||||
legacyHostTitle: "プッシュ通知設定にはホストの更新が必要です",
|
||||
legacyHostHint:
|
||||
"このデバイスのカスタムプッシュ通知設定を同期するには、接続中のホストを更新してください",
|
||||
desktop: {
|
||||
title: "システム",
|
||||
},
|
||||
permission: "通知の権限",
|
||||
refreshAccessibility: "通知の権限を更新",
|
||||
playSound: "サウンドを再生",
|
||||
@@ -3106,6 +3166,8 @@ export const ja: TranslationResources = {
|
||||
},
|
||||
agentProfiles: {
|
||||
sectionTitle: "エージェントプロファイル",
|
||||
sectionDescription:
|
||||
"素早く選べるエージェント設定を保存します。エージェントが作業を委任するときにも使えます",
|
||||
unavailable: "エージェントプロファイルを管理するにはこのホストに接続してください",
|
||||
unsupported: "このホストで動作するデーモンはまだエージェントプロファイルに対応していません",
|
||||
emptyState:
|
||||
@@ -3130,6 +3192,10 @@ export const ja: TranslationResources = {
|
||||
featuresLabel: "機能",
|
||||
featureCount: "{{count}}個の機能",
|
||||
featureCountOne: "{{count}}個の機能",
|
||||
systemPromptLabel: "システムプロンプト",
|
||||
systemPromptPlaceholder:
|
||||
"レイアウト、アクセシビリティ、デザイントークンに集中してください。",
|
||||
systemPromptHint: "新しいエージェントにのみ適用されます",
|
||||
notesLabel: "使用する場面",
|
||||
notesPlaceholder: "UI作業に使用 — コンポーネント、レイアウト、デザイントークンなど。",
|
||||
notesHint: "別のエージェントを起動するとき、このプロファイルを選ぶために使用されます。",
|
||||
|
||||
@@ -657,6 +657,24 @@ export const ko: TranslationResources = {
|
||||
invalidUrl: "잘못된 브라우저 URL",
|
||||
unsupportedProtocol: "지원되지 않는 브라우저 URL을 차단했습니다: {{protocol}}",
|
||||
},
|
||||
routing: {
|
||||
tooltipHost: "{{hostName}}을(를) 통해 탐색 중입니다. 클릭하여 로컬로 탐색하세요.",
|
||||
tooltipLocal: "로컬로 탐색 중입니다. 클릭하여 {{hostName}}을(를) 통해 탐색하세요.",
|
||||
switchToLocal: "브라우저 라우팅을 {{hostName}}에서 로컬로 전환",
|
||||
switchToHost: "브라우저 라우팅을 로컬에서 {{hostName}}(으)로 전환",
|
||||
},
|
||||
proxy: {
|
||||
connecting: "{{hostName}}에 연결 중...",
|
||||
reconnecting: "{{hostName}}에 다시 연결 중...",
|
||||
updateTitle: "이 호스트를 통해 탐색하려면 {{hostName}}을(를) 업데이트하세요",
|
||||
updateDescription: "이 호스트는 아직 브라우저 프록시를 지원하지 않습니다.",
|
||||
routedTitle: "라우팅된 호스트에서는 브라우저 프록시를 사용할 수 없습니다",
|
||||
routedDescription: "이 호스트에 직접 연결하거나 로컬로 탐색하세요.",
|
||||
offlineTitle: "{{hostName}}이(가) 오프라인입니다",
|
||||
offlineDescription: "호스트가 다시 연결될 때까지 기다리거나 로컬로 탐색하세요.",
|
||||
errorTitle: "브라우저 프록시에 연결할 수 없습니다",
|
||||
browseLocally: "로컬로 탐색",
|
||||
},
|
||||
},
|
||||
terminal: {
|
||||
hostDisconnected: "호스트가 연결되어 있지 않습니다",
|
||||
@@ -2452,6 +2470,47 @@ export const ko: TranslationResources = {
|
||||
},
|
||||
notifications: {
|
||||
title: "알림",
|
||||
enabled: {
|
||||
label: "알림 사용",
|
||||
description: "이 기기에서 에이전트, 터미널, 플러그인 알림을 받습니다",
|
||||
pausedDescription: "플러그인을 포함한 모든 알림이 이 기기에서 일시 중지되었습니다",
|
||||
},
|
||||
events: {
|
||||
title: "이벤트",
|
||||
agentPermission: {
|
||||
label: "에이전트 권한 필요",
|
||||
description: "승인, 계획 및 질문",
|
||||
},
|
||||
agentError: {
|
||||
label: "에이전트 오류",
|
||||
description: "에이전트가 오류로 중단될 때",
|
||||
},
|
||||
agentFinished: {
|
||||
label: "에이전트 완료",
|
||||
description: "에이전트가 턴을 완료할 때",
|
||||
},
|
||||
terminalNeedsInput: {
|
||||
label: "터미널 입력 대기",
|
||||
description: "터미널 명령이 입력을 기다릴 때",
|
||||
},
|
||||
terminalFinished: {
|
||||
label: "터미널 완료",
|
||||
description: "터미널 명령이 완료될 때",
|
||||
},
|
||||
},
|
||||
plugins: {
|
||||
title: "플러그인",
|
||||
enabled: {
|
||||
label: "플러그인 알림",
|
||||
description: "설치된 플러그인이 알림을 보낼 수 있도록 허용",
|
||||
},
|
||||
empty: "설치된 플러그인이 여기에 표시되어 개별적으로 음소거할 수 있습니다",
|
||||
},
|
||||
legacyHostTitle: "푸시 설정을 위해 호스트 업데이트 필요",
|
||||
legacyHostHint: "이 기기의 맞춤 푸시 알림 설정을 동기화하려면 연결된 호스트를 업데이트하세요",
|
||||
desktop: {
|
||||
title: "시스템",
|
||||
},
|
||||
permission: "알림 권한",
|
||||
refreshAccessibility: "알림 권한 새로 고침",
|
||||
playSound: "소리 재생",
|
||||
@@ -3090,6 +3149,8 @@ export const ko: TranslationResources = {
|
||||
},
|
||||
agentProfiles: {
|
||||
sectionTitle: "에이전트 프로필",
|
||||
sectionDescription:
|
||||
"빠르게 선택할 수 있고 에이전트가 작업을 위임할 때도 사용할 수 있는 에이전트 설정을 저장합니다",
|
||||
unavailable: "에이전트 프로필을 관리하려면 이 호스트에 연결하세요",
|
||||
unsupported: "이 호스트에서 실행 중인 데몬은 아직 에이전트 프로필을 지원하지 않습니다",
|
||||
emptyState:
|
||||
@@ -3114,6 +3175,9 @@ export const ko: TranslationResources = {
|
||||
featuresLabel: "기능",
|
||||
featureCount: "기능 {{count}}개",
|
||||
featureCountOne: "기능 {{count}}개",
|
||||
systemPromptLabel: "시스템 프롬프트",
|
||||
systemPromptPlaceholder: "레이아웃, 접근성, 디자인 토큰에 집중하세요.",
|
||||
systemPromptHint: "새 에이전트에만 적용됩니다",
|
||||
notesLabel: "사용 시점",
|
||||
notesPlaceholder: "UI 작업에 사용 — 컴포넌트, 레이아웃, 디자인 토큰.",
|
||||
notesHint: "에이전트가 다른 에이전트를 시작할 때 이 프로필을 선택하는 데 사용됩니다.",
|
||||
|
||||
@@ -661,6 +661,24 @@ export const ptBR: TranslationResources = {
|
||||
invalidUrl: "URL de navegador inválida",
|
||||
unsupportedProtocol: "URL de navegador sem suporte bloqueada: {{protocol}}",
|
||||
},
|
||||
routing: {
|
||||
tooltipHost: "Navegando por {{hostName}}. Clique para navegar localmente.",
|
||||
tooltipLocal: "Navegando localmente. Clique para navegar por {{hostName}}.",
|
||||
switchToLocal: "Alternar roteamento do navegador de {{hostName}} para Local",
|
||||
switchToHost: "Alternar roteamento do navegador de Local para {{hostName}}",
|
||||
},
|
||||
proxy: {
|
||||
connecting: "Conectando a {{hostName}}...",
|
||||
reconnecting: "Reconectando a {{hostName}}...",
|
||||
updateTitle: "Atualize {{hostName}} para navegar por este host",
|
||||
updateDescription: "Este host ainda não oferece suporte ao proxy do navegador.",
|
||||
routedTitle: "O proxy do navegador não está disponível para hosts roteados",
|
||||
routedDescription: "Conecte-se diretamente a este host ou navegue localmente.",
|
||||
offlineTitle: "{{hostName}} está offline",
|
||||
offlineDescription: "Aguarde o host reconectar ou navegue localmente.",
|
||||
errorTitle: "Não foi possível conectar o proxy do navegador",
|
||||
browseLocally: "Navegar localmente",
|
||||
},
|
||||
},
|
||||
terminal: {
|
||||
hostDisconnected: "Host não está conectado",
|
||||
@@ -2480,6 +2498,50 @@ export const ptBR: TranslationResources = {
|
||||
},
|
||||
notifications: {
|
||||
title: "Notificações",
|
||||
enabled: {
|
||||
label: "Ativar notificações",
|
||||
description: "Receba notificações de agentes, terminais e plugins neste dispositivo",
|
||||
pausedDescription:
|
||||
"Todas as notificações, incluindo as de plugins, estão pausadas neste dispositivo",
|
||||
},
|
||||
events: {
|
||||
title: "Eventos",
|
||||
agentPermission: {
|
||||
label: "Agente precisa de permissão",
|
||||
description: "Aprovações, planos e perguntas",
|
||||
},
|
||||
agentError: {
|
||||
label: "Erro no agente",
|
||||
description: "Quando um agente para com erro",
|
||||
},
|
||||
agentFinished: {
|
||||
label: "Agente concluiu",
|
||||
description: "Quando um agente conclui um turno",
|
||||
},
|
||||
terminalNeedsInput: {
|
||||
label: "Terminal aguarda entrada",
|
||||
description: "Quando um comando do terminal aguarda entrada",
|
||||
},
|
||||
terminalFinished: {
|
||||
label: "Terminal concluiu",
|
||||
description: "Quando um comando do terminal termina",
|
||||
},
|
||||
},
|
||||
plugins: {
|
||||
title: "Plugins",
|
||||
enabled: {
|
||||
label: "Notificações de plugins",
|
||||
description: "Permitir que plugins instalados enviem notificações",
|
||||
},
|
||||
empty:
|
||||
"Os plugins instalados aparecem aqui para que você possa silenciá-los individualmente",
|
||||
},
|
||||
legacyHostTitle: "Atualize o host para preferências de push",
|
||||
legacyHostHint:
|
||||
"Atualize os hosts conectados para sincronizar as preferências de notificações push deste dispositivo",
|
||||
desktop: {
|
||||
title: "Sistema",
|
||||
},
|
||||
permission: "Permissão de notificações",
|
||||
refreshAccessibility: "Atualizar permissão de notificações",
|
||||
playSound: "Reproduzir som",
|
||||
@@ -3123,6 +3185,8 @@ export const ptBR: TranslationResources = {
|
||||
},
|
||||
agentProfiles: {
|
||||
sectionTitle: "Perfis de agente",
|
||||
sectionDescription:
|
||||
"Salve configurações de agente para escolher rapidamente e para outros agentes usarem ao delegar trabalho",
|
||||
unavailable: "Conecte-se a este host para gerenciar perfis de agente",
|
||||
unsupported: "Este host executa um daemon que ainda não é compatível com perfis de agente",
|
||||
emptyState:
|
||||
@@ -3147,6 +3211,9 @@ export const ptBR: TranslationResources = {
|
||||
featuresLabel: "Recursos",
|
||||
featureCount: "{{count}} recursos",
|
||||
featureCountOne: "{{count}} recurso",
|
||||
systemPromptLabel: "Prompt do sistema",
|
||||
systemPromptPlaceholder: "Foque em layout, acessibilidade e tokens de design.",
|
||||
systemPromptHint: "Aplica-se apenas a novos agentes",
|
||||
notesLabel: "Quando usar",
|
||||
notesPlaceholder: "Use para trabalho de UI — componentes, layout e tokens de design.",
|
||||
notesHint: "Ajuda os agentes a escolher este perfil ao iniciar outro agente.",
|
||||
|
||||
@@ -664,6 +664,24 @@ export const ru: TranslationResources = {
|
||||
unsupportedProtocol:
|
||||
"URL браузера с неподдерживаемым протоколом заблокирован: {{protocol}}",
|
||||
},
|
||||
routing: {
|
||||
tooltipHost: "Просмотр через {{hostName}}. Нажмите, чтобы перейти в локальный режим.",
|
||||
tooltipLocal: "Локальный просмотр. Нажмите, чтобы просматривать через {{hostName}}.",
|
||||
switchToLocal: "Переключить маршрутизацию браузера с {{hostName}} на локальную",
|
||||
switchToHost: "Переключить маршрутизацию браузера с локальной на {{hostName}}",
|
||||
},
|
||||
proxy: {
|
||||
connecting: "Подключение к {{hostName}}...",
|
||||
reconnecting: "Повторное подключение к {{hostName}}...",
|
||||
updateTitle: "Обновите {{hostName}}, чтобы просматривать через этот хост",
|
||||
updateDescription: "Этот хост пока не поддерживает проксирование браузера.",
|
||||
routedTitle: "Прокси браузера недоступен для маршрутизируемых хостов",
|
||||
routedDescription: "Подключитесь к хосту напрямую или просматривайте локально.",
|
||||
offlineTitle: "{{hostName}} не в сети",
|
||||
offlineDescription: "Дождитесь повторного подключения хоста или просматривайте локально.",
|
||||
errorTitle: "Не удалось подключить прокси браузера",
|
||||
browseLocally: "Просматривать локально",
|
||||
},
|
||||
},
|
||||
terminal: {
|
||||
hostDisconnected: "Хост не подключён",
|
||||
@@ -2481,6 +2499,49 @@ export const ru: TranslationResources = {
|
||||
},
|
||||
notifications: {
|
||||
title: "Уведомления",
|
||||
enabled: {
|
||||
label: "Включить уведомления",
|
||||
description: "Получать уведомления от агентов, терминалов и плагинов на этом устройстве",
|
||||
pausedDescription:
|
||||
"Все уведомления, включая уведомления от плагинов, приостановлены на этом устройстве",
|
||||
},
|
||||
events: {
|
||||
title: "События",
|
||||
agentPermission: {
|
||||
label: "Агенту требуется разрешение",
|
||||
description: "Подтверждения, планы и вопросы",
|
||||
},
|
||||
agentError: {
|
||||
label: "Ошибка агента",
|
||||
description: "Когда агент останавливается из-за ошибки",
|
||||
},
|
||||
agentFinished: {
|
||||
label: "Агент завершил работу",
|
||||
description: "Когда агент завершает ход",
|
||||
},
|
||||
terminalNeedsInput: {
|
||||
label: "Терминал ожидает ввода",
|
||||
description: "Когда команда в терминале ждёт ввода",
|
||||
},
|
||||
terminalFinished: {
|
||||
label: "Терминал завершил команду",
|
||||
description: "Когда команда в терминале завершается",
|
||||
},
|
||||
},
|
||||
plugins: {
|
||||
title: "Плагины",
|
||||
enabled: {
|
||||
label: "Уведомления плагинов",
|
||||
description: "Разрешить установленным плагинам отправлять уведомления",
|
||||
},
|
||||
empty: "Установленные плагины появятся здесь, чтобы вы могли отключать их по отдельности",
|
||||
},
|
||||
legacyHostTitle: "Обновите хост для настроек push-уведомлений",
|
||||
legacyHostHint:
|
||||
"Обновите подключённые хосты для синхронизации настроек push-уведомлений с этого устройства",
|
||||
desktop: {
|
||||
title: "Система",
|
||||
},
|
||||
permission: "Разрешение на уведомления",
|
||||
refreshAccessibility: "Обновить разрешение на уведомления",
|
||||
playSound: "Воспроизводить звук",
|
||||
@@ -3132,6 +3193,8 @@ export const ru: TranslationResources = {
|
||||
},
|
||||
agentProfiles: {
|
||||
sectionTitle: "Профили агентов",
|
||||
sectionDescription:
|
||||
"Сохраняйте настройки агентов, чтобы быстро выбирать их и позволять агентам использовать их при делегировании задач",
|
||||
unavailable: "Подключитесь к этому хосту, чтобы управлять профилями агентов",
|
||||
unsupported: "На этом хосте запущен демон, который пока не поддерживает профили агентов",
|
||||
emptyState:
|
||||
@@ -3156,6 +3219,9 @@ export const ru: TranslationResources = {
|
||||
featuresLabel: "Функции",
|
||||
featureCount: "Функции: {{count}}",
|
||||
featureCountOne: "{{count}} функция",
|
||||
systemPromptLabel: "Системный промпт",
|
||||
systemPromptPlaceholder: "Сосредоточься на вёрстке, доступности и дизайн-токенах.",
|
||||
systemPromptHint: "Применяется только к новым агентам",
|
||||
notesLabel: "Когда использовать",
|
||||
notesPlaceholder: "Используйте для работы над UI — компоненты, макет и токены дизайна.",
|
||||
notesHint: "Помогает агентам выбрать этот профиль при запуске другого агента.",
|
||||
|
||||
@@ -656,6 +656,24 @@ export const zhCN: TranslationResources = {
|
||||
invalidUrl: "浏览器 URL 无效",
|
||||
unsupportedProtocol: "已阻止不支持的浏览器 URL:{{protocol}}",
|
||||
},
|
||||
routing: {
|
||||
tooltipHost: "正在通过 {{hostName}} 浏览。点击切换为本地浏览。",
|
||||
tooltipLocal: "正在本地浏览。点击切换为通过 {{hostName}} 浏览。",
|
||||
switchToLocal: "将浏览器路由从 {{hostName}} 切换为本地",
|
||||
switchToHost: "将浏览器路由从本地切换为 {{hostName}}",
|
||||
},
|
||||
proxy: {
|
||||
connecting: "正在连接到 {{hostName}}...",
|
||||
reconnecting: "正在重新连接到 {{hostName}}...",
|
||||
updateTitle: "请更新 {{hostName}} 以通过此主机浏览",
|
||||
updateDescription: "此主机尚不支持浏览器代理。",
|
||||
routedTitle: "路由主机不支持浏览器代理",
|
||||
routedDescription: "请直接连接到此主机,或改为本地浏览。",
|
||||
offlineTitle: "{{hostName}} 已离线",
|
||||
offlineDescription: "请等待主机重新连接,或改为本地浏览。",
|
||||
errorTitle: "无法连接浏览器代理",
|
||||
browseLocally: "本地浏览",
|
||||
},
|
||||
},
|
||||
terminal: {
|
||||
hostDisconnected: "Host 未连接",
|
||||
@@ -2416,6 +2434,47 @@ export const zhCN: TranslationResources = {
|
||||
},
|
||||
notifications: {
|
||||
title: "通知",
|
||||
enabled: {
|
||||
label: "启用通知",
|
||||
description: "在此设备上接收来自智能体、终端和插件的通知",
|
||||
pausedDescription: "此设备上的所有通知(包括插件通知)均已暂停",
|
||||
},
|
||||
events: {
|
||||
title: "事件",
|
||||
agentPermission: {
|
||||
label: "智能体需要权限",
|
||||
description: "审批、计划与提问",
|
||||
},
|
||||
agentError: {
|
||||
label: "智能体出错",
|
||||
description: "当智能体因错误停止时",
|
||||
},
|
||||
agentFinished: {
|
||||
label: "智能体已完成",
|
||||
description: "当智能体完成一轮回复时",
|
||||
},
|
||||
terminalNeedsInput: {
|
||||
label: "终端等待输入",
|
||||
description: "当终端命令正在等待输入时",
|
||||
},
|
||||
terminalFinished: {
|
||||
label: "终端命令完成",
|
||||
description: "当终端命令执行结束时",
|
||||
},
|
||||
},
|
||||
plugins: {
|
||||
title: "插件",
|
||||
enabled: {
|
||||
label: "插件通知",
|
||||
description: "允许已安装的插件发送通知",
|
||||
},
|
||||
empty: "已安装的插件会显示在这里,方便你单独静音",
|
||||
},
|
||||
legacyHostTitle: "更新主机以同步推送偏好",
|
||||
legacyHostHint: "更新已连接的主机,以同步此设备上的自定义推送通知偏好设置",
|
||||
desktop: {
|
||||
title: "系统",
|
||||
},
|
||||
permission: "通知权限",
|
||||
refreshAccessibility: "刷新通知权限",
|
||||
playSound: "播放声音",
|
||||
@@ -3044,6 +3103,7 @@ export const zhCN: TranslationResources = {
|
||||
},
|
||||
agentProfiles: {
|
||||
sectionTitle: "Agent 配置",
|
||||
sectionDescription: "保存可快速选用的 Agent 设置,Agent 委派工作时也可以使用这些配置",
|
||||
unavailable: "连接到这个 Host 以管理 Agent 配置",
|
||||
unsupported: "此 Host 运行的 Daemon 尚不支持 Agent 配置",
|
||||
emptyState: "还没有配置。添加一个以便使用保存的 Provider 和 Model 启动 Agent。",
|
||||
@@ -3067,6 +3127,9 @@ export const zhCN: TranslationResources = {
|
||||
featuresLabel: "Features",
|
||||
featureCount: "{{count}} 个 Feature",
|
||||
featureCountOne: "{{count}} 个 Feature",
|
||||
systemPromptLabel: "System prompt",
|
||||
systemPromptPlaceholder: "专注于布局、无障碍和设计 token。",
|
||||
systemPromptHint: "仅适用于新 Agent",
|
||||
notesLabel: "适用场景",
|
||||
notesPlaceholder: "用于 UI 工作 — 组件、布局和设计 token。",
|
||||
notesHint: "帮助 Agent 在启动另一个 Agent 时选择此配置。",
|
||||
|
||||
@@ -52,6 +52,26 @@ describe("notification open", () => {
|
||||
{ serverId: "h", workspaceId: "w", terminalId: "t", agentId: "a" },
|
||||
{ kind: "terminal", serverId: "h", workspaceId: "w", terminalId: "t" },
|
||||
],
|
||||
[{ kind: "plugin", serverId: "h", pluginId: "p" }, null],
|
||||
[{ kind: "plugin", serverId: "h", notificationId: "n" }, null],
|
||||
[
|
||||
{
|
||||
kind: "plugin",
|
||||
serverId: "h",
|
||||
pluginId: "ci",
|
||||
notificationId: "n-1",
|
||||
open: { type: "screen", screenId: "report", params: { id: "42" } },
|
||||
data: { buildId: 42 },
|
||||
},
|
||||
{
|
||||
kind: "plugin",
|
||||
serverId: "h",
|
||||
pluginId: "ci",
|
||||
notificationId: "n-1",
|
||||
open: { type: "screen", screenId: "report", params: { id: "42" } },
|
||||
data: { buildId: 42 },
|
||||
},
|
||||
],
|
||||
])("parses %j", (data, expected) => {
|
||||
expect(parseNotificationOpenTarget(data)).toEqual(expected);
|
||||
});
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import type { JsonValue } from "@getpaseo/protocol/agent-types";
|
||||
import type { PluginNotificationOpenTarget } from "@getpaseo/protocol/messages";
|
||||
import { buildHostRootRoute } from "@/utils/host-routes";
|
||||
import type { NotificationOpenSource, NotificationTap } from "./source";
|
||||
|
||||
@@ -6,6 +8,14 @@ export const WEB_NOTIFICATION_CLICK_EVENT = "paseo:web-notification-click";
|
||||
export type NotificationOpenTarget =
|
||||
| { kind: "agent"; serverId: string; agentId: string }
|
||||
| { kind: "terminal"; serverId: string; workspaceId: string; terminalId: string }
|
||||
| {
|
||||
kind: "plugin";
|
||||
serverId: string;
|
||||
pluginId: string;
|
||||
notificationId: string;
|
||||
open?: PluginNotificationOpenTarget;
|
||||
data?: Record<string, JsonValue>;
|
||||
}
|
||||
| { kind: "host"; serverId: string };
|
||||
|
||||
function readId(data: object, key: string): string {
|
||||
@@ -13,10 +23,59 @@ function readId(data: object, key: string): string {
|
||||
return typeof value === "string" ? value.trim() : "";
|
||||
}
|
||||
|
||||
function isPlainRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function parsePluginOpenTarget(raw: unknown): PluginNotificationOpenTarget | undefined {
|
||||
if (!isPlainRecord(raw)) return undefined;
|
||||
const type = readId(raw, "type");
|
||||
if (type === "agent") {
|
||||
const agentId = readId(raw, "agentId");
|
||||
return agentId ? { type: "agent", agentId } : undefined;
|
||||
}
|
||||
if (type === "workspace") {
|
||||
const workspaceId = readId(raw, "workspaceId");
|
||||
return workspaceId ? { type: "workspace", workspaceId } : undefined;
|
||||
}
|
||||
if (type === "screen") {
|
||||
const screenId = readId(raw, "screenId");
|
||||
if (!screenId) return undefined;
|
||||
const rawParams = Reflect.get(raw, "params");
|
||||
if (rawParams === undefined) {
|
||||
return { type: "screen", screenId };
|
||||
}
|
||||
if (!isPlainRecord(rawParams)) return undefined;
|
||||
const params: Record<string, string> = {};
|
||||
for (const [key, value] of Object.entries(rawParams)) {
|
||||
if (!key.trim() || typeof value !== "string") return undefined;
|
||||
params[key] = value;
|
||||
}
|
||||
return { type: "screen", screenId, params };
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export function parseNotificationOpenTarget(data: unknown): NotificationOpenTarget | null {
|
||||
if (typeof data !== "object" || data === null || Array.isArray(data)) return null;
|
||||
if (!isPlainRecord(data)) return null;
|
||||
const serverId = readId(data, "serverId");
|
||||
if (!serverId) return null;
|
||||
if (readId(data, "kind") === "plugin") {
|
||||
const pluginId = readId(data, "pluginId");
|
||||
const notificationId = readId(data, "notificationId");
|
||||
if (!pluginId || !notificationId) return null;
|
||||
const open = parsePluginOpenTarget(Reflect.get(data, "open"));
|
||||
const rawData = Reflect.get(data, "data");
|
||||
const payloadData = isPlainRecord(rawData) ? (rawData as Record<string, JsonValue>) : undefined;
|
||||
return {
|
||||
kind: "plugin",
|
||||
serverId,
|
||||
pluginId,
|
||||
notificationId,
|
||||
...(open ? { open } : {}),
|
||||
...(payloadData ? { data: payloadData } : {}),
|
||||
};
|
||||
}
|
||||
const workspaceId = readId(data, "workspaceId");
|
||||
const terminalId = readId(data, "terminalId");
|
||||
if (workspaceId && terminalId) return { kind: "terminal", serverId, workspaceId, terminalId };
|
||||
@@ -30,6 +89,9 @@ interface NotificationOpenRouterDeps {
|
||||
openAgent: (target: { serverId: string; agentId: string }) => void;
|
||||
openRoute: (route: string) => void;
|
||||
openTerminal: (target: Extract<NotificationOpenTarget, { kind: "terminal" }>) => void;
|
||||
openPlugin?: (
|
||||
target: Extract<NotificationOpenTarget, { kind: "plugin" }>,
|
||||
) => void | Promise<void>;
|
||||
whenReadyToNavigate: () => Promise<void>;
|
||||
}
|
||||
|
||||
@@ -45,6 +107,12 @@ export function createNotificationOpenRouter(deps: NotificationOpenRouterDeps) {
|
||||
deps.openAgent({ serverId: target.serverId, agentId: target.agentId });
|
||||
} else if (target?.kind === "terminal") {
|
||||
deps.openTerminal(target);
|
||||
} else if (target?.kind === "plugin") {
|
||||
if (deps.openPlugin) {
|
||||
await deps.openPlugin(target);
|
||||
} else {
|
||||
deps.openRoute(buildHostRootRoute(target.serverId));
|
||||
}
|
||||
} else if (target?.kind === "host") {
|
||||
deps.openRoute(buildHostRootRoute(target.serverId));
|
||||
}
|
||||
|
||||
@@ -1,16 +1,31 @@
|
||||
import { useEffect } from "react";
|
||||
import { router, usePathname, useRootNavigationState, type Href } from "expo-router";
|
||||
import { useHostRegistryStatus } from "@/runtime/host-runtime";
|
||||
import { openPluginNotification } from "@/plugins/notification-open";
|
||||
import { pluginRegistry } from "@/plugins/registry";
|
||||
import { getHostRuntimeStore, useHostRegistryStatus } from "@/runtime/host-runtime";
|
||||
import {
|
||||
navigateToWorkspace,
|
||||
useIsLastWorkspaceSelectionHydrated,
|
||||
} from "@/stores/navigation-active-workspace-store";
|
||||
import { useSidebarViewStore } from "@/stores/sidebar-view-store";
|
||||
import { navigateToAgent } from "@/utils/navigate-to-agent";
|
||||
import { createNotificationOpenRouter } from "../model";
|
||||
import { createNotificationOpenSource } from "../source";
|
||||
|
||||
let ready = false;
|
||||
const waiters = new Set<() => void>();
|
||||
|
||||
function navigateFromNotification(route: string): void {
|
||||
if (!route.startsWith("/settings")) {
|
||||
if (router.canDismiss()) {
|
||||
router.dismissAll();
|
||||
}
|
||||
router.replace(route as Href);
|
||||
return;
|
||||
}
|
||||
router.navigate(route as Href);
|
||||
}
|
||||
|
||||
const notificationRouter = createNotificationOpenRouter({
|
||||
source: createNotificationOpenSource(),
|
||||
openAgent: (target) => navigateToAgent({ ...target, pin: true }),
|
||||
@@ -20,6 +35,18 @@ const notificationRouter = createNotificationOpenRouter({
|
||||
workspaceId,
|
||||
target: { kind: "terminal", terminalId },
|
||||
}),
|
||||
openPlugin: (target) =>
|
||||
openPluginNotification(target, {
|
||||
registry: pluginRegistry,
|
||||
openAgent: (agentTarget) => navigateToAgent({ ...agentTarget, pin: true }),
|
||||
openWorkspace: (workspaceTarget) => navigateToWorkspace(workspaceTarget),
|
||||
openRoute: navigateFromNotification,
|
||||
isHostRegistered: (targetServerId) =>
|
||||
getHostRuntimeStore()
|
||||
.getHosts()
|
||||
.some((host) => host.serverId === targetServerId),
|
||||
focusHost: (targetServerId) => useSidebarViewStore.getState().focusHost(targetServerId),
|
||||
}),
|
||||
openRoute: (route) => router.navigate(route as Href),
|
||||
whenReadyToNavigate: () =>
|
||||
ready
|
||||
|
||||
@@ -14,7 +14,10 @@ import { buildTerminalsQueryKey } from "@/screens/workspace/terminals/state";
|
||||
import { showExplorerSidebar } from "@/workspace-tabs/explorer-sidebar";
|
||||
import { buildWorkspaceTabPersistenceKey } from "@/workspace-tabs/model";
|
||||
import { useIsCompactFormFactor } from "@/constants/layout";
|
||||
import { getIsElectron } from "@/constants/platform";
|
||||
import { createWorkspaceBrowser } from "@/desktop/browser/store";
|
||||
import { useSessionStore } from "@/stores/session-store";
|
||||
import { useWorkspaceLayoutStore } from "@/stores/workspace-layout-store";
|
||||
import { useWorkspaceDirectory, useWorkspaceFields } from "@/stores/session-store-hooks";
|
||||
|
||||
type ListTerminalsPayload = ListTerminalsResponse["payload"];
|
||||
@@ -94,6 +97,24 @@ function TerminalPanel() {
|
||||
workspaceKey: buildWorkspaceTabPersistenceKey({ serverId, workspaceId }),
|
||||
});
|
||||
}, [isCompact, serverId, workspaceId, workspaceDirectory]);
|
||||
const handleOpenBrowserUrl = useCallback(
|
||||
(url: string) => {
|
||||
if (!getIsElectron()) {
|
||||
return;
|
||||
}
|
||||
const workspaceKey = buildWorkspaceTabPersistenceKey({ serverId, workspaceId });
|
||||
if (!workspaceKey) {
|
||||
return;
|
||||
}
|
||||
const { browserId } = createWorkspaceBrowser({ initialUrl: url });
|
||||
useWorkspaceLayoutStore.getState().openTab({
|
||||
workspaceKey,
|
||||
target: { kind: "browser", browserId },
|
||||
intent: "reveal",
|
||||
});
|
||||
},
|
||||
[serverId, workspaceId],
|
||||
);
|
||||
invariant(target.kind === "terminal", "TerminalPanel requires terminal target");
|
||||
|
||||
if (!workspaceDirectory) {
|
||||
@@ -113,6 +134,7 @@ function TerminalPanel() {
|
||||
isPaneFocused={isPaneFocused}
|
||||
onOpenFileExplorer={handleOpenFileExplorer}
|
||||
onOpenWorkspaceFile={openFileInWorkspace}
|
||||
onOpenBrowserUrl={handleOpenBrowserUrl}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -37,6 +37,7 @@ function installation(): InstalledPlugin {
|
||||
themes: [],
|
||||
timelineTransformers: [],
|
||||
timelineRenderers: [],
|
||||
notificationOpenHandlers: [],
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@ import type { SessionOutboundMessage } from "@getpaseo/protocol/messages";
|
||||
import { settingsRpc } from "@getpaseo/plugin";
|
||||
import { syncPluginCatalog } from "./catalog-sync-model";
|
||||
import { createPluginHosts } from "./hosts";
|
||||
import { openPluginNotification } from "./notification-open";
|
||||
import { PluginRegistry } from "./registry";
|
||||
import { pluginSettingsKey } from "./settings/query";
|
||||
import type { InstalledPlugin } from "./types";
|
||||
@@ -391,13 +392,22 @@ it("replaces changed bundles on reconnect and disposes the old installation", as
|
||||
});
|
||||
|
||||
it("replaces an explicitly reloaded bundle even when its source is unchanged", async () => {
|
||||
const h = await connected();
|
||||
let catalogChanges = 0;
|
||||
const h = harness();
|
||||
const stop = h.sync({
|
||||
onCatalogChanged: () => {
|
||||
catalogChanges++;
|
||||
},
|
||||
});
|
||||
cleanups.push(stop);
|
||||
await expect.poll(() => h.registry.getSnapshot().length).toBe(1);
|
||||
const plugin = h.installed();
|
||||
h.client.update({
|
||||
type: "status",
|
||||
payload: { status: "plugin_catalog_changed", pluginId: "reports" },
|
||||
});
|
||||
await expect.poll(() => h.installed() === plugin).toBe(false);
|
||||
expect(catalogChanges).toBe(1);
|
||||
expect(h.disposals()).toBe(1);
|
||||
expect(h.evaluations()).toBe(2);
|
||||
});
|
||||
@@ -504,3 +514,55 @@ it("ignores an in-flight catalog snapshot after disconnect", async () => {
|
||||
expect(h.client.settings.reads).toBe(1);
|
||||
expect(h.evaluations()).toBe(1);
|
||||
});
|
||||
|
||||
it("keeps catalog loading before server_info arrives so cold-launch plugin taps wait for onNotificationOpen", async () => {
|
||||
const h = harness();
|
||||
h.client.catalog = [
|
||||
{
|
||||
id: "ci-alerts",
|
||||
requirements: { paseo: `>=${appPackage.version}` },
|
||||
clientBundle: `(function() { return { default: function(plugin) {
|
||||
plugin.addScreen({ id: "alert", title: "Alert", Component: function() { return null; } });
|
||||
plugin.onNotificationOpen(function(ctx) {
|
||||
ctx.openScreen({ screenId: "alert", params: { buildId: String(ctx.event.data && ctx.event.data.buildId || "") } });
|
||||
});
|
||||
return function() {};
|
||||
} }; })`,
|
||||
},
|
||||
];
|
||||
|
||||
// Before server_info arrives: supported is null (unknown) and connected is false.
|
||||
const stopUnknown = h.sync({ connected: false, supported: null });
|
||||
expect(h.registry.getCatalogStatus("host")).toBe("loading");
|
||||
|
||||
const openedRoutes: string[] = [];
|
||||
const pendingTap = openPluginNotification(
|
||||
{
|
||||
kind: "plugin",
|
||||
serverId: "host",
|
||||
pluginId: "ci-alerts",
|
||||
notificationId: "notif-cold",
|
||||
open: { type: "screen", screenId: "fallback" },
|
||||
data: { buildId: 77 },
|
||||
},
|
||||
{
|
||||
registry: h.registry,
|
||||
timeoutMs: 1_000,
|
||||
openAgent: () => undefined,
|
||||
openWorkspace: () => undefined,
|
||||
openRoute: (route) => openedRoutes.push(route),
|
||||
},
|
||||
);
|
||||
|
||||
// Tap stays pending while server_info has not arrived (does not jump to fallback).
|
||||
await Promise.resolve();
|
||||
expect(openedRoutes).toEqual([]);
|
||||
|
||||
// Host connects and advertises plugin support -> catalog loads and invokes onNotificationOpen.
|
||||
stopUnknown();
|
||||
h.sync({ connected: true, supported: true });
|
||||
|
||||
await pendingTap;
|
||||
expect(h.registry.getCatalogStatus("host")).toBe("ready");
|
||||
expect(openedRoutes).toEqual(["/h/host/plugin/ci-alerts/surface/alert?param.buildId=77"]);
|
||||
});
|
||||
|
||||
@@ -8,11 +8,13 @@ interface CatalogSyncInput {
|
||||
client: DaemonClient;
|
||||
audio: Pick<AudioEngine, "play"> | null;
|
||||
connected: boolean;
|
||||
supported: boolean;
|
||||
/** `null` while `server_info` has not yet arrived for this host. */
|
||||
supported: boolean | null;
|
||||
registry: Pick<
|
||||
PluginRegistry,
|
||||
"installCatalog" | "getSnapshot" | "removeHost" | "setCatalogStatus"
|
||||
>;
|
||||
onCatalogChanged?: () => void;
|
||||
}
|
||||
|
||||
export function syncPluginCatalog({
|
||||
@@ -22,7 +24,13 @@ export function syncPluginCatalog({
|
||||
connected,
|
||||
supported,
|
||||
registry,
|
||||
onCatalogChanged,
|
||||
}: CatalogSyncInput): () => void {
|
||||
if (supported === null) {
|
||||
// Plugin support is unknown until `server_info` arrives; keep status "loading" so cold-launch
|
||||
// plugin notification taps wait instead of falling back prematurely.
|
||||
return () => {};
|
||||
}
|
||||
if (!supported || !audio) {
|
||||
registry.removeHost(serverId);
|
||||
registry.setCatalogStatus(serverId, "ready");
|
||||
@@ -88,6 +96,7 @@ export function syncPluginCatalog({
|
||||
}
|
||||
}
|
||||
if (message.payload.status === "plugin_catalog_changed") {
|
||||
onCatalogChanged?.();
|
||||
const pluginId = message.payload.pluginId;
|
||||
if (typeof pluginId === "string") void refresh(pluginId);
|
||||
}
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
import { useVoiceAudioEngineOptional } from "@/contexts/voice-context";
|
||||
import { useEffect } from "react";
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
|
||||
import { useHostFeature } from "@/runtime/host-features";
|
||||
import { useHostFeatureAvailability } from "@/runtime/host-features";
|
||||
import { useHostRuntimeIsConnected } from "@/runtime/host-runtime";
|
||||
import { pluginListQueryKey } from "./plugin-list";
|
||||
import { pluginRegistry } from "./registry";
|
||||
import { syncPluginCatalog } from "./catalog-sync-model";
|
||||
|
||||
@@ -15,7 +17,8 @@ export function PluginCatalogSync({
|
||||
}) {
|
||||
const audio = useVoiceAudioEngineOptional();
|
||||
const connected = useHostRuntimeIsConnected(serverId);
|
||||
const supported = useHostFeature(serverId, "plugins");
|
||||
const supported = useHostFeatureAvailability(serverId, "plugins");
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
useEffect(
|
||||
() =>
|
||||
@@ -26,8 +29,11 @@ export function PluginCatalogSync({
|
||||
connected,
|
||||
supported,
|
||||
registry: pluginRegistry,
|
||||
onCatalogChanged: () => {
|
||||
void queryClient.invalidateQueries({ queryKey: pluginListQueryKey(serverId) });
|
||||
},
|
||||
}),
|
||||
[audio, client, connected, serverId, supported],
|
||||
[audio, client, connected, queryClient, serverId, supported],
|
||||
);
|
||||
|
||||
useEffect(() => () => pluginRegistry.removeHost(serverId), [serverId]);
|
||||
|
||||
@@ -148,6 +148,7 @@ function plugin(onAgentSelect: AgentCommandItem["onSelect"]): InstalledPlugin {
|
||||
themes: [],
|
||||
timelineTransformers: [],
|
||||
timelineRenderers: [],
|
||||
notificationOpenHandlers: [],
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -58,6 +58,7 @@ function installed(): InstalledPlugin {
|
||||
themes: [],
|
||||
timelineTransformers: [],
|
||||
timelineRenderers: [],
|
||||
notificationOpenHandlers: [],
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -68,6 +68,7 @@ function plugin(): InstalledPlugin {
|
||||
themes: [],
|
||||
timelineTransformers: [],
|
||||
timelineRenderers: [],
|
||||
notificationOpenHandlers: [],
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,15 @@
|
||||
import { readFileSync } from "node:fs";
|
||||
import { createRequire } from "node:module";
|
||||
// eslint-disable-next-line no-restricted-imports -- verify plugin runtime does not leak raw ReactNative.
|
||||
import * as ReactNative from "react-native";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { useRevealedText } from "@/hooks/use-revealed-text";
|
||||
import { runPluginClientBundle, type PluginClientRuntime } from "./evaluate";
|
||||
import {
|
||||
OMITTED_REACT_NATIVE_EXPORTS,
|
||||
createPluginReactNativeRuntime,
|
||||
runPluginClientBundle,
|
||||
type PluginClientRuntime,
|
||||
} from "./evaluate";
|
||||
|
||||
const runtime = {
|
||||
paseo: {},
|
||||
@@ -110,6 +119,7 @@ describe("evaluatePluginClientBundle", () => {
|
||||
plugin.addTheme({ id: "night", name: "Night", appearance: "dark", colors: { background: "#000", foreground: "#fff", raised: "#111", control: "#222", border: "#333", mutedForeground: "#aaa", ring: "#555" } }),
|
||||
plugin.addTimelineTransformer({ id: "transformer", query: { itemType: "tool_call" }, transform() { return { items: [] }; } }),
|
||||
plugin.addTimelineRenderer({ kind: "card", version: 1, schema, Component }),
|
||||
plugin.onNotificationOpen(function handleOpen() {}),
|
||||
];
|
||||
`),
|
||||
{
|
||||
@@ -141,6 +151,7 @@ describe("evaluatePluginClientBundle", () => {
|
||||
plugin.themes,
|
||||
plugin.timelineTransformers,
|
||||
plugin.timelineRenderers,
|
||||
plugin.notificationOpenHandlers,
|
||||
].every((items) => items.length === 1),
|
||||
).toBe(true);
|
||||
expect(pillCount).toBe(1);
|
||||
@@ -162,6 +173,7 @@ describe("evaluatePluginClientBundle", () => {
|
||||
plugin.themes,
|
||||
plugin.timelineTransformers,
|
||||
plugin.timelineRenderers,
|
||||
plugin.notificationOpenHandlers,
|
||||
].every((items) => items.length === 0),
|
||||
).toBe(true);
|
||||
expect(pillCount).toBe(0);
|
||||
@@ -906,6 +918,117 @@ describe("evaluatePluginClientBundle", () => {
|
||||
),
|
||||
).toThrow("setup exploded");
|
||||
});
|
||||
|
||||
it("omits PushNotificationIOS, default, and non-enumerable getters while keeping other exports lazy", () => {
|
||||
let platformReads = 0;
|
||||
let pushReads = 0;
|
||||
let nativeModulesReads = 0;
|
||||
let asyncStorageReads = 0;
|
||||
const raw = {
|
||||
get Platform() {
|
||||
platformReads += 1;
|
||||
return { OS: "ios" };
|
||||
},
|
||||
get PushNotificationIOS() {
|
||||
pushReads += 1;
|
||||
throw new Error("`new NativeEventEmitter()` requires a non-null argument.");
|
||||
},
|
||||
get NativeModules() {
|
||||
nativeModulesReads += 1;
|
||||
return { CustomModule: true };
|
||||
},
|
||||
};
|
||||
const interopNamespace = Object.defineProperties(
|
||||
{},
|
||||
{
|
||||
Platform: Object.getOwnPropertyDescriptor(raw, "Platform")!,
|
||||
PushNotificationIOS: Object.getOwnPropertyDescriptor(raw, "PushNotificationIOS")!,
|
||||
NativeModules: Object.getOwnPropertyDescriptor(raw, "NativeModules")!,
|
||||
AsyncStorage: {
|
||||
configurable: true,
|
||||
enumerable: false,
|
||||
get() {
|
||||
asyncStorageReads += 1;
|
||||
throw new Error("AsyncStorage has been removed from react-native core.");
|
||||
},
|
||||
},
|
||||
default: { enumerable: true, value: raw },
|
||||
},
|
||||
);
|
||||
|
||||
const safe = createPluginReactNativeRuntime(interopNamespace);
|
||||
|
||||
expect(platformReads).toBe(0);
|
||||
expect(pushReads).toBe(0);
|
||||
expect(nativeModulesReads).toBe(0);
|
||||
expect(asyncStorageReads).toBe(0);
|
||||
expect(Object.getOwnPropertyNames(safe)).toEqual(["Platform", "NativeModules"]);
|
||||
expect("PushNotificationIOS" in safe).toBe(false);
|
||||
expect("AsyncStorage" in safe).toBe(false);
|
||||
expect("default" in safe).toBe(false);
|
||||
expect(Object.assign({}, safe)).toEqual({
|
||||
Platform: { OS: "ios" },
|
||||
NativeModules: { CustomModule: true },
|
||||
});
|
||||
expect(platformReads).toBe(1);
|
||||
expect(nativeModulesReads).toBe(1);
|
||||
expect(pushReads).toBe(0);
|
||||
expect(asyncStorageReads).toBe(0);
|
||||
});
|
||||
|
||||
it("wires require('react-native') to the filtered runtime instead of the raw namespace", () => {
|
||||
let exposed: Record<string, unknown> | undefined;
|
||||
const plugin = evaluatePluginClientBundle(
|
||||
"rn-safe",
|
||||
`(function(require) {
|
||||
const rn = require("react-native");
|
||||
return {
|
||||
default: function(plugin) {
|
||||
plugin.addSurface("probe", function() { return null; });
|
||||
globalThis.__testPluginRn = rn;
|
||||
return function() {};
|
||||
},
|
||||
};
|
||||
})`,
|
||||
);
|
||||
exposed = (globalThis as Record<string, unknown>).__testPluginRn as
|
||||
| Record<string, unknown>
|
||||
| undefined;
|
||||
delete (globalThis as Record<string, unknown>).__testPluginRn;
|
||||
|
||||
expect(plugin.id).toBe("rn-safe");
|
||||
expect(exposed).toBeDefined();
|
||||
expect(exposed).not.toBe(ReactNative);
|
||||
const expectedKeys = Object.keys(ReactNative)
|
||||
.filter((key) => !OMITTED_REACT_NATIVE_EXPORTS.has(key))
|
||||
.sort();
|
||||
expect(Object.getOwnPropertyNames(exposed!).sort()).toEqual(expectedKeys);
|
||||
expect("PushNotificationIOS" in exposed!).toBe(false);
|
||||
expect("default" in exposed!).toBe(false);
|
||||
expect(exposed!.Platform).toBe(ReactNative.Platform);
|
||||
expect(exposed!.NativeModules).toBe(ReactNative.NativeModules);
|
||||
});
|
||||
|
||||
it("excludes PushNotificationIOS and checks enumerable react-native/index.js getters for invariant throws", () => {
|
||||
const require = createRequire(import.meta.url);
|
||||
const rnIndexPath = require.resolve("react-native/index.js");
|
||||
const rnIndexSource = readFileSync(rnIndexPath, "utf8");
|
||||
const getterBodies = new Map<string, string>();
|
||||
const getterPattern = /get\s+([A-Za-z0-9_$]+)\s*\(\)\s*\{([\s\S]*?)\n\s*\},/g;
|
||||
for (const match of rnIndexSource.matchAll(getterPattern)) {
|
||||
getterBodies.set(match[1]!, match[2]!);
|
||||
}
|
||||
expect(getterBodies.size).toBeGreaterThan(0);
|
||||
expect(getterBodies.has("PushNotificationIOS")).toBe(true);
|
||||
expect(OMITTED_REACT_NATIVE_EXPORTS.has("PushNotificationIOS")).toBe(true);
|
||||
|
||||
for (const [name, body] of getterBodies) {
|
||||
if (OMITTED_REACT_NATIVE_EXPORTS.has(name)) continue;
|
||||
expect(body, `throwing enumerable getter ${name} in react-native/index.js`).not.toContain(
|
||||
"invariant(",
|
||||
);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it("binds imported getters to each originating installation across delayed callbacks", async () => {
|
||||
|
||||
@@ -24,6 +24,7 @@ import {
|
||||
type PluginSurfaceProps,
|
||||
type PluginTimelineRendererContribution,
|
||||
type PluginTimelineTransformerContribution,
|
||||
type PluginNotificationOpenHandler,
|
||||
type PluginButtonRegistration,
|
||||
} from "@getpaseo/plugin/client";
|
||||
import type {
|
||||
@@ -122,6 +123,29 @@ export type PluginClientRuntime = Pick<
|
||||
// The 0.12 entry exposed the reveal hook as well as UI components.
|
||||
const pluginReactNativeCompatRuntime = { ...pluginUiRuntime, useRevealedText };
|
||||
|
||||
// PushNotificationIOS crashes iOS fatally via Metro's guardedLoadModule ->
|
||||
// RCTExceptionsManager.reportFatal because RCTPushNotificationManager is not linked
|
||||
// in Expo builds, bypassing PluginRegistry's try/catch. Omit it and raw `default`
|
||||
// while preserving all other enumerable react-native exports as lazy descriptors.
|
||||
export const OMITTED_REACT_NATIVE_EXPORTS = new Set(["PushNotificationIOS", "default"]);
|
||||
|
||||
export function createPluginReactNativeRuntime(
|
||||
source: Record<string, unknown>,
|
||||
): Record<string, unknown> {
|
||||
const runtime: Record<string, unknown> = {};
|
||||
for (const key of Object.keys(source)) {
|
||||
if (OMITTED_REACT_NATIVE_EXPORTS.has(key)) continue;
|
||||
const descriptor = Object.getOwnPropertyDescriptor(source, key);
|
||||
if (!descriptor) continue;
|
||||
Object.defineProperty(runtime, key, descriptor);
|
||||
}
|
||||
return runtime;
|
||||
}
|
||||
|
||||
const pluginReactNativeRuntime = createPluginReactNativeRuntime(
|
||||
ReactNative as unknown as Record<string, unknown>,
|
||||
);
|
||||
|
||||
export function runPluginClientBundle(
|
||||
id: string,
|
||||
bundle: string,
|
||||
@@ -145,6 +169,7 @@ export function runPluginClientBundle(
|
||||
themes: [],
|
||||
timelineTransformers: [],
|
||||
timelineRenderers: [],
|
||||
notificationOpenHandlers: [],
|
||||
};
|
||||
const surfaceIds = new Set<string>();
|
||||
const sidebarViewIds = new Set<string>();
|
||||
@@ -565,6 +590,12 @@ export function runPluginClientBundle(
|
||||
timelineRendererIds.delete(rendererId),
|
||||
);
|
||||
},
|
||||
onNotificationOpen(handler: PluginNotificationOpenHandler) {
|
||||
if (typeof handler !== "function") {
|
||||
throw new Error("onNotificationOpen takes a callback function");
|
||||
}
|
||||
return register(collector.notificationOpenHandlers, handler, () => {});
|
||||
},
|
||||
addComposerPill(contribution) {
|
||||
if (stopped) throw new Error("Plugin has stopped");
|
||||
return trackButton(runtime.addComposerPill(contribution));
|
||||
@@ -580,7 +611,7 @@ export function runPluginClientBundle(
|
||||
if (name === "@getpaseo/plugin/client/ui") return pluginUiRuntime;
|
||||
if (name === "react") return React;
|
||||
if (name === "react/jsx-runtime") return ReactJsxRuntime;
|
||||
if (name === "react-native") return ReactNative;
|
||||
if (name === "react-native") return pluginReactNativeRuntime;
|
||||
if (name === "@getpaseo/plugin") return pluginSharedRuntime;
|
||||
if (name === "@getpaseo/plugin/client")
|
||||
return {
|
||||
@@ -665,5 +696,6 @@ export function runPluginClientBundle(
|
||||
themes: collector.themes,
|
||||
timelineTransformers: collector.timelineTransformers,
|
||||
timelineRenderers: collector.timelineRenderers,
|
||||
notificationOpenHandlers: collector.notificationOpenHandlers,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -61,6 +61,7 @@ function installation(invoked: string[]): InstalledPlugin {
|
||||
themes: [],
|
||||
timelineTransformers: [],
|
||||
timelineRenderers: [],
|
||||
notificationOpenHandlers: [],
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,344 @@
|
||||
import { QueryClient } from "@tanstack/react-query";
|
||||
import { PluginTranslationRuntime } from "@getpaseo/plugin/client/host";
|
||||
import { createPaseoApi } from "@getpaseo/client";
|
||||
import { DaemonClient } from "@getpaseo/client/internal/daemon-client";
|
||||
import type { PluginNotificationOpenHandler } from "@getpaseo/plugin/client";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
openPluginNotification,
|
||||
type PluginNotificationOpenRegistry,
|
||||
type PluginNotificationTarget,
|
||||
} from "./notification-open";
|
||||
import type { PluginCatalogStatus } from "./registry";
|
||||
import type { InstalledPlugin } from "./types";
|
||||
|
||||
class FakePluginRegistry implements PluginNotificationOpenRegistry {
|
||||
private plugins: InstalledPlugin[] = [];
|
||||
private statuses = new Map<string, PluginCatalogStatus>();
|
||||
private listeners = new Set<() => void>();
|
||||
|
||||
getSnapshot(): readonly InstalledPlugin[] {
|
||||
return this.plugins;
|
||||
}
|
||||
|
||||
getCatalogStatus(serverId: string): PluginCatalogStatus {
|
||||
return this.statuses.get(serverId) ?? "loading";
|
||||
}
|
||||
|
||||
setCatalogStatus(serverId: string, status: PluginCatalogStatus): void {
|
||||
this.statuses.set(serverId, status);
|
||||
this.notify();
|
||||
}
|
||||
|
||||
install(plugin: InstalledPlugin): void {
|
||||
this.plugins = [
|
||||
...this.plugins.filter((p) => !(p.serverId === plugin.serverId && p.id === plugin.id)),
|
||||
plugin,
|
||||
];
|
||||
this.notify();
|
||||
}
|
||||
|
||||
subscribe(listener: () => void): () => void {
|
||||
this.listeners.add(listener);
|
||||
return () => this.listeners.delete(listener);
|
||||
}
|
||||
|
||||
private notify(): void {
|
||||
for (const listener of this.listeners) listener();
|
||||
}
|
||||
}
|
||||
|
||||
function makeInstalledPlugin(input: {
|
||||
serverId: string;
|
||||
pluginId: string;
|
||||
screens?: string[];
|
||||
handlers?: PluginNotificationOpenHandler[];
|
||||
}): InstalledPlugin {
|
||||
return {
|
||||
id: input.pluginId,
|
||||
serverId: input.serverId,
|
||||
lifetime: new AbortController(),
|
||||
locale: "en",
|
||||
i18n: new PluginTranslationRuntime({
|
||||
getLocale: () => "en",
|
||||
subscribe: () => () => {},
|
||||
}),
|
||||
paseo: createPaseoApi(
|
||||
new DaemonClient({
|
||||
url: "ws://127.0.0.1:1",
|
||||
clientId: `plugin-notification-test-${input.pluginId}`,
|
||||
clientType: "cli",
|
||||
}),
|
||||
),
|
||||
invoke: async () => undefined,
|
||||
subscribe: () => {
|
||||
throw new Error("not used");
|
||||
},
|
||||
clientBundle: "",
|
||||
queryClient: new QueryClient(),
|
||||
cleanup: () => {},
|
||||
surfaces: (input.screens ?? ["main"]).map((id) => ({
|
||||
id,
|
||||
title: id,
|
||||
Component: () => null,
|
||||
})),
|
||||
settingsScreens: [],
|
||||
sidebarViews: [],
|
||||
sidebarItems: { header: [], footer: [] },
|
||||
legacySidebarItems: [],
|
||||
workspaceRowBadgeItems: [],
|
||||
filePanels: [],
|
||||
composerItems: [],
|
||||
newWorkspaceItems: [],
|
||||
workspacePanels: [],
|
||||
commandCenterItems: [],
|
||||
clientSlashCommands: [],
|
||||
attachmentSources: [],
|
||||
themes: [],
|
||||
timelineTransformers: [],
|
||||
timelineRenderers: [],
|
||||
notificationOpenHandlers: input.handlers ?? [],
|
||||
};
|
||||
}
|
||||
|
||||
function createHarness(registry = new FakePluginRegistry()) {
|
||||
const agents: Array<{ serverId: string; agentId: string }> = [];
|
||||
const workspaces: Array<{ serverId: string; workspaceId: string }> = [];
|
||||
const routes: string[] = [];
|
||||
const focusedHosts: string[] = [];
|
||||
const errors: Array<{ error: unknown; serverId: string; pluginId: string }> = [];
|
||||
|
||||
return {
|
||||
registry,
|
||||
agents,
|
||||
workspaces,
|
||||
routes,
|
||||
focusedHosts,
|
||||
errors,
|
||||
dispatch: (target: PluginNotificationTarget, timeoutMs = 100) =>
|
||||
openPluginNotification(target, {
|
||||
registry,
|
||||
timeoutMs,
|
||||
openAgent: (item) => {
|
||||
agents.push(item);
|
||||
return `/h/${item.serverId}/agent/${item.agentId}`;
|
||||
},
|
||||
openWorkspace: (item) => {
|
||||
workspaces.push(item);
|
||||
return `/h/${item.serverId}/workspace/${item.workspaceId}`;
|
||||
},
|
||||
openRoute: (route) => {
|
||||
routes.push(route);
|
||||
},
|
||||
focusHost: (serverId) => {
|
||||
focusedHosts.push(serverId);
|
||||
},
|
||||
onError: (error, context) => {
|
||||
errors.push({ error, ...context });
|
||||
},
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
describe("openPluginNotification", () => {
|
||||
it("invokes onNotificationOpen immediately on warm tap when plugin is already installed", async () => {
|
||||
const harness = createHarness();
|
||||
const receivedEvents: unknown[] = [];
|
||||
|
||||
harness.registry.setCatalogStatus("srv-1", "ready");
|
||||
harness.registry.install(
|
||||
makeInstalledPlugin({
|
||||
serverId: "srv-1",
|
||||
pluginId: "ci-alerts",
|
||||
screens: ["report"],
|
||||
handlers: [
|
||||
({ event, openScreen, navigation }) => {
|
||||
receivedEvents.push(event);
|
||||
if (typeof event.data?.agentId === "string") {
|
||||
navigation.openAgent({ agentId: event.data.agentId, focusHost: true });
|
||||
} else {
|
||||
openScreen({
|
||||
screenId: "report",
|
||||
params: { buildId: String(event.data?.buildId ?? "") },
|
||||
});
|
||||
}
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
|
||||
await harness.dispatch({
|
||||
kind: "plugin",
|
||||
serverId: "srv-1",
|
||||
pluginId: "ci-alerts",
|
||||
notificationId: "notif-42",
|
||||
open: { type: "workspace", workspaceId: "ws-ignored-because-handler-ran" },
|
||||
data: { buildId: 42 },
|
||||
});
|
||||
|
||||
expect(receivedEvents).toEqual([
|
||||
{
|
||||
type: "opened",
|
||||
notificationId: "notif-42",
|
||||
data: { buildId: 42 },
|
||||
},
|
||||
]);
|
||||
expect(harness.routes).toEqual(["/h/srv-1/plugin/ci-alerts/surface/report?param.buildId=42"]);
|
||||
expect(harness.workspaces).toEqual([]);
|
||||
});
|
||||
|
||||
it("waits for plugin catalog readiness on cold launch before invoking onNotificationOpen", async () => {
|
||||
const harness = createHarness();
|
||||
// Catalog is still "loading" on cold launch
|
||||
expect(harness.registry.getCatalogStatus("srv-1")).toBe("loading");
|
||||
|
||||
const pending = harness.dispatch(
|
||||
{
|
||||
kind: "plugin",
|
||||
serverId: "srv-1",
|
||||
pluginId: "ci-alerts",
|
||||
notificationId: "notif-cold",
|
||||
data: { agentId: "agent-99" },
|
||||
},
|
||||
1_000,
|
||||
);
|
||||
|
||||
// Nothing dispatched while catalog is still loading
|
||||
await Promise.resolve();
|
||||
expect(harness.agents).toEqual([]);
|
||||
|
||||
// Catalog finishes loading and installs the plugin
|
||||
harness.registry.install(
|
||||
makeInstalledPlugin({
|
||||
serverId: "srv-1",
|
||||
pluginId: "ci-alerts",
|
||||
handlers: [
|
||||
({ event, navigation }) => {
|
||||
if (typeof event.data?.agentId === "string") {
|
||||
navigation.openAgent({ agentId: event.data.agentId, focusHost: true });
|
||||
}
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
harness.registry.setCatalogStatus("srv-1", "ready");
|
||||
|
||||
await pending;
|
||||
expect(harness.agents).toEqual([{ serverId: "srv-1", agentId: "agent-99" }]);
|
||||
expect(harness.focusedHosts).toEqual(["srv-1"]);
|
||||
});
|
||||
|
||||
it("falls back to declarative open targets (agent, workspace, screen, host root) when no handler is registered or catalog times out", async () => {
|
||||
const harness = createHarness();
|
||||
harness.registry.setCatalogStatus("srv-1", "ready");
|
||||
harness.registry.install(
|
||||
makeInstalledPlugin({
|
||||
serverId: "srv-1",
|
||||
pluginId: "declarative-plugin",
|
||||
screens: ["details"],
|
||||
handlers: [],
|
||||
}),
|
||||
);
|
||||
|
||||
await harness.dispatch({
|
||||
kind: "plugin",
|
||||
serverId: "srv-1",
|
||||
pluginId: "declarative-plugin",
|
||||
notificationId: "n-agent",
|
||||
open: { type: "agent", agentId: "agent-1" },
|
||||
});
|
||||
expect(harness.agents).toEqual([{ serverId: "srv-1", agentId: "agent-1" }]);
|
||||
|
||||
await harness.dispatch({
|
||||
kind: "plugin",
|
||||
serverId: "srv-1",
|
||||
pluginId: "declarative-plugin",
|
||||
notificationId: "n-workspace",
|
||||
open: { type: "workspace", workspaceId: "ws-1" },
|
||||
});
|
||||
expect(harness.workspaces).toEqual([{ serverId: "srv-1", workspaceId: "ws-1" }]);
|
||||
|
||||
await harness.dispatch({
|
||||
kind: "plugin",
|
||||
serverId: "srv-1",
|
||||
pluginId: "declarative-plugin",
|
||||
notificationId: "n-screen",
|
||||
open: { type: "screen", screenId: "details", params: { tab: "logs" } },
|
||||
});
|
||||
expect(harness.routes).toEqual([
|
||||
"/h/srv-1/plugin/declarative-plugin/surface/details?param.tab=logs",
|
||||
]);
|
||||
|
||||
// Timeout waiting for an offline host catalog falls back to declarative open or host root
|
||||
await harness.dispatch(
|
||||
{
|
||||
kind: "plugin",
|
||||
serverId: "srv-loading",
|
||||
pluginId: "missing-plugin",
|
||||
notificationId: "n-host",
|
||||
},
|
||||
10,
|
||||
);
|
||||
expect(harness.routes).toEqual([
|
||||
"/h/srv-1/plugin/declarative-plugin/surface/details?param.tab=logs",
|
||||
"/h/srv-loading",
|
||||
]);
|
||||
});
|
||||
|
||||
it("catches and reports errors thrown by onNotificationOpen handlers without crashing", async () => {
|
||||
const harness = createHarness();
|
||||
harness.registry.setCatalogStatus("srv-1", "ready");
|
||||
harness.registry.install(
|
||||
makeInstalledPlugin({
|
||||
serverId: "srv-1",
|
||||
pluginId: "buggy-plugin",
|
||||
screens: ["main"],
|
||||
handlers: [
|
||||
() => {
|
||||
throw new Error("boom in first handler");
|
||||
},
|
||||
({ openScreen }) => {
|
||||
openScreen({ screenId: "main" });
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
|
||||
await harness.dispatch({
|
||||
kind: "plugin",
|
||||
serverId: "srv-1",
|
||||
pluginId: "buggy-plugin",
|
||||
notificationId: "n-err",
|
||||
});
|
||||
|
||||
expect(harness.errors).toHaveLength(1);
|
||||
expect(harness.routes).toEqual(["/h/srv-1/plugin/buggy-plugin/surface/main"]);
|
||||
});
|
||||
|
||||
it("falls back to declarative open when every registered onNotificationOpen handler throws", async () => {
|
||||
const harness = createHarness();
|
||||
harness.registry.setCatalogStatus("srv-1", "ready");
|
||||
harness.registry.install(
|
||||
makeInstalledPlugin({
|
||||
serverId: "srv-1",
|
||||
pluginId: "failing-plugin",
|
||||
handlers: [
|
||||
() => {
|
||||
throw new Error("handler boom");
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
|
||||
await harness.dispatch({
|
||||
kind: "plugin",
|
||||
serverId: "srv-1",
|
||||
pluginId: "failing-plugin",
|
||||
notificationId: "n-throw-fallback",
|
||||
open: { type: "agent", agentId: "agent-fallback" },
|
||||
});
|
||||
|
||||
expect(harness.errors).toHaveLength(1);
|
||||
expect(harness.agents).toEqual([{ serverId: "srv-1", agentId: "agent-fallback" }]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,223 @@
|
||||
import type {
|
||||
PluginCommandCapabilities,
|
||||
PluginNotificationOpenContext,
|
||||
PluginNotificationOpenEvent,
|
||||
} from "@getpaseo/plugin/client";
|
||||
import type { NotificationOpenTarget } from "@/notification-open/model";
|
||||
import { buildHostRootRoute, parseServerIdFromPathname } from "@/utils/host-routes";
|
||||
import { createPluginCapabilities } from "./actions";
|
||||
import { cloneAndFreeze } from "./freeze";
|
||||
import type { PluginCatalogStatus } from "./registry";
|
||||
import { buildPluginSurfaceRoute, parsePluginScreenParams } from "./routes";
|
||||
import type { InstalledPlugin } from "./types";
|
||||
|
||||
export const PLUGIN_NOTIFICATION_CATALOG_TIMEOUT_MS = 8_000;
|
||||
|
||||
export type PluginNotificationTarget = Extract<NotificationOpenTarget, { kind: "plugin" }>;
|
||||
|
||||
export interface PluginNotificationOpenRegistry {
|
||||
getSnapshot(): readonly InstalledPlugin[];
|
||||
getCatalogStatus(serverId: string): PluginCatalogStatus;
|
||||
subscribe(listener: () => void): () => void;
|
||||
}
|
||||
|
||||
export interface PluginNotificationOpenDependencies {
|
||||
registry: PluginNotificationOpenRegistry;
|
||||
timeoutMs?: number;
|
||||
createCapabilities?: (plugin: InstalledPlugin) => PluginCommandCapabilities;
|
||||
isHostRegistered?: (serverId: string) => boolean;
|
||||
focusHost?: (serverId: string) => void;
|
||||
openAgent: (input: { serverId: string; agentId: string }) => string | void;
|
||||
openWorkspace: (input: { serverId: string; workspaceId: string }) => string | void;
|
||||
openRoute: (route: string) => void;
|
||||
onError?: (error: unknown, context: { serverId: string; pluginId: string }) => void;
|
||||
}
|
||||
|
||||
function findInstalledPlugin(
|
||||
registry: PluginNotificationOpenRegistry,
|
||||
serverId: string,
|
||||
pluginId: string,
|
||||
): InstalledPlugin | null {
|
||||
return (
|
||||
registry
|
||||
.getSnapshot()
|
||||
.find((plugin) => plugin.serverId === serverId && plugin.id === pluginId) ?? null
|
||||
);
|
||||
}
|
||||
|
||||
async function waitForPluginInstallation(
|
||||
registry: PluginNotificationOpenRegistry,
|
||||
serverId: string,
|
||||
pluginId: string,
|
||||
timeoutMs: number,
|
||||
): Promise<InstalledPlugin | null> {
|
||||
const existing = findInstalledPlugin(registry, serverId, pluginId);
|
||||
if (existing) {
|
||||
return existing;
|
||||
}
|
||||
if (registry.getCatalogStatus(serverId) !== "loading" || timeoutMs <= 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
let resolvePromise!: (plugin: InstalledPlugin | null) => void;
|
||||
const promise = new Promise<InstalledPlugin | null>((resolve) => {
|
||||
resolvePromise = resolve;
|
||||
});
|
||||
let settled = false;
|
||||
let unsubscribe = () => {};
|
||||
const finish = (plugin: InstalledPlugin | null) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
clearTimeout(timer);
|
||||
unsubscribe();
|
||||
resolvePromise(plugin);
|
||||
};
|
||||
const check = () => {
|
||||
const found = findInstalledPlugin(registry, serverId, pluginId);
|
||||
if (found) {
|
||||
finish(found);
|
||||
return;
|
||||
}
|
||||
if (registry.getCatalogStatus(serverId) !== "loading") {
|
||||
finish(null);
|
||||
}
|
||||
};
|
||||
const timer = setTimeout(() => {
|
||||
finish(findInstalledPlugin(registry, serverId, pluginId));
|
||||
}, timeoutMs);
|
||||
unsubscribe = registry.subscribe(check);
|
||||
check();
|
||||
return promise;
|
||||
}
|
||||
|
||||
function applyDeclarativeFallback(
|
||||
target: PluginNotificationTarget,
|
||||
deps: Pick<PluginNotificationOpenDependencies, "openAgent" | "openWorkspace" | "openRoute">,
|
||||
): void {
|
||||
const open = target.open;
|
||||
if (open?.type === "agent") {
|
||||
deps.openAgent({ serverId: target.serverId, agentId: open.agentId });
|
||||
return;
|
||||
}
|
||||
if (open?.type === "workspace") {
|
||||
deps.openWorkspace({ serverId: target.serverId, workspaceId: open.workspaceId });
|
||||
return;
|
||||
}
|
||||
if (open?.type === "screen") {
|
||||
try {
|
||||
const params = parsePluginScreenParams(open.params);
|
||||
deps.openRoute(
|
||||
buildPluginSurfaceRoute(
|
||||
target.serverId,
|
||||
target.pluginId,
|
||||
{ kind: "surface", id: open.screenId },
|
||||
params,
|
||||
),
|
||||
);
|
||||
return;
|
||||
} catch {
|
||||
// Fall back to host root route if params are malformed.
|
||||
}
|
||||
}
|
||||
deps.openRoute(buildHostRootRoute(target.serverId));
|
||||
}
|
||||
|
||||
export async function openPluginNotification(
|
||||
target: PluginNotificationTarget,
|
||||
deps: PluginNotificationOpenDependencies,
|
||||
): Promise<void> {
|
||||
const registry = deps.registry;
|
||||
const timeoutMs = deps.timeoutMs ?? PLUGIN_NOTIFICATION_CATALOG_TIMEOUT_MS;
|
||||
const plugin = await waitForPluginInstallation(
|
||||
registry,
|
||||
target.serverId,
|
||||
target.pluginId,
|
||||
timeoutMs,
|
||||
);
|
||||
|
||||
if (plugin && plugin.notificationOpenHandlers.length > 0) {
|
||||
const capabilities =
|
||||
deps.createCapabilities?.(plugin) ??
|
||||
createPluginCapabilities(plugin, {
|
||||
openSettings(pluginId, screenId) {
|
||||
deps.openRoute(
|
||||
`/settings/hosts/${encodeURIComponent(plugin.serverId)}/plugins/${encodeURIComponent(pluginId)}/${encodeURIComponent(screenId)}`,
|
||||
);
|
||||
},
|
||||
openSurface(pluginId, surfaceId, params) {
|
||||
deps.openRoute(
|
||||
buildPluginSurfaceRoute(
|
||||
plugin.serverId,
|
||||
pluginId,
|
||||
{ kind: "surface", id: surfaceId },
|
||||
params,
|
||||
),
|
||||
);
|
||||
},
|
||||
openWorkspacePanel() {
|
||||
throw new Error("No active workspace");
|
||||
},
|
||||
openAgentPanel() {
|
||||
throw new Error("No active workspace");
|
||||
},
|
||||
});
|
||||
|
||||
const focusRouteHost = (route: string | void, fallbackServerId: string) => {
|
||||
if (!deps.focusHost) return;
|
||||
const destinationServerId =
|
||||
(typeof route === "string" ? parseServerIdFromPathname(route) : null) ?? fallbackServerId;
|
||||
if (!deps.isHostRegistered || deps.isHostRegistered(destinationServerId)) {
|
||||
deps.focusHost(destinationServerId);
|
||||
}
|
||||
};
|
||||
|
||||
const event: PluginNotificationOpenEvent = Object.freeze({
|
||||
type: "opened" as const,
|
||||
notificationId: target.notificationId,
|
||||
data: target.data ? cloneAndFreeze(target.data) : undefined,
|
||||
});
|
||||
|
||||
const context: PluginNotificationOpenContext = {
|
||||
...capabilities,
|
||||
event,
|
||||
navigation: {
|
||||
openAgent: ({ agentId, serverId: targetServerId, focusHost }) => {
|
||||
const resolvedServerId = targetServerId ?? target.serverId;
|
||||
const route = deps.openAgent({ serverId: resolvedServerId, agentId });
|
||||
if (focusHost) {
|
||||
focusRouteHost(route, resolvedServerId);
|
||||
}
|
||||
},
|
||||
openWorkspace: ({ workspaceId, serverId: targetServerId, focusHost }) => {
|
||||
const resolvedServerId = targetServerId ?? target.serverId;
|
||||
const route = deps.openWorkspace({ serverId: resolvedServerId, workspaceId });
|
||||
if (focusHost) {
|
||||
focusRouteHost(route, resolvedServerId);
|
||||
}
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
let anySucceeded = false;
|
||||
for (const handler of plugin.notificationOpenHandlers) {
|
||||
try {
|
||||
await handler(context);
|
||||
anySucceeded = true;
|
||||
} catch (error) {
|
||||
if (deps.onError) {
|
||||
deps.onError(error, { serverId: target.serverId, pluginId: target.pluginId });
|
||||
} else {
|
||||
console.warn(
|
||||
`[Plugins] onNotificationOpen handler failed for ${target.serverId}/${target.pluginId}`,
|
||||
error,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (anySucceeded) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
applyDeclarativeFallback(target, deps);
|
||||
}
|
||||
@@ -1,7 +1,13 @@
|
||||
import { useMemo } from "react";
|
||||
import type { PluginListItem } from "@getpaseo/protocol/messages";
|
||||
import { useFetchQuery } from "@/data/query";
|
||||
import { useHostFeature } from "@/runtime/host-features";
|
||||
import { useHostRuntimeClient, useHostRuntimeIsConnected } from "@/runtime/host-runtime";
|
||||
import { useFetchQueries, useFetchQuery } from "@/data/query";
|
||||
import { useHostFeature, useHostFeatureMap } from "@/runtime/host-features";
|
||||
import {
|
||||
getHostRuntimeStore,
|
||||
useHostRuntimeClient,
|
||||
useHostRuntimeIsConnected,
|
||||
useHosts,
|
||||
} from "@/runtime/host-runtime";
|
||||
|
||||
export function pluginListQueryKey(serverId: string) {
|
||||
return ["plugins", serverId] as const;
|
||||
@@ -38,3 +44,38 @@ export function usePluginDisplayName(
|
||||
const plugin = plugins.data?.find((candidate) => candidate.id === target.pluginId);
|
||||
return plugin ? pluginDisplayName(plugin) : target.pluginId;
|
||||
}
|
||||
|
||||
/** Configured plugins across all connected hosts advertising `pluginManagement`, including server-only plugins. */
|
||||
export function useConfiguredPluginsAcrossHosts(): readonly Pick<PluginListItem, "id" | "name">[] {
|
||||
const hosts = useHosts();
|
||||
const serverIds = useMemo(() => hosts.map((host) => host.serverId), [hosts]);
|
||||
const featureMap = useHostFeatureMap(serverIds, "pluginManagement");
|
||||
const queries = useFetchQueries(
|
||||
hosts.map((host) => {
|
||||
const serverId = host.serverId;
|
||||
const client = getHostRuntimeStore().getClient(serverId);
|
||||
const supported = featureMap.get(serverId) === true;
|
||||
return {
|
||||
queryKey: pluginListQueryKey(serverId),
|
||||
queryFn: async () => {
|
||||
const currentClient = getHostRuntimeStore().getClient(serverId);
|
||||
if (!currentClient) throw new Error("Plugin host is offline");
|
||||
return currentClient.listPlugins();
|
||||
},
|
||||
enabled: Boolean(client?.isConnected && supported),
|
||||
dataShape: "list" as const,
|
||||
staleTimeMs: 1_000,
|
||||
};
|
||||
}),
|
||||
);
|
||||
return useMemo(
|
||||
() =>
|
||||
queries.flatMap((query) =>
|
||||
(query.data ?? []).map((plugin) => ({
|
||||
id: plugin.id,
|
||||
name: pluginDisplayName(plugin),
|
||||
})),
|
||||
),
|
||||
[queries],
|
||||
);
|
||||
}
|
||||
|
||||
@@ -136,6 +136,7 @@ export class PluginRegistry {
|
||||
themes: [],
|
||||
timelineTransformers: [],
|
||||
timelineRenderers: [],
|
||||
notificationOpenHandlers: [],
|
||||
};
|
||||
const unsubscribeTranslations = installation.i18n.subscribe(() => this.publish());
|
||||
installation.lifetime.signal.addEventListener("abort", unsubscribeTranslations, {
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user