Compare commits

..
233 changed files with 2235 additions and 10748 deletions
+1 -2
View File
@@ -96,7 +96,6 @@ jobs:
publish-macos:
needs: [create-release]
if: ${{ always() && (needs.create-release.result == 'success' || needs.create-release.result == 'skipped') && ((github.event_name == 'workflow_dispatch' && (github.event.inputs.platform == 'all' || github.event.inputs.platform == 'macos')) || (github.event_name == 'push' && (startsWith(github.ref_name, 'v') || startsWith(github.ref_name, 'desktop-v') || startsWith(github.ref_name, 'desktop-macos-v')))) }}
timeout-minutes: 45
strategy:
fail-fast: false
matrix:
@@ -182,7 +181,7 @@ jobs:
npm run build:desktop "${build_args[@]}"
- name: Upload packaged smoke diagnostics
if: always()
if: failure()
uses: actions/upload-artifact@v4
with:
name: desktop-smoke-macos-${{ matrix.electron_arch }}
-90
View File
@@ -1,95 +1,5 @@
# Changelog
## 0.17.6 - 2026-11-27
### Improved
- Reorganized Settings into Device and Host sections and consolidated sparse pages ([#10933](https://github.com/getpaseo/paseo/pull/10933))
- Added arrow-key navigation for models, providers, and profiles in the model picker ([#10929](https://github.com/getpaseo/paseo/pull/10929), [#10962](https://github.com/getpaseo/paseo/pull/10962))
- Added an in-place Refresh control for Tailscale availability in host settings and setup ([#10903](https://github.com/getpaseo/paseo/pull/10903))
### Changed
- Removed the Antigravity usage source that ran `agy -p /usage` in the background ([#10953](https://github.com/getpaseo/paseo/pull/10953) by [@luoph](https://github.com/luoph))
### Fixed
- Fixed Paseo Android crashing on Samsung devices when a chat shows a code block or quote ([#10964](https://github.com/getpaseo/paseo/pull/10964))
- Fixed mouse clicks not selecting model picker rows on Android ([#10972](https://github.com/getpaseo/paseo/pull/10972))
- Fixed macOS Desktop freezing during startup because of Dock progress bar updates ([#10939](https://github.com/getpaseo/paseo/pull/10939))
- Fixed Linux AppImage leaking its runtime environment into shells and child processes ([#10920](https://github.com/getpaseo/paseo/pull/10920))
- Fixed background Git fetches on Linux spawning orphan D-Bus daemons and retrying failing auth in a loop ([#10921](https://github.com/getpaseo/paseo/pull/10921))
- Fixed flashes when restoring archived workspaces and agents, and added an unarchiving state ([#10928](https://github.com/getpaseo/paseo/pull/10928))
- Fixed worktree ownership drifting outside the configured worktrees root ([#10878](https://github.com/getpaseo/paseo/pull/10878))
- Fixed new web tabs losing projects after another tab evicts the directory cache ([#10942](https://github.com/getpaseo/paseo/pull/10942))
- Fixed timelines dropping rows when a rewind epoch changes ([#8794](https://github.com/getpaseo/paseo/pull/8794) by [@LiebeLee](https://github.com/LiebeLee))
## 0.17.5 - 2026-11-26
- **Archive workspaces together:** Cmd/Ctrl+click a workspace in the sidebar to select multiple workspaces and archive them in one step. ([#10798](https://github.com/getpaseo/paseo/pull/10798), [#10821](https://github.com/getpaseo/paseo/pull/10821))
- **Copy quoted drafts:** Copy a quote from a reply with one tap, without the `>` markers. ([#10608](https://github.com/getpaseo/paseo/pull/10608) by [@pedrovieira](https://github.com/pedrovieira), [@dinhphieu](https://github.com/dinhphieu))
- **Redesigned agent profiles page:** Agent profiles have their own dedicated settings page, and the model picker saves a new profile in one tap. ([#10789](https://github.com/getpaseo/paseo/pull/10789), [#10824](https://github.com/getpaseo/paseo/pull/10824))
- **Redesigned Add project:** Add project opens on folder search, with Clone and New folder one tab away. ([#10767](https://github.com/getpaseo/paseo/pull/10767))
- **Choose how Desktop updates:** Desktop can download updates automatically, only notify you, or never check. ([#10785](https://github.com/getpaseo/paseo/pull/10785))
- **First-class Tailscale support:** Turn on Tailscale for a host from its settings or from setup, without editing its configuration. ([#10801](https://github.com/getpaseo/paseo/pull/10801))
### Added
- Added host icons, connection types, and latency to the host picker ([#10702](https://github.com/getpaseo/paseo/pull/10702) by [@artile](https://github.com/artile))
- Added agent profiles to model picker search and the Command Center ([#10774](https://github.com/getpaseo/paseo/pull/10774))
- Added Archive on finish to `paseo schedule create`, `paseo schedule update`, and the schedule MCP tools ([#8479](https://github.com/getpaseo/paseo/pull/8479) by [@ArnoldHueteG](https://github.com/ArnoldHueteG))
- Added newer Factory Droid models by updating its catalog entry to Droid 1.20.0 ([#10779](https://github.com/getpaseo/paseo/pull/10779) by [@dsingal0](https://github.com/dsingal0))
### Changed
- Changed automatic stable Desktop updates to check at most every 6 hours and to wait 24 hours after each update ([#10882](https://github.com/getpaseo/paseo/pull/10882), [#10901](https://github.com/getpaseo/paseo/pull/10901))
### Fixed
- Fixed agents hiding the subagents they create from tabs and the subagent track ([#10887](https://github.com/getpaseo/paseo/pull/10887))
- Fixed parent agents getting a Claude subagent's interim reply instead of its final reply when the subagent waits on background work ([#10864](https://github.com/getpaseo/paseo/pull/10864))
- Fixed agents that watch a pull request staying in Running after their turn ends ([#10740](https://github.com/getpaseo/paseo/pull/10740) by [@drgould](https://github.com/drgould))
- Fixed the Changes pane offering no Push or Pull when the remote is not named `origin` ([#10679](https://github.com/getpaseo/paseo/pull/10679))
- Fixed a pane switching to the wrong tab after you split or move its active tab out ([#10716](https://github.com/getpaseo/paseo/pull/10716))
- Fixed New workspace leaving focus on the project button after you choose a project ([#10632](https://github.com/getpaseo/paseo/pull/10632))
- Fixed archived chats staying in memory until the window reloads ([#10866](https://github.com/getpaseo/paseo/pull/10866))
- Fixed hover cards and other overlays slowing down in long app sessions ([#10778](https://github.com/getpaseo/paseo/pull/10778) by [@maci0](https://github.com/maci0))
- Fixed Desktop freezing when you open a chat whose last turn has hundreds of tool calls ([#8661](https://github.com/getpaseo/paseo/pull/8661) by [@luoph](https://github.com/luoph))
- Fixed direct connections dropping on slow links while a large timeline loads ([#10651](https://github.com/getpaseo/paseo/pull/10651) by [@apple-ouyang](https://github.com/apple-ouyang))
- Fixed large Git workspaces stalling the daemon while their file watchers scan ([#10788](https://github.com/getpaseo/paseo/pull/10788), [#10602](https://github.com/getpaseo/paseo/pull/10602))
- Fixed a Git change in one repository rescanning every checkout ([#10863](https://github.com/getpaseo/paseo/pull/10863) by [@viiqswim](https://github.com/viiqswim))
- Fixed iOS chats staying blank when a pending question is taller than the screen ([#10759](https://github.com/getpaseo/paseo/pull/10759))
- Fixed Android long-press text selection in chat leaving the magnifier stuck on screen ([#10844](https://github.com/getpaseo/paseo/pull/10844))
- Fixed mobile sheet footers dropping behind the system bar when the keyboard closes ([#10827](https://github.com/getpaseo/paseo/pull/10827))
- Fixed the sidebar toggle covering plugin screen titles on macOS ([#10773](https://github.com/getpaseo/paseo/pull/10773))
- Fixed Windows file links with a slash before the drive letter failing to open ([#7711](https://github.com/getpaseo/paseo/pull/7711))
- Fixed Import Session giving up on slow providers and hiding provider errors ([#10516](https://github.com/getpaseo/paseo/pull/10516) by [@chirag127](https://github.com/chirag127), [@derek-geekdive](https://github.com/derek-geekdive))
- Fixed OMP 19.1 `ask` questions not showing a question card ([#10862](https://github.com/getpaseo/paseo/pull/10862) by [@gtoxlili](https://github.com/gtoxlili))
- Fixed OpenCode 2 agents with their own MCP servers failing when a shared OpenCode server is running. Requires OpenCode 2.0.29 or later ([#10752](https://github.com/getpaseo/paseo/pull/10752))
- Fixed deleted OpenCode subagents staying in the subagent track ([#8332](https://github.com/getpaseo/paseo/pull/8332))
- Fixed stopped Claude background subagents showing as running after you reopen the parent ([#9013](https://github.com/getpaseo/paseo/pull/9013))
- Fixed plugin and Paseo instructions replacing a Codex agent's own `developer_instructions` ([#10792](https://github.com/getpaseo/paseo/pull/10792))
- Fixed the OpenCode Go usage card missing when the Go key is in OpenCode's `auth.json` ([#10678](https://github.com/getpaseo/paseo/pull/10678))
- Fixed GitHub, GitLab, and Gitea commands on Windows breaking multiline arguments and expanding `%VAR%` text ([#10685](https://github.com/getpaseo/paseo/pull/10685))
- Fixed `paseo hub login` printing a link without the code ([#10751](https://github.com/getpaseo/paseo/pull/10751))
- Fixed Hub trigger runs failing on Antigravity and other plugin providers without tool policy support ([#10889](https://github.com/getpaseo/paseo/pull/10889))
- Fixed Hub sessions being refused when they read a daemon's provider controls ([#10794](https://github.com/getpaseo/paseo/pull/10794))
- Fixed Hermes and other plugin ACP providers leaving processes running after a model list refresh times out ([#10867](https://github.com/getpaseo/paseo/pull/10867))
- Fixed a plugin's agent tools returning `Tool not found` after the plugin reloads during a turn ([#10106](https://github.com/getpaseo/paseo/pull/10106) by [@tomgrin10](https://github.com/tomgrin10))
- Fixed replies changed by a timeline plugin losing Copy, Fork, and turn duration ([#10795](https://github.com/getpaseo/paseo/pull/10795) by [@Brandon168](https://github.com/Brandon168))
- Fixed idle plugin sessions waking the daemon every 10 seconds ([#9363](https://github.com/getpaseo/paseo/pull/9363) by [@Brandon168](https://github.com/Brandon168))
### Security
- Changed Claude Code 2.1.326 or later to receive MCP server tokens over stdin instead of in process arguments that other local users can read ([#10698](https://github.com/getpaseo/paseo/pull/10698) by [@mdbraber](https://github.com/mdbraber))
- Fixed repository teardown commands running on archive for pull request worktrees whose setup you have not approved ([#10694](https://github.com/getpaseo/paseo/pull/10694))
### Plugins
- Added launch wraps so plugins can run agents, terminals, and worktree commands inside a sandbox ([#10786](https://github.com/getpaseo/paseo/pull/10786) by [@clkao](https://github.com/clkao), [@bendavid](https://github.com/bendavid))
- Added the parent workspace to plugin workspace snapshots ([#10781](https://github.com/getpaseo/paseo/pull/10781) by [@spatenotte](https://github.com/spatenotte))
- Updated the bundled `paseo-plugin` skill to the current plugin API ([#10793](https://github.com/getpaseo/paseo/pull/10793))
## 0.17.4 - 2026-11-23
### Fixed
-90
View File
@@ -1,95 +1,5 @@
# Changelog
## 0.17.6 - 2026-11-27
### 改进
- 将设置重组为设备和主机两个范围,并合并了内容较少的页面 ([#10933](https://github.com/getpaseo/paseo/pull/10933))
- 为模型选择器中的模型、Provider 和配置文件新增方向键导航 ([#10929](https://github.com/getpaseo/paseo/pull/10929), [#10962](https://github.com/getpaseo/paseo/pull/10962))
- 在主机设置和初始设置中新增就地刷新 Tailscale 可用性的按钮 ([#10903](https://github.com/getpaseo/paseo/pull/10903))
### 变更
- 移除了在后台运行 `agy -p /usage` 的 Antigravity 用量数据源 ([#10953](https://github.com/getpaseo/paseo/pull/10953),贡献者:[@luoph](https://github.com/luoph))
### 修复
- 修复对话中出现代码块或引用时 Paseo Android 在三星设备上崩溃的问题 ([#10964](https://github.com/getpaseo/paseo/pull/10964))
- 修复在 Android 上使用鼠标点击无法选择模型选择器行的问题 ([#10972](https://github.com/getpaseo/paseo/pull/10972))
- 修复 macOS 桌面端因 Dock 进度条更新在启动时卡死的问题 ([#10939](https://github.com/getpaseo/paseo/pull/10939))
- 修复 Linux AppImage 将其运行时环境变量泄漏到 Shell 和子进程的问题 ([#10920](https://github.com/getpaseo/paseo/pull/10920))
- 修复 Linux 上后台 Git fetch 启动孤立 D-Bus 进程并在认证失败后循环重试的问题 ([#10921](https://github.com/getpaseo/paseo/pull/10921))
- 修复恢复已归档工作区和 Agent 时的界面闪烁问题,并新增恢复中状态提示 ([#10928](https://github.com/getpaseo/paseo/pull/10928))
- 修复 worktree 所有权超出已配置 worktrees 根目录的问题 ([#10878](https://github.com/getpaseo/paseo/pull/10878))
- 修复另一个标签页淘汰目录缓存后,新打开的网页标签页丢失 project 的问题 ([#10942](https://github.com/getpaseo/paseo/pull/10942))
- 修复 rewind epoch 变更时时间线丢失行的问题 ([#8794](https://github.com/getpaseo/paseo/pull/8794),贡献者:[@LiebeLee](https://github.com/LiebeLee))
## 0.17.5 - 2026-11-26
- **批量归档工作区**:在侧边栏按住 Cmd/Ctrl 点击工作区即可多选,一步归档。([#10798](https://github.com/getpaseo/paseo/pull/10798), [#10821](https://github.com/getpaseo/paseo/pull/10821))
- **复制引用草稿**:一键复制回复中的引用内容,不带 `>` 标记。([#10608](https://github.com/getpaseo/paseo/pull/10608),贡献者:[@pedrovieira](https://github.com/pedrovieira), [@dinhphieu](https://github.com/dinhphieu))
- **重新设计的智能体配置文件页面**:智能体配置文件现在有专属的设置页面,模型选择器一键即可保存新的配置文件。([#10789](https://github.com/getpaseo/paseo/pull/10789), [#10824](https://github.com/getpaseo/paseo/pull/10824))
- **重新设计的添加 project**:“添加 project”直接打开文件夹搜索,克隆和新建文件夹只需切换一个标签页。([#10767](https://github.com/getpaseo/paseo/pull/10767))
- **选择桌面端的更新方式**:桌面端可以自动下载更新、仅通知你,或完全不检查。([#10785](https://github.com/getpaseo/paseo/pull/10785))
- **全面支持 Tailscale**:在主机设置或初始设置中为主机开启 Tailscale,无需编辑配置。([#10801](https://github.com/getpaseo/paseo/pull/10801))
### 新增
- 在主机选择器中新增主机图标、连接类型和延迟 ([#10702](https://github.com/getpaseo/paseo/pull/10702),贡献者:[@artile](https://github.com/artile))
- 在模型选择器搜索和命令中心中新增智能体配置文件 ([#10774](https://github.com/getpaseo/paseo/pull/10774))
- 为 `paseo schedule create`、`paseo schedule update` 和定时任务 MCP 工具新增“完成后归档”选项 ([#8479](https://github.com/getpaseo/paseo/pull/8479),贡献者:[@ArnoldHueteG](https://github.com/ArnoldHueteG))
- 将 Factory Droid 的目录条目更新到 Droid 1.20.0,新增其较新的模型 ([#10779](https://github.com/getpaseo/paseo/pull/10779),贡献者:[@dsingal0](https://github.com/dsingal0))
### 变更
- 桌面端稳定版的自动更新改为最多每 6 小时检查一次,每次更新后等待 24 小时 ([#10882](https://github.com/getpaseo/paseo/pull/10882), [#10901](https://github.com/getpaseo/paseo/pull/10901))
### 修复
- 修复 Agent 将自己创建的子 Agent 从标签页和子 Agent 列表中隐藏的问题 ([#10887](https://github.com/getpaseo/paseo/pull/10887))
- 修复 Claude 子 Agent 等待后台任务时,父 Agent 收到的是中间回复而不是最终回复的问题 ([#10864](https://github.com/getpaseo/paseo/pull/10864))
- 修复监视 PR 的 Agent 在轮次结束后仍显示为运行中的问题 ([#10740](https://github.com/getpaseo/paseo/pull/10740),贡献者:[@drgould](https://github.com/drgould))
- 修复远程名称不是 `origin` 时“变更”面板不显示推送或拉取的问题 ([#10679](https://github.com/getpaseo/paseo/pull/10679))
- 修复拆分窗格或移出当前标签后,原窗格切换到错误标签的问题 ([#10716](https://github.com/getpaseo/paseo/pull/10716))
- 修复在“新建工作区”中选择 project 后,焦点停留在 project 按钮上的问题 ([#10632](https://github.com/getpaseo/paseo/pull/10632))
- 修复已归档的对话在窗口重新加载前一直占用内存的问题 ([#10866](https://github.com/getpaseo/paseo/pull/10866))
- 修复应用长时间运行后悬停卡片等浮层变慢的问题 ([#10778](https://github.com/getpaseo/paseo/pull/10778),贡献者:[@maci0](https://github.com/maci0))
- 修复打开最后一轮包含数百次工具调用的对话时桌面端卡顿的问题 ([#8661](https://github.com/getpaseo/paseo/pull/8661),贡献者:[@luoph](https://github.com/luoph))
- 修复在慢速网络上加载大型时间线时直接连接断开的问题 ([#10651](https://github.com/getpaseo/paseo/pull/10651),贡献者:[@apple-ouyang](https://github.com/apple-ouyang))
- 修复大型 Git 工作区在文件监视器扫描时阻塞 daemon 的问题 ([#10788](https://github.com/getpaseo/paseo/pull/10788), [#10602](https://github.com/getpaseo/paseo/pull/10602))
- 修复一个仓库中的 Git 变更导致所有检出重新扫描的问题 ([#10863](https://github.com/getpaseo/paseo/pull/10863),贡献者:[@viiqswim](https://github.com/viiqswim))
- 修复待回答问题高于屏幕时 iOS 对话一直空白的问题 ([#10759](https://github.com/getpaseo/paseo/pull/10759))
- 修复 Android 上在对话中长按选择文本后放大镜卡在屏幕上的问题 ([#10844](https://github.com/getpaseo/paseo/pull/10844))
- 修复移动端弹窗底部栏在键盘收起时落到系统栏后面的问题 ([#10827](https://github.com/getpaseo/paseo/pull/10827))
- 修复 macOS 上侧边栏切换按钮遮挡插件页面标题的问题 ([#10773](https://github.com/getpaseo/paseo/pull/10773))
- 修复 Windows 上盘符前带斜杠的文件链接无法打开的问题 ([#7711](https://github.com/getpaseo/paseo/pull/7711))
- 修复导入会话在 Provider 响应慢时提前放弃并隐藏 Provider 错误的问题 ([#10516](https://github.com/getpaseo/paseo/pull/10516),贡献者:[@chirag127](https://github.com/chirag127), [@derek-geekdive](https://github.com/derek-geekdive))
- 修复 OMP 19.1 的 `ask` 问题不显示问题卡片的问题 ([#10862](https://github.com/getpaseo/paseo/pull/10862),贡献者:[@gtoxlili](https://github.com/gtoxlili))
- 修复共享 OpenCode 服务器运行时,带有自己 MCP 服务器的 OpenCode 2 Agent 启动失败的问题。需要 OpenCode 2.0.29 或更高版本 ([#10752](https://github.com/getpaseo/paseo/pull/10752))
- 修复已删除的 OpenCode 子 Agent 一直留在子 Agent 列表中的问题 ([#8332](https://github.com/getpaseo/paseo/pull/8332))
- 修复重新打开父 Agent 后,已停止的 Claude 后台子 Agent 显示为运行中的问题 ([#9013](https://github.com/getpaseo/paseo/pull/9013))
- 修复插件和 Paseo 的指令替换 Codex Agent 自身 `developer_instructions` 的问题 ([#10792](https://github.com/getpaseo/paseo/pull/10792))
- 修复 Go 密钥保存在 OpenCode 的 `auth.json` 中时 OpenCode Go 用量卡片消失的问题 ([#10678](https://github.com/getpaseo/paseo/pull/10678))
- 修复 Windows 上 GitHub、GitLab 和 Gitea 命令破坏多行参数并展开 `%VAR%` 文本的问题 ([#10685](https://github.com/getpaseo/paseo/pull/10685))
- 修复 `paseo hub login` 输出的链接不包含验证码的问题 ([#10751](https://github.com/getpaseo/paseo/pull/10751))
- 修复 Hub 触发器在 Antigravity 等不支持工具策略的插件 Provider 上运行失败的问题 ([#10889](https://github.com/getpaseo/paseo/pull/10889))
- 修复 Hub 会话读取 daemon 的 Provider 控件时被拒绝的问题 ([#10794](https://github.com/getpaseo/paseo/pull/10794))
- 修复模型列表刷新超时后,Hermes 等插件 ACP Provider 留下进程继续运行的问题 ([#10867](https://github.com/getpaseo/paseo/pull/10867))
- 修复插件在轮次进行中重新加载后,其 Agent 工具返回 `Tool not found` 的问题 ([#10106](https://github.com/getpaseo/paseo/pull/10106),贡献者:[@tomgrin10](https://github.com/tomgrin10))
- 修复被时间线插件改写的回复缺少复制、分叉和轮次耗时的问题 ([#10795](https://github.com/getpaseo/paseo/pull/10795),贡献者:[@Brandon168](https://github.com/Brandon168))
- 修复空闲的插件会话每 10 秒唤醒一次 daemon 的问题 ([#9363](https://github.com/getpaseo/paseo/pull/9363),贡献者:[@Brandon168](https://github.com/Brandon168))
### 安全
- Claude Code 2.1.326 或更高版本现在通过 stdin 接收 MCP 服务器令牌,不再放在其他本地用户可读取的进程参数中 ([#10698](https://github.com/getpaseo/paseo/pull/10698),贡献者:[@mdbraber](https://github.com/mdbraber))
- 修复归档未批准设置的 PR worktree 时仍运行仓库 teardown 命令的问题 ([#10694](https://github.com/getpaseo/paseo/pull/10694))
### 插件
- 新增启动包装,插件可以在沙箱中运行 Agent、终端和 worktree 命令 ([#10786](https://github.com/getpaseo/paseo/pull/10786),贡献者:[@clkao](https://github.com/clkao), [@bendavid](https://github.com/bendavid))
- 在插件的工作区快照中新增父工作区 ([#10781](https://github.com/getpaseo/paseo/pull/10781),贡献者:[@spatenotte](https://github.com/spatenotte))
- 将内置的 `paseo-plugin` 技能更新到当前的插件 API ([#10793](https://github.com/getpaseo/paseo/pull/10793))
## 0.17.4 - 2026-11-23
### 修复
+1 -1
View File
@@ -15,7 +15,7 @@ Each live agent in `AgentManager` carries a `lastStatus` of `initializing`, `idl
## Daemon restart recovery
Restart recovery is off by default. Enable `agents.resumeOnStartup` in host config or
Settings → Host → Daemon to resume interrupted agents after graceful shutdown or a crash. The daemon
Host settings → Agents to resume interrupted agents after graceful shutdown or a crash. The daemon
reopens the saved provider conversation and settings, then sends `Resume working.`. Customize
the prompt with `agents.resumePrompt` or the same settings page.
Disabling recovery consumes pending intent; enabling it later does not revive old work.
-5
View File
@@ -591,11 +591,6 @@ then retry only when a requested row changes during the read. Unrelated agent st
invalidate the read. Directory baseline replacements and host removal or renaming still invalidate
the affected reads.
On web and Electron, tabs share IndexedDB but hold independent directory snapshots in memory. A
tab can commit directory deltas only while the persisted checkpoint revision matches the one it
read or wrote. If a different tab evicts or rewrites that baseline, the next full directory refresh
can replace it. Timeline writes do not depend on the directory checkpoint.
The cache is capped at 32 MiB and evicts whole hosts in least-recently-written order. After an
eviction, only a baseline replacement stores that host's directory again. Mutations queued around
the eviction are dropped when they are written, so a checkpoint never outlives its rows. Budget
+3 -3
View File
@@ -331,12 +331,12 @@ A stable desktop release reaches automatic updates in stages, so a bad release r
| Canary | For the first 8 hours, 5% of installs are admitted. |
| Ramp | From 8 hours to `rolloutHours` (18 by default), admission rises in a straight line from 5% to 100%. |
| Check interval | An install asks GitHub for the latest release at most once every 6 hours. |
| Cooldown | After an install updates, it skips paced releases for 24 hours. |
| Cooldown | After an install updates, it skips paced releases for 72 hours. |
| Staged update | An install that holds a downloaded update keeps it and does not download the paced release that follows. |
A paced release is a stable release with `rolloutHours` above 0. When `rolloutHours` is under 16, the canary hold is half of `rolloutHours`.
Every release places each install at a new position in the rollout, so the canary group changes with each release. With one or two releases per day, an install updates at most once every 24 hours and skips the releases in between.
Every release places each install at a new position in the rollout, so the canary group changes with each release. With one or two releases per day, an install updates at most once every 72 hours and skips the releases in between.
These paths skip the stages:
@@ -443,7 +443,7 @@ To resume a halted release, run `gh release edit v0.1.42 --latest` with its tag.
-f rollout_hours=0
```
Do not leave the fix as a paced release. The installs that took the bad release are in their 24-hour cooldown and skip a paced release. An install that holds the bad release as a staged update, and did not check during the halt, keeps it when a paced release follows. An emergency release reaches both.
Do not leave the fix as a paced release. The installs that took the bad release are in their 72-hour cooldown and skip a paced release. An install that holds the bad release as a staged update, and did not check during the halt, keeps it when a paced release follows. An emergency release reaches both.
### Custom ramp on a manually-dispatched build
-5
View File
@@ -61,11 +61,6 @@ the chat and its replica cache would keep only the end of the reply. A recovery
running catch-up starts after whatever that catch-up applied, because the app applies a forward page
row by row and an older cursor repeats rows.
A live row whose epoch differs from the local cursor is a rewind or replacement this client never
saw as an invalidation, not a stale row. The app recovers like a gap: it asks `after` its own
cursor, and the daemon answers that stale epoch with a reset tail. Dropping the rows instead would
leave the chat on pre-rewind history while the new epoch streams.
Initialization timeouts guard lack of catch-up progress, not the full multi-page sync. A successful page that queues the next `after` page refreshes the watchdog.
Opening or resuming an agent fetches the latest available turns with a soft target of 40
@@ -1,5 +0,0 @@
- Archive workspaces together: Cmd/Ctrl+click a workspace in the sidebar to select multiple workspaces and archive them in one step.
- Copy quoted drafts: Copy a quote from a reply with one tap, without the > markers.
- Redesigned agent profiles page: Agent profiles have their own dedicated settings page, and the model picker saves a new profile in one tap.
Full notes: https://paseo.sh/changelog
@@ -1,5 +0,0 @@
- Archive workspaces together: Cmd/Ctrl+click a workspace in the sidebar to select multiple workspaces and archive them in one step.
- Copy quoted drafts: Copy a quote from a reply with one tap, without the > markers.
- Redesigned agent profiles page: Agent profiles have their own dedicated settings page, and the model picker saves a new profile in one tap.
Full notes: https://paseo.sh/changelog
@@ -1,5 +0,0 @@
- Archive workspaces together: Cmd/Ctrl+click a workspace in the sidebar to select multiple workspaces and archive them in one step.
- Copy quoted drafts: Copy a quote from a reply with one tap, without the > markers.
- Redesigned agent profiles page: Agent profiles have their own dedicated settings page, and the model picker saves a new profile in one tap.
Full notes: https://paseo.sh/changelog
@@ -1,5 +0,0 @@
- Archive workspaces together: Cmd/Ctrl+click a workspace in the sidebar to select multiple workspaces and archive them in one step.
- Copy quoted drafts: Copy a quote from a reply with one tap, without the > markers.
- Redesigned agent profiles page: Agent profiles have their own dedicated settings page, and the model picker saves a new profile in one tap.
Full notes: https://paseo.sh/changelog
@@ -1,12 +0,0 @@
Improved
- Reorganized Settings into Device and Host sections and consolidated sparse pages
- Added arrow-key navigation for models, providers, and profiles in the model picker
- Added an in-place Refresh control for Tailscale availability in host settings and setup
Changed
- Removed the Antigravity usage source that ran agy -p /usage in the background
Fixed
- Fixed Paseo Android crashing on Samsung devices when a chat shows a code block or quote
Full notes: https://paseo.sh/changelog
@@ -1,12 +0,0 @@
Improved
- Reorganized Settings into Device and Host sections and consolidated sparse pages
- Added arrow-key navigation for models, providers, and profiles in the model picker
- Added an in-place Refresh control for Tailscale availability in host settings and setup
Changed
- Removed the Antigravity usage source that ran agy -p /usage in the background
Fixed
- Fixed Paseo Android crashing on Samsung devices when a chat shows a code block or quote
Full notes: https://paseo.sh/changelog
@@ -1,12 +0,0 @@
Improved
- Reorganized Settings into Device and Host sections and consolidated sparse pages
- Added arrow-key navigation for models, providers, and profiles in the model picker
- Added an in-place Refresh control for Tailscale availability in host settings and setup
Changed
- Removed the Antigravity usage source that ran agy -p /usage in the background
Fixed
- Fixed Paseo Android crashing on Samsung devices when a chat shows a code block or quote
Full notes: https://paseo.sh/changelog
@@ -1,12 +0,0 @@
Improved
- Reorganized Settings into Device and Host sections and consolidated sparse pages
- Added arrow-key navigation for models, providers, and profiles in the model picker
- Added an in-place Refresh control for Tailscale availability in host settings and setup
Changed
- Removed the Antigravity usage source that ran agy -p /usage in the background
Fixed
- Fixed Paseo Android crashing on Samsung devices when a chat shows a code block or quote
Full notes: https://paseo.sh/changelog
+29 -29
View File
@@ -1,12 +1,12 @@
{
"name": "paseo",
"version": "0.17.6",
"version": "0.17.4",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "paseo",
"version": "0.17.6",
"version": "0.17.4",
"hasInstallScript": true,
"license": "Apache-2.0",
"workspaces": [
@@ -37541,7 +37541,7 @@
},
"packages/app": {
"name": "@getpaseo/app",
"version": "0.17.6",
"version": "0.17.4",
"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.17.4",
"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.17.4",
"@getpaseo/protocol": "0.17.4",
"@getpaseo/server": "0.17.4",
"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.17.4",
"license": "Apache-2.0",
"dependencies": {
"@getpaseo/protocol": "0.17.6",
"@getpaseo/relay": "0.17.6",
"@getpaseo/protocol": "0.17.4",
"@getpaseo/relay": "0.17.4",
"ws": "^8.20.0",
"zod": "^4.4.3"
},
@@ -39963,7 +39963,7 @@
},
"packages/desktop": {
"name": "@getpaseo/desktop",
"version": "0.17.6",
"version": "0.17.4",
"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.17.4",
"license": "MIT",
"devDependencies": {
"@types/jest": "^29.5.14",
@@ -40252,7 +40252,7 @@
},
"packages/highlight": {
"name": "@getpaseo/highlight",
"version": "0.17.6",
"version": "0.17.4",
"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.17.4",
"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.17.4",
"@getpaseo/protocol": "0.17.4",
"@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.17.4",
"@getpaseo/protocol": "0.17.4",
"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.17.4",
"license": "Apache-2.0",
"dependencies": {
"semver": "^7.8.5",
@@ -40351,7 +40351,7 @@
}
},
"packages/react-native-enriched-markdown": {
"version": "0.17.6",
"version": "0.17.4",
"hasInstallScript": true,
"license": "MIT",
"peerDependencies": {
@@ -40367,7 +40367,7 @@
},
"packages/relay": {
"name": "@getpaseo/relay",
"version": "0.17.6",
"version": "0.17.4",
"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.17.4",
"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.17.4",
"@getpaseo/highlight": "0.17.4",
"@getpaseo/plugin": "0.17.4",
"@getpaseo/protocol": "0.17.4",
"@getpaseo/relay": "0.17.4",
"@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.17.4",
"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.17.4",
"dependencies": {
"@getpaseo/plugin": "*",
"zod": "^4.4.3"
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "paseo",
"version": "0.17.6",
"version": "0.17.4",
"private": true,
"description": "Paseo: voice-controlled development environment for local AI coding agents",
"keywords": [
@@ -32,7 +32,6 @@ import {
waitForWorkspaceTabsVisible,
} from "../support/helpers/workspace-tabs";
import { getServerId } from "../support/helpers/server-id";
import { openSettingsSection } from "../support/helpers/settings";
import { buildHostWorkspaceRoute } from "@/utils/host-routes";
import { WORKSPACE_DECK_MAX_MOUNTED_WORKSPACES } from "@/screens/workspace/workspace-deck-retention";
import { delayBrowserAgentCreatedStatus } from "../support/helpers/new-workspace";
@@ -351,7 +350,6 @@ async function selectSendBehaviorInSettings(
behaviorLabel: string,
stored: string,
): Promise<void> {
await openSettingsSection(page, "chat");
await page.getByRole("button", { name: /^Default send: / }).click();
await page.getByRole("menuitem", { name: behaviorLabel, exact: true }).click();
await expect
@@ -272,15 +272,13 @@ test.describe("Agent profiles settings", () => {
await test.step("switching Settings sections asks before discarding an edited draft", async () => {
await fillAgentProfileName(page, "Unsaved sidebar edit");
await switchSettingsSectionWithConfirm(page, "Tools & prompts", "dismiss");
await switchSettingsSectionWithConfirm(page, "Agents", "dismiss");
await expect(page.getByTestId("agent-profile-drawer")).toBeVisible();
await expectAgentProfileNameDraft(page, "Unsaved sidebar edit");
await switchSettingsSectionWithConfirm(page, "Tools & prompts", "accept");
await switchSettingsSectionWithConfirm(page, "Agents", "accept");
await expect(page.getByTestId("agent-profile-drawer")).toHaveCount(0, { timeout: 30_000 });
await expect(page.getByTestId("settings-detail-header-title")).toHaveText(
"Tools & prompts",
);
await expect(page.getByTestId("settings-detail-header-title")).toHaveText("Agents");
});
await test.step("confirming browser Back leaves Agent profiles and discards the draft", async () => {
@@ -47,7 +47,7 @@ async function openHostOverview(page: Page, daemon: IsolatedHostDaemon): Promise
endpoint: `127.0.0.1:${daemon.port}`,
},
]);
await page.goto(`/settings/hosts/${daemon.serverId}/daemon`);
await page.goto(`/settings/hosts/${daemon.serverId}/host`);
await expect(page.getByText("Online", { exact: true })).toBeVisible();
}
@@ -84,7 +84,7 @@ async function expectHelpHostVersion(page: Page, serverId: string, version: stri
async function openHostPage(page: Page, host: RestartableHostDaemon): Promise<void> {
await openSettings(page);
await selectSettingsHost(page, host.serverId);
await openHostSection(page, host.serverId, "daemon");
await openHostSection(page, host.serverId, "host");
}
function hostIdentity(page: Page) {
@@ -13,8 +13,8 @@ async function openMetadataGenerationSettings(page: Page) {
await gotoAppShell(page);
await openSettings(page);
await openSettingsHost(page, serverId);
await openHostSection(page, serverId, "workspaces");
await expectSettingsHeader(page, "Workspaces");
await openHostSection(page, serverId, "metadata");
await expectSettingsHeader(page, "Metadata");
}
async function openManualMetadataModelPicker(page: Page) {
@@ -3,9 +3,7 @@ import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
import { test, expect, type Page } from "../support/fixtures";
import { connectDaemonClient } from "../support/helpers/daemon-client-loader";
import {
clickModelRowWhileProviderOpens,
closeModelPicker,
expectModelListScrollKeepsSearchFocused,
expectModelSearchEmptyState,
expectModelPickerHeight,
expectModelPickerWidth,
@@ -156,137 +154,6 @@ test.describe("Cross-provider model search", () => {
await expectModelPickerHeight(page, restingHeight);
await expectModelPickerWidth(page, restingWidth);
});
await test.step("ArrowUp wraps to the end of a virtualized catalog and Enter selects it", async () => {
await searchAllModels(page, "bulk model");
await page.keyboard.press("ArrowUp");
// Tie-broken lexicographically by modelLabel, so "Bulk model 99" sits at the bottom.
const lastRow = page
.getByTestId("combobox-desktop-container")
.getByTestId(`model-row-${LARGE_CATALOG.id}-bulk-99`);
await expect(lastRow).toBeVisible();
await expect(lastRow).toHaveAttribute("data-active", "true");
await page.keyboard.press("Enter");
await expect(page.getByTestId("combobox-desktop-container")).toHaveCount(0);
await expect(
page.getByTestId("combined-model-selector").filter({ visible: true }).first(),
).toContainText("Bulk model 99");
});
} finally {
await workspace.cleanup();
await profile.restore();
await provider.restore();
}
});
test("arrow keys navigate profiles, providers, models, and search results in the composer", async ({
page,
}) => {
const provider = await seedModelProvider(STUDIO);
const profile = await seedAgentProfiles([
{
id: "agent_profile_e2e_arrows",
name: "Arrow Profile",
provider: STUDIO.id,
modelId: "studio-fast",
},
]);
const workspace = await seedWorkspace({ repoPrefix: "model-picker-arrows-" });
try {
await test.step("open the composer model picker on the root view", async () => {
await gotoWorkspace(page, workspace.workspaceId);
await clickNewChat(page);
await expectComposerVisible(page);
await openModelPicker(page);
});
const viewport = page.getByTestId("combobox-desktop-container");
const trigger = page.getByTestId("combined-model-selector").filter({ visible: true }).first();
const profileRow = viewport.getByTestId("model-profile-row-agent_profile_e2e_arrows");
const studioProviderRow = viewport.getByTestId(`model-provider-${STUDIO.id}`);
await test.step("move from profiles to providers, drill in with ArrowRight, and go back with ArrowLeft", async () => {
await expect(profileRow).toHaveAttribute("data-active", "true");
// Root view keeps aria-selected absent while keyboard-active uses data-active.
await expect(viewport.locator("[aria-selected]")).toHaveCount(0);
// Step down until Mock Studio is active (provider order can vary across environments).
for (let step = 0; step < 10; step += 1) {
if ((await studioProviderRow.getAttribute("data-active")) === "true") break;
await page.keyboard.press("ArrowDown");
}
await expect(studioProviderRow).toHaveAttribute("data-active", "true");
await page.keyboard.press("ArrowRight");
await expect(viewport.getByTestId(`model-row-${STUDIO.id}-studio-fast`)).toBeVisible();
await page.keyboard.press("ArrowLeft");
await expect(studioProviderRow).toHaveAttribute("data-active", "true");
});
await test.step("Enter drills into the active provider and ArrowDown + Enter selects a model", async () => {
await page.keyboard.press("Enter");
const deepRow = viewport.getByTestId(`model-row-${STUDIO.id}-studio-deep`);
await expect(deepRow).toBeVisible();
await expectModelListScrollKeepsSearchFocused(page);
for (let step = 0; step < 5; step += 1) {
if ((await deepRow.getAttribute("data-active")) === "true") break;
await page.keyboard.press("ArrowDown");
}
await expect(deepRow).toHaveAttribute("data-active", "true");
await page.keyboard.press("Enter");
await expect(viewport).toHaveCount(0);
await expect(trigger).toContainText("Studio deep think");
});
await test.step("typing filters results while arrow keys select across search matches", async () => {
await openModelPicker(page);
await searchAllModels(page, "ten second stream");
const studioFast = viewport.getByTestId(`model-row-${STUDIO.id}-studio-fast`);
const mockFast = viewport.getByTestId("model-row-mock-ten-second-stream");
await expect(studioFast).toBeVisible();
await expect(mockFast).toBeVisible();
// Advance to the second match and confirm with Enter.
const initialMockActive = (await mockFast.getAttribute("data-active")) === "true";
await page.keyboard.press("ArrowDown");
const targetRow = initialMockActive ? studioFast : mockFast;
await expect(targetRow).toHaveAttribute("data-active", "true");
await page.keyboard.press("Enter");
await expect(viewport).toHaveCount(0);
await expect(trigger).toContainText("Ten second stream");
});
await test.step("a press on a model row selects it while the provider list is still opening", async () => {
await openModelPicker(page);
await clickModelRowWhileProviderOpens(page, {
provider: "mock",
modelLabel: "One minute stream",
});
await expect(viewport).toHaveCount(0);
await expect(trigger).toContainText("One minute stream");
});
await test.step("Enter on the active profile row applies it", async () => {
await openModelPicker(page);
await expect(profileRow).toHaveAttribute("data-active", "true");
await page.keyboard.press("Enter");
await expect(viewport).toHaveCount(0);
await expect(trigger).toContainText("Ten second stream");
});
await test.step("folded compact sheet also supports Enter on the active profile row", async () => {
await page.setViewportSize({ width: 390, height: 800 });
await page.getByTestId("combined-model-selector").filter({ visible: true }).first().click();
const sheetProfileRow = page.getByTestId("model-profile-row-agent_profile_e2e_arrows");
await expect(sheetProfileRow).toBeVisible();
await expect(sheetProfileRow).toHaveAttribute("data-active", "true");
await page.keyboard.press("Enter");
await expect(sheetProfileRow).toHaveCount(0);
});
} finally {
await workspace.cleanup();
await profile.restore();
+4 -4
View File
@@ -105,7 +105,7 @@ test("a new user is walked through setup once", async ({ page }, testInfo) => {
await expectSetupStep(page, "Let agents use Paseo");
await expect(paseoToolsSwitch(setupModal(page))).toBeChecked();
await expect(
setupModal(page).getByRole("switch", { name: "Paseo skills", exact: true }),
setupModal(page).getByRole("switch", { name: "Orchestration skills", exact: true }),
).toBeChecked();
await page.screenshot({ path: testInfo.outputPath("4-orchestration.png") });
});
@@ -417,7 +417,7 @@ test("setup choices carry over to Settings and the phone step pairs over relay",
await test.step("Finish closes setup and Settings shows the same Paseo tools value", async () => {
await finishSetup(page);
await page.locator('[data-testid="sidebar-settings"]:visible').first().click();
await openSettingsHostSection(page, host.serverId, "tools");
await openSettingsHostSection(page, host.serverId, "agents");
await expect(paseoToolsSwitch(page)).toBeChecked();
await page.screenshot({ path: testInfo.outputPath("7-settings-agents.png") });
});
@@ -439,7 +439,7 @@ test("with no skills picked, skills read as off and Continue moves on", async ({
await chooseCustomSkills(page, []);
await saveSkillSelection(page);
const skillsSwitch = setupModal(page).getByRole("switch", {
name: "Paseo skills",
name: "Orchestration skills",
exact: true,
});
await expect(skillsSwitch).not.toBeChecked();
@@ -476,7 +476,7 @@ test("in the compact layout, Finish on Orchestration applies its switches", asyn
await step("Let agents use Paseo");
await expect(paseoToolsSwitch(page)).toBeChecked();
// Skills are not installed, so leaving them off has nothing to apply.
const skillsSwitch = page.getByRole("switch", { name: "Paseo skills", exact: true });
const skillsSwitch = page.getByRole("switch", { name: "Orchestration skills", exact: true });
await skillsSwitch.click();
await expect(skillsSwitch).not.toBeChecked();
gate.holdNextClientRequest("set_daemon_config_request");
@@ -15,12 +15,8 @@ import {
disableTailscale,
enableTailscale,
expectTailscaleAddress,
expectTailscaleAvailable,
expectTailscaleRowLoadsOn,
expectTailscaleUnavailable,
observeDaemonStatusPolling,
openSetupMobileStep,
refreshTailscaleAvailability,
slowConnectionToHost,
expectTailscaleUpdateRequired,
expectCompletePairingQr,
@@ -97,11 +93,6 @@ test("turns Tailscale on and off from Devices, asking first over Tailscale", asy
const restoreSpeed = await slowConnectionToHost(page, daemon.port, 300);
await expectTailscaleRowLoadsOn(page, address, () => openSetupMobileStep(page, daemon));
await expectTailscaleRowLoadsOn(page, address, () => preparePairingHost(page, daemon));
await test.step("Turning Tailscale off and back on settles over a slow connection", async () => {
await disableTailscale(page, address);
await enableTailscale(page);
await expectTailscaleAddress(page, address);
});
restoreSpeed();
});
@@ -119,54 +110,3 @@ test("turns Tailscale on and off from Devices, asking first over Tailscale", asy
await daemon.close();
}
});
test("refreshes Tailscale availability in place after Tailscale starts", async ({
page,
baseURL,
}) => {
test.skip(process.platform !== "linux", "Uses a second IPv4 loopback address");
test.setTimeout(120_000);
if (!baseURL) throw new Error("Expected the app base URL");
const daemon = await startTailscaleTestDaemon(baseURL, { initialAvailable: false });
const statusPolling = observeDaemonStatusPolling(page, daemon.port);
try {
await preparePairingHost(page, daemon);
await expectTailscaleUnavailable(page);
await test.step("Refreshing while still unavailable shows progress and stays unavailable", async () => {
const restoreSpeed = await slowConnectionToHost(page, daemon.port, 250);
await preparePairingHost(page, daemon);
await expectTailscaleUnavailable(page);
await refreshTailscaleAvailability(page);
await page.getByRole("button", { name: "Refreshing...", exact: true }).waitFor();
await expectTailscaleUnavailable(page);
restoreSpeed();
});
await test.step("Refreshing after Tailscale starts enables the switch in place", async () => {
await statusPolling.waitForFreshPollWindow();
await daemon.setTailscaleAvailable(true);
const refreshRequest = statusPolling.waitForStatusRequest(1_000);
await refreshTailscaleAvailability(page);
await refreshRequest;
await expectTailscaleAvailable(page, { timeout: 1_000 });
await enableTailscale(page);
await expectTailscaleAddress(page, daemon.tailscaleAddress);
await disableTailscale(page, daemon.tailscaleAddress);
});
await test.step("Setup mobile step also refreshes Tailscale availability in place", async () => {
await daemon.setTailscaleAvailable(false);
await openSetupMobileStep(page, daemon);
await expectTailscaleUnavailable(page);
await statusPolling.waitForFreshPollWindow();
await daemon.setTailscaleAvailable(true);
const refreshRequest = statusPolling.waitForStatusRequest(1_000);
await refreshTailscaleAvailability(page);
await refreshRequest;
await expectTailscaleAvailable(page, { timeout: 1_000 });
});
} finally {
await daemon.close();
}
});
@@ -33,7 +33,7 @@ function askAgain(page: Page) {
async function openFilesSettings(page: Page) {
await openSettings(page);
await openSettingsSection(page, "chat");
await openSettingsSection(page, "files");
await expect(page.getByTestId("file-panel-settings")).toBeVisible();
}
@@ -91,7 +91,6 @@ test("Settings > Files chooses which panel opens .md and asks again on request",
await page.setViewportSize({ width: 390, height: 844 });
await page.goto("/settings/files");
await expect(markdownDropdown(page, PLUGIN_MARKDOWN_OPTION)).toBeVisible({ timeout: 30_000 });
await askAgain(page).scrollIntoViewIfNeeded();
await expect(askAgain(page)).toBeInViewport({ ratio: 1 });
await capture(page, testInfo, "file-panel-settings-compact");
await markdownDropdown(page, PLUGIN_MARKDOWN_OPTION).click();
@@ -114,20 +113,22 @@ test("Settings > Files chooses which panel opens .md and asks again on request",
}
});
test("Settings > Chat & panes hides file panels when no plugin adds one", async ({
test("Settings > Files explains where file panels come from when no plugin adds one", async ({
page,
}, testInfo) => {
await page.setViewportSize({ width: 1280, height: 900 });
await page.goto("/settings/files");
await expect(page).toHaveURL(/\/settings\/chat$/);
await expect(page.getByTestId("file-panel-settings")).toHaveCount(0);
const empty = page.getByTestId("file-panel-settings-empty");
await expect(empty).toHaveText("File panels appear here when a plugin adds one", {
timeout: 30_000,
});
await capture(page, testInfo, "file-panel-settings-empty-wide");
await page.setViewportSize({ width: 390, height: 844 });
await expect(page.getByTestId("file-panel-settings")).toHaveCount(0);
await expect(empty).toBeVisible();
await capture(page, testInfo, "file-panel-settings-empty-compact");
});
test("Settings > Chat & panes offers Source in place of a panel no host has, and forgets it", async ({
test("Settings > Files offers Source in place of a panel no host has, and forgets it", async ({
page,
}) => {
await page.addInitScript(() => {
@@ -145,5 +146,5 @@ test("Settings > Chat & panes offers Source in place of a panel no host has, and
await page.keyboard.press("Escape");
await expect(page.getByRole("menuitem", { name: SOURCE_OPTION })).toBeHidden();
await row.getByRole("button", { name: "Ask again for .pdf", exact: true }).click();
await expect(page.getByTestId("file-panel-settings")).toHaveCount(0);
await expect(page.getByTestId("file-panel-settings-empty")).toBeVisible();
});
@@ -3,7 +3,7 @@ import { test } from "../support/fixtures";
import { gotoAppShell, openSettings } from "../support/helpers/app";
import { renameHostFromSettings } from "../support/helpers/hosts";
import { getServerId } from "../support/helpers/server-id";
import { openClientHostSettings } from "../support/helpers/settings";
import { openHostSection, selectSettingsHost } from "../support/helpers/settings";
const REGISTRY_KEY = "@paseo:daemon-registry";
const SEED_NONCE_KEY = "@paseo:e2e-seed-nonce";
@@ -87,7 +87,8 @@ test("saved hosts survive a registry entry this build can't read, and saving kee
await test.step("renaming a host keeps its password and the entries it can't read", async () => {
await openSettings(page);
await openClientHostSettings(page, OFFLINE_HOST.serverId);
await selectSettingsHost(page, OFFLINE_HOST.serverId);
await openHostSection(page, OFFLINE_HOST.serverId, "host");
await renameHostFromSettings(page, "Renamed offline host");
await expect
@@ -18,7 +18,6 @@ import {
expectProviderNotOnHost,
expectProviderPageLoaded,
gotoProviderPage,
openClientHostSettings,
openSettingsHost,
openHostSection,
expectHostLabelDisplayed,
@@ -54,30 +53,36 @@ test.describe("Settings host page", () => {
const port = getE2EDaemonPort();
await gotoAppShell(page);
await openSettings(page);
await test.step("client host detail shows the seeded connection endpoint and label editor", async () => {
await openClientHostSettings(page, serverId);
await openSettingsHost(page, serverId);
await test.step("connections section shows the seeded connection endpoint", async () => {
await expectSettingsHeader(page, "Connections");
await expectHostConnectionsCard(page, port);
await expectHostLabelDisplayed(page);
await clickEditHostLabel(page);
await expectHostLabelEditMode(page, TEST_HOST_LABEL);
await page.keyboard.press("Escape");
});
await test.step("tools section shows the inject MCP toggle", async () => {
await openHostSection(page, serverId, "tools");
await expectSettingsHeader(page, "Tools & prompts");
await test.step("agents section shows the inject MCP toggle", async () => {
await openHostSection(page, serverId, "agents");
await expectSettingsHeader(page, "Agents");
await expectHostInjectMcpCard(page);
});
await test.step("providers section shows the providers card", async () => {
await expectHostProvidersCard(page, serverId);
await expectSettingsHeader(page, "Providers");
});
await test.step("daemon section shows restart and client host shows remove", async () => {
await openHostSection(page, serverId, "daemon");
await expectSettingsHeader(page, "Daemon");
await test.step("host section shows the host label and restart/remove action cards", async () => {
await openHostSection(page, serverId, "host");
await expectSettingsHeader(page, "Overview");
await expectHostLabelDisplayed(page);
await expectHostActionCards(page, serverId);
});
await test.step("daemon section does not render daemon lifecycle controls for a remote daemon", async () => {
await openHostSection(page, serverId, "daemon");
await test.step("clicking the label pencil reveals the inline editor", async () => {
await openHostSection(page, serverId, "host");
await expectHostLabelDisplayed(page);
await clickEditHostLabel(page);
await expectHostLabelEditMode(page, TEST_HOST_LABEL);
await page.keyboard.press("Escape");
});
await test.step("host section does not render daemon lifecycle controls for a remote daemon", async () => {
await openHostSection(page, serverId, "host");
await expectHostNoDaemonLifecycleRow(page);
});
@@ -94,7 +99,7 @@ test.describe("Settings host page", () => {
await page.reload();
await openSettings(page);
await openSettingsHost(page, outdatedDaemon.serverId);
await openHostSection(page, outdatedDaemon.serverId, "daemon");
await openHostSection(page, outdatedDaemon.serverId, "host");
page.once("dialog", (dialog) => dialog.accept());
const updateButton = page.getByTestId("host-page-update-button");
@@ -133,7 +138,8 @@ test.describe("Settings host page", () => {
]);
await page.reload();
await openSettings(page);
await openClientHostSettings(page, daemon.serverId);
await selectSettingsHost(page, daemon.serverId);
await openHostSection(page, daemon.serverId, "host");
await test.step("the host page shows the reason and the re-add guidance, with no password UI", async () => {
await expectHostRejectedWithReAddGuidance(page, "Password required");
@@ -143,7 +149,7 @@ test.describe("Settings host page", () => {
await test.step("removing the host and adding it again with the password brings it online", async () => {
await removeHostFromHostPage(page, daemon.serverId);
await addDirectHostFromSettings(page, { host: "127.0.0.1", port: daemon.port, password });
await openHostSection(page, daemon.serverId, "daemon");
await openHostSection(page, daemon.serverId, "host");
await expectHostOnlineWithoutError(page);
});
} finally {
@@ -186,7 +192,7 @@ test.describe("Settings host page", () => {
await page.reload();
await openSettings(page);
await selectSettingsHost(page, serverId);
await openHostSection(page, serverId, "daemon");
await openHostSection(page, serverId, "agents");
};
try {
await test.step("idle agent release starts on and turns off", async () => {
@@ -207,7 +213,7 @@ test.describe("Settings host page", () => {
await test.step("other hosts keep their own setting", async () => {
await selectSettingsHost(page, primaryServerId);
await openHostSection(page, primaryServerId, "daemon");
await openHostSection(page, primaryServerId, "agents");
await expectIdleAgentRelease(page, true);
await expectLiveSavedSetting(false);
});
@@ -226,7 +232,7 @@ test.describe("Settings host page", () => {
]);
await page.reload();
await openSettings(page);
await openHostSection(page, daemon.serverId, "daemon");
await openHostSection(page, daemon.serverId, "agents");
await expectIdleAgentRelease(page, true);
// A real filesystem failure, with the daemon and RPC path intact.
await rename(configPath, `${configPath}.saved`);
@@ -245,7 +251,7 @@ test.describe("Settings host page", () => {
}
});
test("navigating to /settings/hosts/[serverId] redirects to the daemon section", async ({
test("navigating to /settings/hosts/[serverId] redirects to the connections section", async ({
page,
}) => {
const serverId = getServerId();
@@ -254,9 +260,10 @@ test.describe("Settings host page", () => {
await page.goto(`/settings/hosts/${encodeURIComponent(serverId)}`);
await expectHostPageVisible(page, serverId);
await expectSettingsHeader(page, "Daemon");
await expectHostActionCards(page, serverId);
await expectSettingsHeader(page, "Connections");
await openHostSection(page, serverId, "host");
await expectHostLabelDisplayed(page);
await expectHostActionCards(page, serverId);
});
});
@@ -279,7 +286,7 @@ test("restart recovery defaults off and persists opt-in and custom prompt", asyn
await gotoAppShell(page);
await openSettings(page);
await openSettingsHost(page, serverId);
await openHostSection(page, serverId, "daemon");
await openHostSection(page, serverId, "agents");
await expectRestartRecoveryEnabled(page, false);
await setRestartRecoveryEnabled(page, true);
await page.reload();
@@ -347,12 +354,12 @@ test("sidebar Add host completes without navigating", async ({ page }) => {
await expect(page.getByRole("button", { name: "Hosts", exact: true })).toBeVisible();
});
test("Settings Add host opens the saved host detail", async ({ page }) => {
test("Settings Add host opens the saved host Overview", async ({ page }) => {
await gotoAppShell(page);
await openSettings(page);
await addDirectHostFromSettings(page, { host: "127.0.0.1", port: Number(getE2EDaemonPort()) });
await expect(page.getByTestId("host-page-connections-card")).toBeVisible();
await expect(page).toHaveURL(new RegExp(`/settings/device-hosts/${getServerId()}$`));
await expectSettingsHeader(page, "Overview");
await expect(page).toHaveURL(new RegExp(`/settings/hosts/${getServerId()}/host$`));
});
test("New workspace Add host preserves the prompt after connecting", async ({ page }) => {
@@ -46,15 +46,15 @@ test.describe("Settings host selection", () => {
await openSettings(page);
await openSettingsHostSection(page, remoteDaemon.serverId, "daemon");
await openSettingsHostSection(page, remoteDaemon.serverId, "connections");
await selectSettingsHost(page, getServerId());
await openSettingsSection(page, "appearance");
await openSettingsHostSection(page, getServerId(), "daemon");
await openSettingsHostSection(page, getServerId(), "connections");
await clickSettingsBackToWorkspace(page);
await openSettings(page);
await openSettingsHostSection(page, remoteDaemon.serverId, "daemon");
await openSettingsHostSection(page, remoteDaemon.serverId, "connections");
} finally {
await remoteWorkspace.cleanup().catch(() => undefined);
await remoteDaemon.close().catch(() => undefined);
@@ -9,17 +9,17 @@ test("Settings language selector switches General labels", async ({ page }) => {
await openSettings(page);
await openSettingsSection(page, "general");
await expect(page.getByText("Language", { exact: true }).first()).toBeVisible();
await expect(page.getByText("Default send", { exact: true }).first()).toBeVisible();
await page.getByRole("button", { name: "System", exact: true }).click();
await page.getByRole("menuitem", { name: "简体中文 - Simplified Chinese", exact: true }).click();
await expect(page.getByText("语言", { exact: true }).first()).toBeVisible();
await expect(page.getByText("默认发送", { exact: true }).first()).toBeVisible();
await page.getByRole("button", { name: "简体中文", exact: true }).click();
await page.getByRole("menuitem", { name: "English - 英语", exact: true }).click();
await expect(page.getByText("Language", { exact: true }).first()).toBeVisible();
await expect(page.getByText("Default send", { exact: true }).first()).toBeVisible();
});
test("Settings language selector switches to Korean", async ({ page }) => {
@@ -32,10 +32,10 @@ test("Settings language selector switches to Korean", async ({ page }) => {
await page.getByRole("button", { name: "System", exact: true }).click();
await page.getByRole("menuitem", { name: "한국어 - Korean", exact: true }).click();
await expect(page.getByText("언어", { exact: true }).first()).toBeVisible();
await expect(page.getByText("기본 전송", { exact: true }).first()).toBeVisible();
await page.getByRole("button", { name: "한국어", exact: true }).click();
await page.getByRole("menuitem", { name: "English - 영어", exact: true }).click();
await expect(page.getByText("Language", { exact: true }).first()).toBeVisible();
await expect(page.getByText("Default send", { exact: true }).first()).toBeVisible();
});
@@ -62,7 +62,6 @@ import {
seedSavedSettingsHosts,
selectSettingsHost,
expectSettingsHostPickerLabel,
openClientHostSettings,
openSettingsHostSection,
removeCurrentHostFromSettings,
openSidebarHostPicker,
@@ -177,28 +176,28 @@ test.describe("Settings sidebar scroll position", () => {
}
const sidebar = page.getByTestId("settings-sidebar");
const appScrollTop = await revealSettingsSidebarSection(page, "about");
const appScrollTop = await revealSettingsSidebarSection(page, "diagnostics");
await expect(sidebar.getByRole("button", { name: "About", exact: true })).toBeInViewport();
await openSettingsSection(page, "about");
await expectAboutContent(page);
await expectDiagnosticsContent(page);
await expectSettingsSidebarScrollOffset(page, appScrollTop);
await openSettingsSection(page, "shortcuts");
await openSettingsSection(page, "diagnostics");
await expectDiagnosticsContent(page);
await expectSettingsSidebarScrollOffset(page, appScrollTop);
});
});
});
test.describe("Settings sidebar navigation", () => {
test("the sidebar host row opens Daemon in one click", async ({ page, withWorkspace }) => {
test("the sidebar host row opens Overview in one click", async ({ page, withWorkspace }) => {
const workspace = await withWorkspace({ prefix: "sidebar-host-settings-" });
await openWorkspace(page, workspace);
await openSidebarHostPicker(page);
await sidebarHostRowButton(page).click();
await expectAppRoute(page, buildSettingsHostSectionRoute(getServerId(), "daemon"));
await expectAppRoute(page, buildSettingsHostSectionRoute(getServerId(), "host"));
});
test("Enter opens the active sidebar host row", async ({ page, withWorkspace }) => {
@@ -208,7 +207,7 @@ test.describe("Settings sidebar navigation", () => {
await openSidebarHostPicker(page);
await activateSidebarHostSettingsWithKeyboard(page);
await expectAppRoute(page, buildSettingsHostSectionRoute(getServerId(), "daemon"));
await expectAppRoute(page, buildSettingsHostSectionRoute(getServerId(), "host"));
});
test("opening Settings closes the composer model selector until it is opened again", async ({
@@ -283,10 +282,13 @@ test.describe("Settings sidebar navigation", () => {
await gotoAppShell(page);
await openSettings(page);
await openSettingsSection(page, "diagnostics");
await expectSettingsHeader(page, "Diagnostics");
await expectDiagnosticsContent(page);
await openSettingsSection(page, "about");
await expectSettingsHeader(page, "About");
await expectAboutContent(page);
await expectDiagnosticsContent(page);
await openSettingsSection(page, "general");
await expectSettingsHeader(page, "General");
@@ -311,18 +313,18 @@ test.describe("Settings sidebar navigation", () => {
await gotoAppShell(page);
await openSettings(page);
await selectSettingsHost(page, secondaryServerId);
await openSettingsHostSection(page, secondaryServerId, "daemon");
await openSettingsHostSection(page, secondaryServerId, "connections");
await openSettingsSection(page, "appearance");
await expectSettingsHostPickerLabel(page, "Stable horse");
await openSettingsSection(page, "general");
await expectSettingsHostPickerLabel(page, "Stable horse");
await openSettingsHostSection(page, secondaryServerId, "daemon");
await openSettingsHostSection(page, secondaryServerId, "connections");
await selectSettingsHost(page, primaryServerId);
await openSettingsSection(page, "about");
await expectSettingsHostPickerLabel(page, "First horse");
});
test("/h/[serverId]/settings redirects to the host daemon section", async ({ page }) => {
test("/h/[serverId]/settings redirects to the host connections section", async ({ page }) => {
await gotoAppShell(page);
await verifyLegacyHostSettingsRedirect(page);
});
@@ -526,12 +528,12 @@ test.describe("Settings — compact master-detail", () => {
await gotoAppShell(page);
await openCompactSettings(page, buildOpenProjectRoute());
await expectSettingsSidebarSections(page, ["general", "hosts", "about"]);
await expectSettingsSidebarSections(page, ["general", "diagnostics", "about"]);
await expectCompactSettingsList(page);
await test.step("open app details and return to the list", async () => {
await openSettingsSection(page, "about");
await expectAppRoute(page, buildSettingsSectionRoute("about"));
await openSettingsSection(page, "diagnostics");
await expectAppRoute(page, buildSettingsSectionRoute("diagnostics"));
await expectDiagnosticsContent(page);
await expectSettingsSidebarHidden(page);
await expectSettingsBackButton(page);
@@ -552,7 +554,7 @@ test.describe("Settings — compact master-detail", () => {
});
});
test("host picker settings opens Daemon and backs through the settings list", async ({
test("host picker settings opens Overview and backs through the settings list", async ({
page,
withWorkspace,
}) => {
@@ -564,8 +566,8 @@ test.describe("Settings — compact master-detail", () => {
await page.getByTestId("sidebar-hosts-trigger").click();
await sidebarHostRowButton(page).click();
await expectAppRoute(page, buildSettingsHostSectionRoute(getServerId(), "daemon"));
await expect(page.getByText("Daemon", { exact: true }).first()).toBeVisible();
await expectAppRoute(page, buildSettingsHostSectionRoute(getServerId(), "host"));
await expect(page.getByText("Overview", { exact: true })).toBeVisible();
await goBackInSettings(page);
await expectCompactSettingsList(page);
@@ -595,14 +597,14 @@ test.describe("Settings — compact master-detail", () => {
await expectSettingsSidebarVisible(page);
await expectSettingsHostPickerLabel(page, secondaryHostLabel);
await openSettingsHostSection(page, secondaryServerId, "daemon");
await openSettingsHostSection(page, secondaryServerId, "connections");
await goBackInSettings(page);
await expectSettingsHostPickerLabel(page, secondaryHostLabel);
await openSettingsSection(page, "appearance");
await goBackInSettings(page);
await expectSettingsHostPickerLabel(page, secondaryHostLabel);
await openSettingsHostSection(page, secondaryServerId, "daemon");
await openSettingsHostSection(page, secondaryServerId, "connections");
await goBackInSettings(page);
await expectSettingsHostPickerLabel(page, secondaryHostLabel);
});
@@ -615,9 +617,8 @@ test.describe("Settings — compact master-detail", () => {
await openWorkspace(page, workspace);
await openCompactSettings(page, buildHostWorkspaceRoute(getServerId(), workspace.workspaceId));
await openClientHostSettings(page, getServerId());
await openSettingsHostSection(page, getServerId(), "host");
await removeCurrentHostFromSettings(page);
await goBackInSettings(page);
await closeCompactSettings(page);
await expect(page).toHaveURL(/\/welcome$/);
@@ -5,7 +5,6 @@ import { createMockIdleAgent, openWorkspaceWithAgents } from "../support/helpers
import { waitForTabBar, expectAgentTabActive } from "../support/helpers/launcher";
import { seedWorkspace } from "../support/helpers/seed-client";
import { getServerId } from "../support/helpers/server-id";
import { openSettingsSection } from "../support/helpers/settings";
async function pressSettingsToggleShortcut(page: import("@playwright/test").Page) {
const modifier = process.platform === "darwin" ? "Meta" : "Control";
@@ -135,7 +134,6 @@ test.describe("Settings toggle tab regression", () => {
await pressSettingsToggleShortcut(page);
await expect(page).toHaveURL(/\/settings\/general$/);
await openSettingsSection(page, "chat");
const defaultSendTrigger = page.getByRole("button", {
name: "Default send: Steer",
@@ -326,7 +324,6 @@ test("send shortcut selection persists and controls the composer", async ({ page
});
await test.step("choose the explicit modifier shortcut and retain it after reload", async () => {
await pressSettingsToggleShortcut(page);
await openSettingsSection(page, "chat");
await expect(
page.getByRole("button", { name: "Send shortcut: Enter", exact: true }),
).toBeVisible();
@@ -354,7 +351,6 @@ test("send shortcut selection persists and controls the composer", async ({ page
});
await test.step("switch back to Enter without changing the default send behavior", async () => {
await pressSettingsToggleShortcut(page);
await openSettingsSection(page, "chat");
await selectSendingOption(page, "Send shortcut", "Enter");
await pressSettingsToggleShortcut(page);
await composer.fill("Shift still edits");
@@ -379,7 +375,6 @@ for (const behavior of ["Steer", "Interrupt", "Queue"] as const) {
await openAgentRoute(page, agent);
await expect(page.getByRole("textbox", { name: "Message agent..." })).toBeVisible();
await pressSettingsToggleShortcut(page);
await openSettingsSection(page, "chat");
await selectSendingOption(page, "Send shortcut", `${modifierLabel}+Enter`);
await selectSendingOption(page, "Default send", behavior);
await pressSettingsToggleShortcut(page);
@@ -175,7 +175,7 @@ test("searches keyboard shortcuts from the sidebar help menu", async ({ page })
test("keeps diagnostics available from Settings after globalizing the sheet", async ({ page }) => {
await gotoAppShell(page);
await openSettings(page);
await openSettingsSection(page, "about");
await openSettingsSection(page, "diagnostics");
await page.getByRole("button", { name: "Run", exact: true }).click();
await expectDiagnosticReport(page);
@@ -210,14 +210,14 @@ async function simulateDamagedLegacyDirectoryCache(
return;
}
const stored = JSON.parse(checkpoint.payload);
// Read the cursors from whichever version wrote them, then store them as version 2:
// the format whose writer could keep a checkpoint after another tab evicted its rows.
// Read the cursors from whichever version wrote them, then store them as version 1:
// the format whose writer could keep a checkpoint after evicting the rows it describes.
const cursors = typeof stored.version === "number" ? stored.cursors : stored;
if (!cursors?.workspaces?.generation) {
transaction.abort();
return;
}
store.put({ ...checkpoint, payload: JSON.stringify({ version: 2, cursors }) });
store.put({ ...checkpoint, payload: JSON.stringify({ version: 1, cursors }) });
for (const row of rows) {
if (
row.serverId === serverId &&
@@ -2,7 +2,6 @@ import type { Page } from "@playwright/test";
import { expect, test } from "../support/fixtures";
import { gotoAppShell } from "../support/helpers/app";
import {
archiveLocalWorkspaceFromDaemon,
archiveWorkspaceFromDaemon,
connectNewWorkspaceDaemonClient,
createWorktreeViaDaemon,
@@ -10,12 +9,7 @@ import {
} from "../support/helpers/new-workspace";
import { getServerId } from "../support/helpers/server-id";
import { expectWorkspaceAbsentFromSidebar } from "../support/helpers/sidebar";
import {
createMockIdleAgent,
fetchAgentArchivedAt,
openSessions,
openWorkspaceWithAgents,
} from "../support/helpers/archive-tab";
import { createMockIdleAgent, openWorkspaceWithAgents } from "../support/helpers/archive-tab";
import { connectSeedClient } from "../support/helpers/seed-client";
import { createTempGitRepo } from "../support/helpers/workspace";
import { getWorkspaceTabTestIds } from "../support/helpers/workspace-tabs";
@@ -44,61 +38,6 @@ import {
waitForWorkspaceInSidebar,
} from "../support/helpers/workspace-ui";
async function clearIndexedDbDatabases(page: Page): Promise<void> {
await page.evaluate(async () => {
const dbs = (await indexedDB.databases?.()) ?? [];
for (const db of dbs) {
if (!db.name) continue;
await new Promise<void>((resolve) => {
const req = indexedDB.deleteDatabase(db.name!);
const done = () => resolve();
req.addEventListener("success", done, { once: true });
req.addEventListener("error", done, { once: true });
req.addEventListener("blocked", done, { once: true });
});
}
});
}
async function delayRefreshAgentRequests(page: Page, delayMs: number): Promise<void> {
await page.routeWebSocket(/\/ws/, (ws) => {
const server = ws.connectToServer();
ws.onMessage((message) => {
if (typeof message === "string" && isRefreshAgentRequestMessage(message)) {
setTimeout(() => {
server.send(message);
}, delayMs);
return;
}
server.send(message);
});
server.onMessage((message) => {
ws.send(message);
});
});
}
function isRefreshAgentRequestMessage(message: string): boolean {
try {
const parsed = JSON.parse(message) as { type?: string; message?: { type?: string } };
return (
parsed.type === "refresh_agent_request" || parsed.message?.type === "refresh_agent_request"
);
} catch {
return false;
}
}
async function isSidebarFooterHitTestable(page: Page): Promise<boolean> {
return page.evaluate(() => {
const footer = document.querySelector('[data-testid="sidebar-footer"]');
if (!(footer instanceof HTMLElement)) return false;
const rect = footer.getBoundingClientRect();
const topEl = document.elementFromPoint(rect.left + rect.width / 2, rect.top + rect.height / 2);
return Boolean(topEl && footer.contains(topEl));
});
}
test.describe("Workspace archive undo", () => {
let client: Awaited<ReturnType<typeof connectNewWorkspaceDaemonClient>>;
let tempRepo: { path: string; cleanup: () => Promise<void> };
@@ -357,12 +296,6 @@ test.describe("Workspace archive undo", () => {
await createMockIdleAgent(seedClient, { ...target, title: "first" }),
await createMockIdleAgent(seedClient, { ...target, title: "second" }),
] as const;
const preArchivedAgent = await createMockIdleAgent(seedClient, {
...target,
title: "pre-archived",
});
await seedClient.archiveAgent(preArchivedAgent.id);
await expect.poll(() => fetchAgentArchivedAt(seedClient, preArchivedAgent.id)).not.toBeNull();
await openWorkspaceWithAgents(page, [agents[0], agents[1]]);
const tabsBefore = await getWorkspaceTabTestIds(page);
@@ -375,66 +308,9 @@ test.describe("Workspace archive undo", () => {
for (const agent of agents) {
await expect(page.getByTestId(`workspace-tab-agent_${agent.id}`).first()).toBeVisible();
}
await expect(
page.getByTestId("agent-unarchiving-callout").filter({ visible: true }),
).toHaveCount(1);
await expect(page.getByRole("button", { name: "Unarchive", exact: true })).toHaveCount(0);
// Opening an agent that was already archived before the workspace archive still shows
// the manual Unarchive callout rather than claiming it is unarchiving with the workspace.
await openSessions(page);
await page.getByTestId(`agent-row-${getServerId()}-${preArchivedAgent.id}`).click();
await expect(page.getByTestId("agent-archived-callout")).toBeVisible();
await expect(page.getByRole("button", { name: "Unarchive", exact: true })).toBeVisible();
await expect(
page.getByTestId("agent-unarchiving-callout").filter({ visible: true }),
).toHaveCount(0);
await page.getByTestId(`workspace-tab-agent_${agents[0].id}`).first().click();
await expect(
page.getByTestId("agent-unarchiving-callout").filter({ visible: true }),
).toHaveCount(1);
await page.evaluate(() => {
const win = window as unknown as Record<string, unknown>;
let sawAgentLoading = false;
let running = true;
const isVisible = (el: Element | null) => {
if (!el || !(el instanceof HTMLElement)) return false;
const rect = el.getBoundingClientRect();
if (rect.width === 0 || rect.height === 0) return false;
const style = getComputedStyle(el);
return style.display !== "none" && style.visibility !== "hidden" && style.opacity !== "0";
};
const tick = () => {
if (!running) return;
if (
Array.from(document.querySelectorAll('[data-testid="agent-loading"]')).some(isVisible)
) {
sawAgentLoading = true;
}
requestAnimationFrame(tick);
};
win.__stopMidUndoLoadingCheck = () => {
running = false;
return sawAgentLoading;
};
requestAnimationFrame(tick);
});
teardown.release();
await expectHostWorkspaceSettledActive(client, worktree.workspaceId);
await expect(page.getByRole("textbox", { name: "Message agent..." })).toBeEditable({
timeout: 30_000,
});
const sawMidUndoLoading = await page.evaluate(() => {
const win = window as unknown as { __stopMidUndoLoadingCheck?: () => boolean };
return win.__stopMidUndoLoadingCheck?.();
});
expect(sawMidUndoLoading).toBe(false);
await expect
.poll(() => getWorkspaceTabTestIds(page))
.toEqual([...tabsBefore, `workspace-tab-agent_${preArchivedAgent.id}`]);
await expect.poll(() => getWorkspaceTabTestIds(page)).toEqual(tabsBefore);
} finally {
teardown.release();
await seedClient.close().catch(() => undefined);
@@ -481,318 +357,4 @@ test.describe("Workspace archive undo", () => {
await expect(undoButton(page)).toHaveCount(0);
await expect(workspaceRow(page, worktree.workspaceId)).toBeVisible();
});
test("unarchiving a workspace with archived agents skips archived-callout and loading flashes", async ({
page,
}) => {
const seedClient = await connectSeedClient();
const project = await openProjectViaDaemon(client, tempRepo.path);
try {
const agent1 = await createMockIdleAgent(seedClient, {
cwd: project.workspaceDirectory,
workspaceId: project.workspaceId,
title: "Atomic restore agent 1",
});
const agent2 = await createMockIdleAgent(seedClient, {
cwd: project.workspaceDirectory,
workspaceId: project.workspaceId,
title: "Atomic restore agent 2",
});
// Seed 25 turns so the archived conversation spans multiple timeline pages (hasOlder=true).
for (let i = 0; i < 25; i += 1) {
await seedClient.sendAgentMessage(
agent1.id,
`atomic-restore-turn-${i}: emit 1 coalesced agent stream updates`,
);
await seedClient.waitForFinish(agent1.id, 15_000);
}
await archiveLocalWorkspaceFromDaemon(client, project.workspaceId);
await expect.poll(() => fetchAgentArchivedAt(seedClient, agent1.id)).not.toBeNull();
await expect.poll(() => fetchAgentArchivedAt(seedClient, agent2.id)).not.toBeNull();
await gotoAppShell(page);
// Clear persisted replica IndexedDB so this tests a true cold restore.
await clearIndexedDbDatabases(page);
await page.reload();
await waitForSidebarHydration(page);
await openSessions(page);
await page.getByTestId(`agent-row-${getServerId()}-${agent1.id}`).click();
await expect(page.getByTestId("workspace-recovery-action")).toHaveText("Unarchive", {
timeout: 30_000,
});
// Verify the compact left sidebar overlays the recovery gate rather than painting behind it.
const desktopViewport = page.viewportSize() ?? { width: 1280, height: 720 };
await page.setViewportSize({ width: 390, height: 720 });
await page.getByRole("button", { name: "Open menu", exact: true }).first().click();
const sidebarFooter = page.getByTestId("sidebar-footer").first();
await expect(sidebarFooter).toBeVisible();
await expect.poll(() => isSidebarFooterHitTestable(page)).toBe(true);
await page.setViewportSize(desktopViewport);
await expect(page.getByTestId("workspace-recovery-action")).toBeVisible();
await page.evaluate(() => {
const win = window as unknown as Record<string, unknown>;
const recoveryButton = document.querySelector('[data-testid="workspace-recovery-action"]');
const seen = {
archivedCallout: false,
agentLoading: false,
agentInitialFill: false,
updatingToast: false,
recoveryButtonRemounted: false,
firstRevealedTabsCount: -1,
firstRevealedRowCount: -1,
firstRevealedStreamOpacity: -1,
firstRevealedDistanceFromBottom: -1,
};
let running = true;
const isVisible = (el: Element | null) => {
if (!el || !(el instanceof HTMLElement)) return false;
const rect = el.getBoundingClientRect();
if (rect.width === 0 || rect.height === 0) return false;
const style = getComputedStyle(el);
return style.display !== "none" && style.visibility !== "hidden" && style.opacity !== "0";
};
const tick = () => {
if (!running) return;
const currentRecoveryButton = document.querySelector(
'[data-testid="workspace-recovery-action"]',
);
if (currentRecoveryButton && recoveryButton && currentRecoveryButton !== recoveryButton) {
seen.recoveryButtonRemounted = true;
}
if (
Array.from(document.querySelectorAll('[data-testid="agent-archived-callout"]')).some(
isVisible,
)
) {
seen.archivedCallout = true;
}
if (
Array.from(document.querySelectorAll('[data-testid="agent-loading"]')).some(isVisible)
) {
seen.agentLoading = true;
}
if (
Array.from(document.querySelectorAll('[data-testid="agent-initial-fill"]')).some(
isVisible,
)
) {
seen.agentInitialFill = true;
}
if (
Array.from(document.querySelectorAll('[data-testid="agent-updating-toast"]')).some(
isVisible,
)
) {
seen.updatingToast = true;
}
const composerVisible = Array.from(
document.querySelectorAll(
'textarea[aria-label="Message agent..."], [role="textbox"][aria-label="Message agent..."]',
),
).some(isVisible);
if (seen.firstRevealedTabsCount === -1 && composerVisible) {
seen.firstRevealedTabsCount = Array.from(
document.querySelectorAll('[data-testid^="workspace-tab-"]'),
).filter(isVisible).length;
const stream =
Array.from(document.querySelectorAll('[data-testid="agent-chat-scroll"]')).find(
isVisible,
) ?? null;
if (stream instanceof HTMLElement) {
seen.firstRevealedRowCount = stream.querySelectorAll("[data-history-row-id]").length;
seen.firstRevealedStreamOpacity = Number.parseFloat(
getComputedStyle(stream).opacity || "1",
);
seen.firstRevealedDistanceFromBottom = Math.max(
0,
Math.round(stream.scrollHeight - stream.scrollTop - stream.clientHeight),
);
}
}
requestAnimationFrame(tick);
};
win.__stopUnarchiveFlashCheck = () => {
running = false;
return seen;
};
requestAnimationFrame(tick);
});
await page.getByTestId("workspace-recovery-action").click();
await expect(page.getByRole("textbox", { name: "Message agent..." })).toBeEditable({
timeout: 30_000,
});
await expect(
page.getByText("atomic-restore-turn-24", { exact: false }).first(),
).toBeVisible();
const seen = await page.evaluate(() => {
const win = window as unknown as {
__stopUnarchiveFlashCheck?: () => {
archivedCallout: boolean;
agentLoading: boolean;
agentInitialFill: boolean;
updatingToast: boolean;
recoveryButtonRemounted: boolean;
firstRevealedTabsCount: number;
firstRevealedRowCount: number;
firstRevealedStreamOpacity: number;
firstRevealedDistanceFromBottom: number;
};
};
return win.__stopUnarchiveFlashCheck?.();
});
expect(seen).toBeDefined();
expect({
archivedCallout: seen?.archivedCallout,
agentLoading: seen?.agentLoading,
agentInitialFill: seen?.agentInitialFill,
updatingToast: seen?.updatingToast,
recoveryButtonRemounted: seen?.recoveryButtonRemounted,
firstRevealedTabsCount: seen?.firstRevealedTabsCount,
firstRevealedStreamOpacity: seen?.firstRevealedStreamOpacity,
}).toEqual({
archivedCallout: false,
agentLoading: false,
agentInitialFill: false,
updatingToast: false,
recoveryButtonRemounted: false,
firstRevealedTabsCount: 2,
firstRevealedStreamOpacity: 1,
});
expect(seen!.firstRevealedRowCount).toBeGreaterThan(0);
expect(seen!.firstRevealedDistanceFromBottom).toBeLessThanOrEqual(16);
} finally {
await client.removeProject(project.projectKey).catch(() => undefined);
await seedClient.close().catch(() => undefined);
}
});
test("unarchiving a single archived agent keeps the chat mounted without a loading flash", async ({
page,
}) => {
const seedClient = await connectSeedClient();
const project = await openProjectViaDaemon(client, tempRepo.path);
try {
const agent1 = await createMockIdleAgent(seedClient, {
cwd: project.workspaceDirectory,
workspaceId: project.workspaceId,
title: "Single unarchive agent",
});
await createMockIdleAgent(seedClient, {
cwd: project.workspaceDirectory,
workspaceId: project.workspaceId,
title: "Sibling active agent",
});
for (let i = 0; i < 6; i += 1) {
await seedClient.sendAgentMessage(
agent1.id,
`single-unarchive-turn-${i}: emit 1 coalesced agent stream updates`,
);
await seedClient.waitForFinish(agent1.id, 15_000);
}
await seedClient.archiveAgent(agent1.id);
await expect.poll(() => fetchAgentArchivedAt(seedClient, agent1.id)).not.toBeNull();
// Delay `refresh_agent_request` briefly so the UI renders its busy state on the Unarchive button.
await delayRefreshAgentRequests(page, 250);
await gotoAppShell(page);
await waitForSidebarHydration(page);
await openSessions(page);
await page.getByTestId(`agent-row-${getServerId()}-${agent1.id}`).click();
const unarchiveBtn = page.getByRole("button", { name: "Unarchive", exact: true });
await expect(unarchiveBtn).toBeVisible({ timeout: 30_000 });
await expect(
page.getByText("single-unarchive-turn-5", { exact: false }).first(),
).toBeVisible();
const idleCalloutBox = await page.getByTestId("agent-archived-callout").boundingBox();
if (!idleCalloutBox) throw new Error("Archived callout is not laid out");
await page.evaluate(() => {
const win = window as unknown as Record<string, unknown>;
const state = {
sawAgentLoading: false,
sawUnarchivingCallout: false,
unarchivingCalloutHeights: [] as number[],
minRowCount: Number.POSITIVE_INFINITY,
minStreamOpacity: Number.POSITIVE_INFINITY,
};
let running = true;
const isVisible = (el: Element | null) => {
if (!el || !(el instanceof HTMLElement)) return false;
const rect = el.getBoundingClientRect();
if (rect.width === 0 || rect.height === 0) return false;
const style = getComputedStyle(el);
return style.display !== "none" && style.visibility !== "hidden" && style.opacity !== "0";
};
const tick = () => {
if (!running) return;
if (
Array.from(document.querySelectorAll('[data-testid="agent-loading"]')).some(isVisible)
) {
state.sawAgentLoading = true;
}
const stream =
Array.from(document.querySelectorAll('[data-testid="agent-chat-scroll"]')).find(
isVisible,
) ?? null;
if (stream instanceof HTMLElement) {
const rowCount = stream.querySelectorAll("[data-history-row-id]").length;
const opacity = Number.parseFloat(getComputedStyle(stream).opacity || "1");
state.minRowCount = Math.min(state.minRowCount, rowCount);
state.minStreamOpacity = Math.min(state.minStreamOpacity, opacity);
} else {
state.minRowCount = 0;
state.minStreamOpacity = 0;
}
const unarchivingCallout = Array.from(
document.querySelectorAll('[data-testid="agent-unarchiving-callout"]'),
).find(isVisible);
if (unarchivingCallout instanceof HTMLElement) {
state.sawUnarchivingCallout = true;
state.unarchivingCalloutHeights.push(
Math.round(unarchivingCallout.getBoundingClientRect().height),
);
}
requestAnimationFrame(tick);
};
win.__stopSingleUnarchiveCheck = () => {
running = false;
return state;
};
requestAnimationFrame(tick);
});
await unarchiveBtn.click();
await expect(page.getByRole("textbox", { name: "Message agent..." })).toBeEditable({
timeout: 30_000,
});
const result = await page.evaluate(() => {
const win = window as unknown as {
__stopSingleUnarchiveCheck?: () => {
sawAgentLoading: boolean;
sawUnarchivingCallout: boolean;
unarchivingCalloutHeights: number[];
minRowCount: number;
minStreamOpacity: number;
};
};
return win.__stopSingleUnarchiveCheck?.();
});
expect(result?.sawAgentLoading).toBe(false);
expect(result?.sawUnarchivingCallout).toBe(true);
expect(result?.minRowCount).toBeGreaterThan(0);
expect(result?.minStreamOpacity).toBe(1);
for (const height of result?.unarchivingCalloutHeights ?? []) {
expect(Math.abs(height - Math.round(idleCalloutBox.height))).toBeLessThanOrEqual(1);
}
} finally {
await client.removeProject(project.projectKey).catch(() => undefined);
await seedClient.close().catch(() => undefined);
}
});
});
@@ -38,6 +38,9 @@ fill "id=\"direct-password-input\"" "${PASSWORD}"
wait stable
press "id=\"direct-host-submit\""
wait stable
open "${APP_ID}" "paseo://settings/hosts"
wait "id=\"client-hosts-card\"" 15000
open "${APP_ID}" "paseo://settings"
wait "label=\"Connections\"" 10000
press "label=\"Connections\""
wait stable
wait "id=\"host-page-connections-card\"" 30000
screenshot "${OUT}/16-settings-connected.png"
@@ -768,44 +768,6 @@ export async function selectModelRow(
await modelRow(page, input).click();
}
/**
* Opens a provider on a slow machine and clicks a model row before the list has
* finished laying out, holding the button as long as a person does.
*/
export async function clickModelRowWhileProviderOpens(
page: Page,
input: { provider: string; modelLabel: string },
): Promise<void> {
const viewport = pickerViewport(page);
await drillIntoProvider(page, input.provider);
const rowBox = await viewport.getByText(input.modelLabel, { exact: true }).boundingBox();
if (!rowBox) throw new Error(`Model row ${input.modelLabel} has no box`);
await viewport.getByRole("button", { name: "Back", exact: true }).click();
const cdp = await page.context().newCDPSession(page);
await cdp.send("Emulation.setCPUThrottlingRate", { rate: 10 });
try {
await drillIntoProvider(page, input.provider);
await page.mouse.click(rowBox.x + rowBox.width / 2, rowBox.y + rowBox.height / 2, {
delay: 150,
});
} finally {
await cdp.send("Emulation.setCPUThrottlingRate", { rate: 1 });
await cdp.detach();
}
}
/** Scrolling a provider's model list with the wheel leaves typing and Enter in the search field. */
export async function expectModelListScrollKeepsSearchFocused(page: Page): Promise<void> {
const search = pickerViewport(page).getByTestId("model-search-input");
const list = pickerViewport(page).getByTestId("compact-model-list");
await expect(search).toBeFocused();
await list.hover();
await page.mouse.wheel(0, 200);
await expect.poll(() => list.evaluate((element) => element.scrollTop)).toBeGreaterThan(0);
await expect(search).toBeFocused();
}
// ─── Cross-provider model search ───────────────────────────────────────────
export async function searchAllModels(page: Page, query: string): Promise<void> {
@@ -134,13 +134,9 @@ export async function openAgentSkillsSettings(
host: "127.0.0.1",
port: sandbox.daemon.port,
});
if (options.compact) {
// Adding a host opens its client host detail page; back once goes to Hosts, back again returns to the Settings root.
await goBackInSettings(page);
await goBackInSettings(page);
}
if (options.compact) await goBackInSettings(page);
await selectSettingsHost(page, sandbox.daemon.serverId);
await openHostSection(page, sandbox.daemon.serverId, "tools");
await openHostSection(page, sandbox.daemon.serverId, "agents");
await expect(page.getByTestId("host-agent-skills-card")).toBeVisible();
}
@@ -16,7 +16,7 @@ export async function openDaemonOverview(page: Page, daemon: IsolatedHostDaemon)
await page.reload();
await openSettings(page);
await openSettingsHost(page, daemon.serverId);
await openHostSection(page, daemon.serverId, "daemon");
await openHostSection(page, daemon.serverId, "host");
}
export async function restartDaemonInSettings(
+3 -2
View File
@@ -2,7 +2,7 @@ import { expect, type Page } from "@playwright/test";
import { identityForeground, type IdentityColorName } from "@/styles/identity-colors";
import { openSettings } from "./app";
import { buildSeededHost } from "./daemon-registry";
import { clickSettingsBackToWorkspace, openClientHostSettings } from "./settings";
import { clickSettingsBackToWorkspace, openHostSection, selectSettingsHost } from "./settings";
const REGISTRY_KEY = "@paseo:daemon-registry";
const SEED_NONCE_KEY = "@paseo:e2e-seed-nonce";
@@ -170,7 +170,8 @@ export async function selectAllHostsFilter(page: Page): Promise<void> {
export async function openHostAppearanceSettings(page: Page, serverId: string): Promise<void> {
await openSettings(page);
await openClientHostSettings(page, serverId);
await selectSettingsHost(page, serverId);
await openHostSection(page, serverId, "host");
await expect(page.getByTestId("host-appearance-preview")).toBeVisible({ timeout: 15_000 });
}
+18 -119
View File
@@ -108,7 +108,6 @@ export async function enableTailscale(page: Page): Promise<void> {
await expect(toggle).not.toBeChecked();
await toggle.click();
await expect(toggle).toBeChecked();
await expect(toggle).toBeEnabled();
}
export async function expectTailscaleAddress(page: Page, address: string): Promise<void> {
@@ -143,7 +142,6 @@ export async function disableTailscale(page: Page, address: string): Promise<voi
await expect(toggle).toBeEnabled();
await toggle.click();
await expect(toggle).not.toBeChecked();
await expect(toggle).toBeEnabled();
await expect(tailscaleAddressRow(page, address)).toHaveCount(0);
await expectHostUnreachableAt(address);
}
@@ -309,8 +307,7 @@ export async function expectTailscaleRowLoadsOn(
/**
* Holds every message between the app and the host on `port` for `ms` in each direction, as on a
* slow network. The returned function brings the connection back to full speed and flushes any
* queued messages.
* slow network. The returned function brings the connection back to full speed.
*/
export async function slowConnectionToHost(
page: Page,
@@ -318,29 +315,30 @@ export async function slowConnectionToHost(
ms: number,
): Promise<() => void> {
let delay = ms;
const flushers = new Set<() => void>();
await page.routeWebSocket(wsRoutePatternForPort(String(port)), (app) => {
const host = app.connectToServer();
const appToHost = deliverInOrderAfter(
() => delay,
(message) => host.send(message),
app.onMessage(
deliverInOrderAfter(
() => delay,
(message) => host.send(message),
),
);
const hostToApp = deliverInOrderAfter(
() => delay,
(message) => app.send(message),
host.onMessage(
deliverInOrderAfter(
() => delay,
(message) => app.send(message),
),
);
flushers.add(appToHost.flushNow);
flushers.add(hostToApp.flushNow);
app.onMessage(appToHost.enqueue);
host.onMessage(hostToApp.enqueue);
});
return () => {
delay = 0;
for (const flushNow of flushers) flushNow();
};
}
function deliverInOrderAfter(delay: () => number, deliver: (message: string | Buffer) => void) {
function deliverInOrderAfter(
delay: () => number,
deliver: (message: string | Buffer) => void,
): (message: string | Buffer) => void {
const queue: { at: number; message: string | Buffer }[] = [];
let timer: ReturnType<typeof setTimeout> | null = null;
const flush = () => {
@@ -348,26 +346,9 @@ function deliverInOrderAfter(delay: () => number, deliver: (message: string | Bu
while (queue[0] && queue[0].at <= Date.now()) deliver(queue.shift()!.message);
if (queue[0]) timer = setTimeout(flush, queue[0].at - Date.now());
};
return {
enqueue: (message: string | Buffer) => {
queue.push({ at: Math.max(Date.now() + delay(), queue.at(-1)?.at ?? 0), message });
if (!timer) flush();
},
flushNow: () => {
if (timer) {
clearTimeout(timer);
timer = null;
}
while (queue[0]) {
const next = queue.shift()!;
try {
deliver(next.message);
} catch {
queue.length = 0;
break;
}
}
},
return (message) => {
queue.push({ at: Math.max(Date.now() + delay(), queue.at(-1)?.at ?? 0), message });
if (!timer) flush();
};
}
@@ -377,88 +358,6 @@ export async function expectTailscaleUpdateRequired(page: Page): Promise<void> {
await expect(page.getByRole("link", { name: "How to update", exact: true })).toBeVisible();
}
export async function expectTailscaleUnavailable(page: Page): Promise<void> {
await expect(page.getByRole("switch", { name: "Tailscale", exact: true })).toBeDisabled();
await expect(
page.getByText("Tailscale is not running on this host", { exact: true }),
).toBeVisible();
await expect(page.getByRole("link", { name: "Get Tailscale", exact: true })).toBeVisible();
await expect(page.getByRole("button", { name: "Refresh", exact: true })).toBeEnabled();
}
export async function refreshTailscaleAvailability(page: Page): Promise<void> {
await page.getByRole("button", { name: "Refresh", exact: true }).click();
}
export async function expectTailscaleAvailable(
page: Page,
options?: { timeout?: number },
): Promise<void> {
await expect(page.getByRole("button", { name: "Refresh", exact: true })).toHaveCount(0, options);
const toggle = page.getByRole("switch", { name: "Tailscale", exact: true });
await expect(toggle).toBeEnabled(options);
await expect(toggle).not.toBeChecked(options);
await expect(
page.getByText("Direct over your tailnet, enter an address", { exact: true }),
).toBeVisible(options);
}
/**
* Tracks `daemon.get_status` frames on the host socket so Refresh tests can align right after a
* 2-second poll and verify the button click itself sent a fresh status request.
*/
export function observeDaemonStatusPolling(page: Page, port: number) {
let lastResponseAt = 0;
let waitingForResponse: (() => void) | null = null;
let waitingForRequest: (() => void) | null = null;
page.on("websocket", (socket) => {
if (!socket.url().includes(`:${port}`)) return;
socket.on("framesent", ({ payload }) => {
const message = typeof payload === "string" ? payload : payload.toString();
if (message.includes('"type":"daemon.get_status.request"')) {
waitingForRequest?.();
waitingForRequest = null;
}
});
socket.on("framereceived", ({ payload }) => {
const message = typeof payload === "string" ? payload : payload.toString();
if (message.includes('"type":"daemon.get_status.response"')) {
lastResponseAt = Date.now();
waitingForResponse?.();
waitingForResponse = null;
}
});
});
return {
async waitForFreshPollWindow(): Promise<void> {
if (Date.now() - lastResponseAt < 250) return;
await new Promise<void>((resolve, reject) => {
const timer = setTimeout(() => {
waitingForResponse = null;
reject(new Error("Timed out waiting for daemon status poll"));
}, 5_000);
waitingForResponse = () => {
clearTimeout(timer);
resolve();
};
});
},
waitForStatusRequest(timeoutMs = 1_000): Promise<void> {
return new Promise<void>((resolve, reject) => {
const timer = setTimeout(() => {
waitingForRequest = null;
reject(new Error("Refresh did not send daemon.get_status.request"));
}, timeoutMs);
waitingForRequest = () => {
clearTimeout(timer);
resolve();
};
});
},
};
}
export async function openPairDeviceModal(page: Page): Promise<void> {
await page.getByRole("button", { name: "Relay", exact: true }).click();
await expect(page.getByTestId("devices-relay-pairing")).toBeVisible();
+44 -40
View File
@@ -3,7 +3,6 @@ import { buildCreateAgentPreferences, buildSeededHost, TEST_HOST_LABEL } from ".
import { getServerId } from "./server-id";
import { expectAppRoute } from "./route-assertions";
import {
buildClientHostSettingsRoute,
buildSettingsHostSectionRoute,
buildSettingsRoute,
buildSettingsSectionRoute,
@@ -48,29 +47,35 @@ interface SavedSettingsHostInput {
const SECTION_LABELS = {
general: "General",
hosts: "Hosts",
chat: "Chat",
appearance: "Appearance",
sidebar: "Sidebar",
chat: "Chat & panes",
editor: "Editor",
files: "Files",
terminal: "Terminal",
browser: "Browser",
shortcuts: "Shortcuts",
notifications: "Notifications",
integrations: "Integrations",
permissions: "Permissions",
diagnostics: "Diagnostics",
about: "About",
} as const;
export type SettingsSection = keyof typeof SECTION_LABELS;
type HostSection =
| "providers"
| "agent-profiles"
| "tools"
| "projects"
| "workspaces"
| "connections"
| "devices"
| "agents"
| "metadata"
| "voice"
| "workspaces"
| "providers"
| "usage"
| "terminals"
| "plugins"
| "devices"
| "daemon";
| "host";
export async function openSettingsSection(page: Page, section: SettingsSection): Promise<void> {
const sidebar = page.getByTestId("settings-sidebar");
@@ -193,17 +198,12 @@ export async function expectSettingsDetailScrollOffset(page: Page, offset: numbe
await expect.poll(() => scrollBody.evaluate((node) => node.scrollTop)).toBe(offset);
}
export async function openClientHostSettings(page: Page, serverId: string): Promise<void> {
await openSettingsSection(page, "hosts");
await page.getByTestId(`client-host-row-${serverId}`).click();
await expectAppRoute(page, buildClientHostSettingsRoute(serverId));
await expect(page.getByTestId("host-page-connections-card")).toBeVisible();
}
export async function openSettingsHost(page: Page, serverId: string): Promise<void> {
await page.getByTestId("settings-host-section-daemon").click();
// Host sections are now flat top-level rows under the Host group. Navigate by
// clicking the Connections section row; the picker only matters when >1 host.
await page.getByTestId("settings-host-section-connections").click();
await expectHostSettingsUrl(page, serverId);
await expect(page.getByTestId("host-page-identity")).toBeVisible();
await expect(page.getByTestId("host-page-connections-card")).toBeVisible();
}
export async function openSettingsHostSection(
@@ -367,7 +367,7 @@ export async function removeCurrentHostFromSettings(page: Page): Promise<void> {
await page.getByTestId("host-page-remove-host-button").click();
await expect(page.getByTestId("remove-host-confirm-modal")).toBeVisible();
await page.getByTestId("remove-host-confirm").click();
await expectAppRoute(page, buildSettingsSectionRoute("hosts"));
await expectAppRoute(page, buildSettingsRoute());
}
export async function expectSettingsBackButton(page: Page): Promise<void> {
@@ -379,7 +379,7 @@ export async function clickSettingsBackToWorkspace(page: Page): Promise<void> {
}
export async function expectHostSettingsUrl(page: Page, serverId: string): Promise<void> {
await expectAppRoute(page, buildSettingsHostSectionRoute(serverId, "daemon"));
await expectAppRoute(page, buildSettingsHostSectionRoute(serverId, "connections"));
}
export async function verifyLegacyHostSettingsRedirect(page: Page): Promise<void> {
@@ -449,7 +449,7 @@ export async function expectAboutContent(page: Page): Promise<void> {
}
export async function expectGeneralContent(page: Page): Promise<void> {
await expect(page.getByText("Language", { exact: true }).first()).toBeVisible();
await expect(page.getByText("Default send", { exact: true }).first()).toBeVisible();
}
export async function expectAppearanceContent(page: Page): Promise<void> {
@@ -474,7 +474,14 @@ export async function expectHostLabelEditMode(page: Page, expectedLabel: string)
export async function expectHostConnectionsCard(page: Page, port: string): Promise<void> {
const card = page.getByTestId("host-page-connections-card");
await expect(card).toBeVisible();
await expect(card.getByText(new RegExp(`(localhost|127\\.0\\.0\\.1):${port}`))).toBeVisible();
// "Connections" appears three times on this page: the sidebar section row, the
// detail header title, and the SettingsSection heading above the card. Match
// the first to keep the heading assertion without tripping Playwright strict
// mode.
await expect(page.getByText("Connections", { exact: true }).first()).toBeVisible();
await expect(
card.getByText(new RegExp(`TCP \\((localhost|127\\.0\\.0\\.1):${port}\\)`)),
).toBeVisible();
}
export async function expectHostInjectMcpCard(page: Page): Promise<void> {
@@ -511,11 +518,11 @@ export async function openHostSection(
}
export async function expectHostActionCards(page: Page, serverId: string): Promise<void> {
// Restart lives on Daemon; removing the saved host lives on This device -> Hosts.
await openSettingsHostSection(page, serverId, "daemon");
// Restart + remove cards live on the Host section; providers moved to its
// own Providers section (asserted via expectHostProvidersCard).
await openSettingsHostSection(page, serverId, "host");
await expect(page.getByTestId("host-page-restart-card")).toBeVisible();
await expect(page.getByTestId("host-page-restart-button")).toBeVisible();
await openClientHostSettings(page, serverId);
await expect(page.getByTestId("host-page-remove-host-card")).toBeVisible();
await expect(page.getByTestId("host-page-remove-host-button")).toBeVisible();
}
@@ -634,30 +641,27 @@ export async function expectRetiredSidebarSectionsAbsent(page: Page): Promise<vo
const sidebar = page.getByTestId("settings-sidebar");
await expect(sidebar).toBeVisible();
// App group ("This device") rows remain top-level.
// App group rows remain top-level.
await expect(sidebar.getByRole("button", { name: "General", exact: true })).toBeVisible();
await expect(sidebar.getByRole("button", { name: "Hosts", exact: true })).toBeVisible();
await expect(sidebar.getByRole("button", { name: "Diagnostics", exact: true })).toBeVisible();
await expect(sidebar.getByRole("button", { name: "About", exact: true })).toBeVisible();
await expect(sidebar.getByRole("button", { name: "Diagnostics", exact: true })).toHaveCount(0);
await expect(sidebar.getByRole("button", { name: "Daemon", exact: true })).toHaveCount(0);
// Host group rows are daemon-scoped flat top-level sections.
await expect(sidebar.getByTestId("settings-host-section-providers")).toBeVisible();
await expect(sidebar.getByTestId("settings-host-section-agent-profiles")).toBeVisible();
await expect(sidebar.getByTestId("settings-host-section-tools")).toBeVisible();
// Host group rows are now flat top-level sections (no drill-in).
await expect(sidebar.getByTestId("settings-host-section-connections")).toBeVisible();
await expect(sidebar.getByTestId("settings-host-section-projects")).toBeVisible();
await expect(sidebar.getByTestId("settings-host-section-agents")).toBeVisible();
await expect(sidebar.getByTestId("settings-host-section-workspaces")).toBeVisible();
await expect(sidebar.getByTestId("settings-host-section-providers")).toBeVisible();
await expect(sidebar.getByTestId("settings-host-section-usage")).toBeVisible();
await expect(sidebar.getByTestId("settings-host-section-daemon")).toBeVisible();
await expect(sidebar.getByTestId("settings-host-section-host")).toBeVisible();
// Retired host rows and old per-host entry rows are absent.
await expect(sidebar.getByTestId("settings-host-section-connections")).toHaveCount(0);
await expect(sidebar.getByTestId("settings-host-section-agents")).toHaveCount(0);
await expect(sidebar.getByTestId("settings-host-section-metadata")).toHaveCount(0);
// The old per-host entry rows are replaced by the host picker.
await expect(sidebar.locator('[data-testid^="settings-host-entry-"]')).toHaveCount(0);
}
export async function expectHostPageVisible(page: Page, _serverId: string): Promise<void> {
await expect(page.getByTestId("host-page-identity")).toBeVisible();
await expect(page.getByTestId("host-page-connections-card")).toBeVisible();
}
export async function expectLocalHostEntryFirst(page: Page, _serverId: string): Promise<void> {
@@ -693,7 +697,7 @@ export async function expectNoHostPasswordControls(page: Page): Promise<void> {
export async function removeHostFromHostPage(page: Page, serverId: string): Promise<void> {
await page.getByTestId("host-page-remove-host-button").click();
await page.getByTestId("remove-host-confirm").click();
await expect(page).not.toHaveURL(new RegExp(`/settings/(hosts|device-hosts)/${serverId}`));
await expect(page).not.toHaveURL(new RegExp(`/settings/hosts/${serverId}`));
}
export async function expectHostOnlineWithoutError(page: Page): Promise<void> {
@@ -4,18 +4,13 @@ import { z } from "zod";
import { killProcessTree, spawnTsx } from "./spawn-node";
const readySchema = z.object({ port: z.number(), serverId: z.string() });
const ackSchema = z.object({ type: z.literal("tailscale-available-set"), available: z.boolean() });
export async function startTailscaleTestDaemon(
origin: string,
options?: { initialAvailable?: boolean },
) {
export async function startTailscaleTestDaemon(origin: string) {
const entrypoint = path.resolve(
__dirname,
"../../../../server/src/server/test-utils/tailscale-daemon.ts",
);
const initialMode = options?.initialAvailable === false ? "unavailable" : "available";
const child = spawnTsx(entrypoint, [origin, initialMode], {
const child = spawnTsx(entrypoint, [origin], {
stdio: ["ignore", "inherit", "inherit", "ipc"],
});
const signal = AbortSignal.timeout(30_000);
@@ -29,16 +24,6 @@ export async function startTailscaleTestDaemon(
return {
...ready,
tailscaleAddress: `127.0.0.2:${ready.port}`,
async setTailscaleAvailable(available: boolean): Promise<void> {
const ack = once(child, "message", { signal: AbortSignal.timeout(10_000) }).then(
([message]) => ackSchema.parse(message),
);
child.send({ type: "set-tailscale-available", available });
const result = await ack;
if (result.available !== available) {
throw new Error(`Expected tailscaleAvailable=${String(available)}`);
}
},
close: () => killProcessTree(child),
};
} catch (error) {
+2 -2
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/app",
"version": "0.17.6",
"version": "0.17.4",
"private": true,
"main": "index.ts",
"scripts": {
@@ -40,7 +40,7 @@
"dev:ios": "npm --prefix ../.. run build:client && cross-env APP_VARIANT=development expo run:ios",
"build:apk": "npm --prefix ../.. run build:apk",
"build:apk:arm64": "npm --prefix ../.. run build:apk:arm64",
"test:android": "expo prebuild --platform android --no-install && cd android && ./gradlew :paseo-native-trace:testReleaseUnitTest :paseo-hardware-keyboard:testReleaseUnitTest :react-native-enriched-markdown:testReleaseUnitTest --tests '*InlineCodeFormattingTest' --tests '*ListRenderingTest' --tests '*TaskListInteractionTest' --tests '*ListBlockquoteMeasurementTest' --tests '*BlockquoteCopyTest' --tests '*CodeBlockCopyButtonConstructionTest' --tests '*LongPressSelectionInterceptTest' --no-daemon --max-workers=2 -Dorg.gradle.parallel=false"
"test:android": "expo prebuild --platform android --no-install && cd android && ./gradlew :paseo-native-trace:testReleaseUnitTest :paseo-hardware-keyboard:testReleaseUnitTest :react-native-enriched-markdown:testReleaseUnitTest --tests '*InlineCodeFormattingTest' --tests '*ListRenderingTest' --tests '*TaskListInteractionTest' --tests '*ListBlockquoteMeasurementTest' --tests '*BlockquoteCopyTest' --tests '*LongPressSelectionInterceptTest' --no-daemon --max-workers=2 -Dorg.gradle.parallel=false"
},
"dependencies": {
"@codemirror/commands": "6.10.4",
@@ -230,22 +230,19 @@ function NativeStreamViewport(props: StreamRenderInput & { strategy: StreamStrat
const hasMeasuredViewport =
metrics.viewportMeasuredForKey === metrics.containerKey &&
metrics.contentMeasuredForKey === metrics.containerKey;
const geometry = nativeHistoryStartGeometry({
contentHeight: metrics.contentHeight,
viewportHeight: metrics.viewportHeight,
offsetY: metrics.offsetY,
topOverlayInset,
});
return {
...geometry,
...nativeHistoryStartGeometry({
contentHeight: metrics.contentHeight,
viewportHeight: metrics.viewportHeight,
offsetY: metrics.offsetY,
topOverlayInset,
}),
hasOlderHistory,
isLoadingOlderHistory,
// Reveal an already-filled measured viewport immediately; keep waiting on
// rAF before auto-fetching older pages on underfilled views.
isReady:
isActive &&
isAuthoritativeHistoryReady &&
(historyStartReadyRef.current || !geometry.isUnderfilled) &&
historyStartReadyRef.current &&
hasMeasuredViewport,
progressKey: olderHistoryProgressKey,
};
@@ -503,21 +503,18 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
}
const bottomAnchorSettled =
!followOutputRef.current || isScrollContainerNearBottom(scrollContainer);
const isUnderfilled =
(rowsHostRef.current?.getBoundingClientRect().height ?? 0) +
(auxiliaryRef.current?.getBoundingClientRect().height ?? 0) <
scrollContainer.clientHeight;
return {
distanceFromHistoryStart: scrollContainer.scrollTop,
isUnderfilled,
isUnderfilled:
(rowsHostRef.current?.getBoundingClientRect().height ?? 0) +
(auxiliaryRef.current?.getBoundingClientRect().height ?? 0) <
scrollContainer.clientHeight,
hasOlderHistory,
isLoadingOlderHistory,
// An explicit jump owns the landing position. Revealing another local
// page here changes the virtual index before the target has mounted.
// Reveal an already-filled viewport during initial layout before paint;
// still wait for rAF before auto-fetching older pages on underfilled views.
isReady:
(historyStartReadyRef.current || !isUnderfilled) &&
historyStartReadyRef.current &&
isAuthoritativeHistoryReady &&
bottomAnchorSettled &&
!isJumpSettling(),
-2
View File
@@ -925,14 +925,12 @@ function RootStack() {
<Stack.Screen name="welcome" />
<Stack.Screen name="settings/index" />
<Stack.Screen name="settings/[section]" />
<Stack.Screen name="settings/hosts/index" />
<Stack.Screen name="new" />
<Stack.Screen name="open-project" />
<Stack.Screen name="sessions" />
<Stack.Screen name="schedules" />
</Stack.Protected>
<Stack.Screen name="h/[serverId]" />
<Stack.Screen name="settings/device-hosts/[serverId]" />
<Stack.Screen name="settings/hosts/[serverId]/index" />
<Stack.Screen name="settings/hosts/[serverId]/[hostSection]" />
<Stack.Screen name="settings/hosts/[serverId]/plugins/[pluginId]/index" />
+2 -9
View File
@@ -9,9 +9,7 @@ import { StartupSplashScreen } from "@/screens/startup-splash-screen";
import {
buildSettingsHostSectionRoute,
buildSettingsRoute,
buildSettingsSectionRoute,
isSettingsSectionSlug,
normalizeSettingsSectionSlug,
type SettingsSectionSlug,
} from "@/utils/host-routes";
@@ -30,7 +28,7 @@ function SettingsDaemonRedirect() {
localDaemon.serverId !== null &&
hosts.some((host) => host.serverId === localDaemon.serverId)
) {
return <Redirect href={buildSettingsHostSectionRoute(localDaemon.serverId, "daemon")} />;
return <Redirect href={buildSettingsHostSectionRoute(localDaemon.serverId, "host")} />;
}
return <Redirect href={buildSettingsRoute()} />;
@@ -39,8 +37,7 @@ function SettingsDaemonRedirect() {
export default function SettingsSectionRoute() {
const params = useLocalSearchParams<{ section?: string }>();
const rawSection = typeof params.section === "string" ? params.section : "";
const normalized = normalizeSettingsSectionSlug(rawSection);
const section: SettingsSectionSlug = normalized ?? "general";
const section: SettingsSectionSlug = isSettingsSectionSlug(rawSection) ? rawSection : "general";
const view = useMemo(() => ({ kind: "section" as const, section }), [section]);
// COMPAT(settingsDaemonRedirect): added 2026-07-08, remove after 2027-01-08.
@@ -52,9 +49,5 @@ export default function SettingsSectionRoute() {
);
}
if (normalized && !isSettingsSectionSlug(rawSection)) {
return <Redirect href={buildSettingsSectionRoute(normalized)} />;
}
return <SettingsScreen view={view} />;
}
@@ -1,21 +0,0 @@
import { Redirect, useLocalSearchParams } from "expo-router";
import { useMemo } from "react";
import { HostRouteBootstrapBoundary } from "@/components/host-route-bootstrap-boundary";
import SettingsScreen from "@/screens/settings-screen";
import { buildSettingsSectionRoute } from "@/utils/host-routes";
export default function SettingsDeviceHostDetailRoute() {
const params = useLocalSearchParams<{ serverId?: string }>();
const serverId = typeof params.serverId === "string" ? params.serverId.trim() : "";
const view = useMemo(() => ({ kind: "clientHost" as const, serverId }), [serverId]);
if (!serverId) {
return <Redirect href={buildSettingsSectionRoute("hosts")} />;
}
return (
<HostRouteBootstrapBoundary>
<SettingsScreen view={view} />
</HostRouteBootstrapBoundary>
);
}
@@ -2,27 +2,17 @@ import { Redirect, useLocalSearchParams } from "expo-router";
import { useMemo } from "react";
import { HostRouteBootstrapBoundary } from "@/components/host-route-bootstrap-boundary";
import SettingsScreen from "@/screens/settings-screen";
import {
buildClientHostSettingsRoute,
buildSettingsHostSectionRoute,
isHostSectionSlug,
normalizeHostSectionSlug,
} from "@/utils/host-routes";
import { buildSettingsHostSectionRoute, normalizeHostSectionSlug } from "@/utils/host-routes";
export default function SettingsHostSectionRoute() {
const params = useLocalSearchParams<{ serverId?: string; hostSection?: string }>();
const serverId = typeof params.serverId === "string" ? params.serverId.trim() : "";
const rawSection = typeof params.hostSection === "string" ? params.hostSection : "";
const normalized = normalizeHostSectionSlug(rawSection);
const section = normalized ?? "daemon";
const section = normalizeHostSectionSlug(rawSection) ?? "connections";
const view = useMemo(() => ({ kind: "host" as const, serverId, section }), [serverId, section]);
if (rawSection === "connections" && serverId) {
return <Redirect href={buildClientHostSettingsRoute(serverId)} />;
}
if (normalized && !isHostSectionSlug(rawSection) && serverId) {
return <Redirect href={buildSettingsHostSectionRoute(serverId, normalized)} />;
if (rawSection === "pair-device" && serverId) {
return <Redirect href={buildSettingsHostSectionRoute(serverId, "devices")} />;
}
return (
@@ -9,5 +9,5 @@ export default function SettingsHostIndexRoute() {
return <Redirect href={buildSettingsRoute()} />;
}
return <Redirect href={buildSettingsHostSectionRoute(serverId, "daemon")} />;
return <Redirect href={buildSettingsHostSectionRoute(serverId, "connections")} />;
}
@@ -1,7 +0,0 @@
import SettingsScreen from "@/screens/settings-screen";
const HOSTS_VIEW = { kind: "section" as const, section: "hosts" as const };
export default function SettingsHostsSectionRoute() {
return <SettingsScreen view={HOSTS_VIEW} />;
}
@@ -26,7 +26,6 @@ import {
import { ScrollView } from "@/components/ui/scroll-view";
import { isWeb } from "@/constants/platform";
import { SafeAreaInsetsContext, useSafeAreaInsets } from "react-native-safe-area-context";
import type { EditingTextInputHandle } from "@/components/ui/text-input";
import { AdaptiveTextInput } from "@/components/adaptive-text-input";
import { useDismissibleOverlay } from "@/components/ui/overlay-dismissal";
import { DismissBackdrop } from "@/components/ui/dismiss-backdrop";
@@ -56,7 +55,6 @@ export interface SheetHeaderSearch {
resetKey?: string | number;
placeholder?: string;
autoFocus?: boolean;
inputRef?: React.RefObject<EditingTextInputHandle | null>;
testID?: string;
}
@@ -491,7 +489,6 @@ export function SheetHeaderView({
<View style={styles.searchRow}>
<Search size={theme.iconSize.md} color={theme.colors.foregroundMuted} />
<AdaptiveTextInput
ref={search.inputRef}
// @ts-expect-error - outlineStyle is web-only
style={[styles.searchInput, isWeb && { outlineStyle: "none" }]}
placeholder={search.placeholder ?? t("common.actions.search")}
@@ -533,7 +530,6 @@ export function InlineHeaderView({ header }: { header: SheetHeader }) {
<View style={styles.inlineSearchRow}>
<Search size={theme.iconSize.sm} color={theme.colors.foregroundMuted} />
<AdaptiveTextInput
ref={header.search.inputRef}
// @ts-expect-error - outlineStyle is web-only
style={[styles.searchInput, isWeb && { outlineStyle: "none" }]}
placeholder={header.search.placeholder ?? t("common.actions.search")}
@@ -1,144 +1,55 @@
import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react";
import { useCallback, useState } from "react";
import { View, Text } from "react-native";
import { useTranslation } from "react-i18next";
import { ArchiveRestore } from "lucide-react-native";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { StyleSheet } from "react-native-unistyles";
import { CHAT_COLUMN_RAIL_DATASET } from "@/chat-rail";
import { FOOTER_HEIGHT } from "@/constants/layout";
import { useToast } from "@/contexts/toast-context";
import { useUnarchiveAgent } from "@/hooks/use-unarchive-agent";
import { useHostRuntimeClient, useHostRuntimeIsConnected } from "@/runtime/host-runtime";
import { KeyboardTranslateView } from "@/keyboard/shift";
import { Button } from "@/components/ui/button";
import { CONTROL_HEIGHTS } from "@/components/ui/control-geometry";
import { LoadingSpinner } from "@/components/ui/loading-spinner";
import type { Theme } from "@/styles/theme";
import { toErrorMessage } from "@/utils/error-messages";
const ThemedLoadingSpinner = withUnistyles(LoadingSpinner);
const foregroundMutedColorMapping = (theme: Theme) => ({
color: theme.colors.foregroundMuted,
});
interface ArchivedAgentCalloutProps {
serverId: string;
agentId: string;
/** True while the owning workspace's archive undo is restoring this agent. */
isWorkspaceRestoring?: boolean;
}
export function deliverUnarchiveError(input: {
error: unknown;
attemptKey: string;
isMounted: boolean;
currentTargetKey: string;
onInlineError: (state: { targetKey: string; message: string }) => void;
onToastError: (message: string) => void;
}): void {
const message = toErrorMessage(input.error);
if (input.isMounted && input.currentTargetKey === input.attemptKey) {
input.onInlineError({ targetKey: input.attemptKey, message });
} else {
input.onToastError(message);
}
}
function ArchivedCalloutRow({
isShowingUnarchiving,
canUnarchive,
onUnarchive,
}: {
isShowingUnarchiving: boolean;
canUnarchive: boolean;
onUnarchive: () => void;
}) {
export function ArchivedAgentCallout({ serverId, agentId }: ArchivedAgentCalloutProps) {
const { t } = useTranslation();
return (
<View style={styles.calloutRow}>
{isShowingUnarchiving ? (
<>
<ThemedLoadingSpinner size={14} uniProps={foregroundMutedColorMapping} />
<Text style={styles.calloutText}>{t("agentPanel.archived.unarchiving")}</Text>
</>
) : (
<>
<Text style={styles.calloutText}>{t("agentPanel.archived.callout")}</Text>
<Button
variant="secondary"
leftIcon={ArchiveRestore}
onPress={onUnarchive}
disabled={!canUnarchive}
>
{t("agentPanel.archived.unarchive")}
</Button>
</>
)}
</View>
);
}
export function ArchivedAgentCallout({
serverId,
agentId,
isWorkspaceRestoring = false,
}: ArchivedAgentCalloutProps) {
const targetKey = `${serverId}:${agentId}`;
const toast = useToast();
const { unarchive, isUnarchiving, canUnarchive } = useUnarchiveAgent({ serverId, agentId });
const isShowingUnarchiving = isWorkspaceRestoring || isUnarchiving;
const [unarchiveErrorState, setUnarchiveErrorState] = useState<{
targetKey: string;
message: string;
} | null>(null);
const unarchiveError =
unarchiveErrorState?.targetKey === targetKey ? unarchiveErrorState.message : null;
const isMountedRef = useRef(true);
const targetKeyRef = useRef(targetKey);
useLayoutEffect(() => {
targetKeyRef.current = targetKey;
}, [targetKey]);
useEffect(() => {
isMountedRef.current = true;
return () => {
isMountedRef.current = false;
};
}, []);
const client = useHostRuntimeClient(serverId);
const isConnected = useHostRuntimeIsConnected(serverId);
const [isUnarchiving, setIsUnarchiving] = useState(false);
const [unarchiveError, setUnarchiveError] = useState<string | null>(null);
const handleUnarchive = useCallback(async () => {
if (!canUnarchive) return;
const attemptKey = targetKey;
setUnarchiveErrorState(null);
if (!client || !isConnected || isUnarchiving) return;
setIsUnarchiving(true);
setUnarchiveError(null);
try {
await unarchive();
await client.refreshAgent(agentId);
} catch (error) {
deliverUnarchiveError({
error,
attemptKey,
isMounted: isMountedRef.current,
currentTargetKey: targetKeyRef.current,
onInlineError: setUnarchiveErrorState,
onToastError: toast.error,
});
setUnarchiveError(toErrorMessage(error));
setIsUnarchiving(false);
}
}, [canUnarchive, targetKey, toast, unarchive]);
}, [client, isConnected, isUnarchiving, agentId]);
return (
<KeyboardTranslateView style={styles.container}>
<View style={styles.inputAreaContainer} dataSet={CHAT_COLUMN_RAIL_DATASET}>
<View style={styles.inputAreaContent}>
<View style={styles.calloutStack}>
<View
style={styles.callout}
testID={isShowingUnarchiving ? "agent-unarchiving-callout" : "agent-archived-callout"}
>
<ArchivedCalloutRow
isShowingUnarchiving={isShowingUnarchiving}
canUnarchive={canUnarchive}
onUnarchive={handleUnarchive}
/>
<View style={styles.callout}>
<Text style={styles.calloutText}>{t("agentPanel.archived.callout")}</Text>
<Button
variant="secondary"
onPress={handleUnarchive}
disabled={!isConnected || isUnarchiving}
>
{t("agentPanel.archived.unarchive")}
</Button>
</View>
{!isShowingUnarchiving && unarchiveError ? (
{unarchiveError ? (
<Text style={styles.errorText} testID="agent-unarchive-error">
{unarchiveError}
</Text>
@@ -169,6 +80,10 @@ const styles = StyleSheet.create((theme: Theme) => ({
maxWidth: theme.contentMaxWidth,
},
callout: {
flexDirection: "row",
alignItems: "center",
justifyContent: "center",
gap: theme.spacing[3],
backgroundColor: theme.colors.surface1,
borderWidth: theme.borderWidth[1],
borderColor: theme.colors.borderAccent,
@@ -182,18 +97,10 @@ const styles = StyleSheet.create((theme: Theme) => ({
md: theme.spacing[6],
},
},
calloutRow: {
minHeight: CONTROL_HEIGHTS.md,
flexDirection: "row",
alignItems: "center",
justifyContent: "center",
gap: theme.spacing[3],
},
calloutStack: {
gap: theme.spacing[2],
},
calloutText: {
flexShrink: 1,
color: theme.colors.foregroundMuted,
fontSize: theme.fontSize.base,
},
@@ -307,7 +307,6 @@ export function CombinedModelSelector({
desktopFixedHeight={browser.desktopFixedHeight}
desktopChildrenScrollEnabled={false}
header={browser.header}
keyboard={browser.keyboard}
mobileChildrenScrollEnabled={!browser.isProviderView || !isNative}
mobileChildrenContentContainerStyle={styles.mobileBrowserContent}
>
+1 -1
View File
@@ -227,7 +227,7 @@ export const LeftSidebar = memo(function LeftSidebar({
openSettingsFromSidebar({
workspace: activeWorkspace,
isCompact: isCompactLayout,
route: buildSettingsHostSectionRoute(serverId, "daemon"),
route: buildSettingsHostSectionRoute(serverId, "host"),
});
},
[activeWorkspace, isCompactLayout],
@@ -1,9 +0,0 @@
/** Native moves no focus to buttons from a hardware keyboard, so Enter always reaches the picker. */
export function focusedModelBrowserControlOwnsEnter(): boolean {
return false;
}
/** Native fires focus on rows only for a hardware keyboard or a TV remote. */
export function focusCameFromKeyboard(_target: unknown): boolean {
return true;
}
@@ -1,23 +0,0 @@
const ACTIVATES_ON_ENTER =
'button, a[href], [role="button"], [role="link"], [role="tab"], [role="combobox"], [role="menuitem"]';
/**
* Whether the focused element handles Enter itself (Back, Provider settings, Edit profiles,
* Close, Retry, or a model row's sibling profile action button). Navigable rows carry
* `data-model-browser-row="true"` and sync `activeKey` on focus, so Enter runs the active row
* action even after arrowing away from a Tab-focused row.
*/
export function focusedModelBrowserControlOwnsEnter(): boolean {
const active = document.activeElement;
if (!(active instanceof HTMLElement)) return false;
if (active.closest('[data-model-browser-row="true"]')) return false;
return active.matches(ACTIVATES_ON_ENTER);
}
/**
* A pointer press also focuses the row it lands on. Only keyboard focus marks a row
* active, so the press does not scroll the list to that row before the button is released.
*/
export function focusCameFromKeyboard(target: unknown): boolean {
return target instanceof Element && target.matches(":focus-visible");
}
@@ -4,19 +4,10 @@ import type {
ProviderSelectorProvider,
} from "@/provider-selection/provider-selection";
import {
MODEL_BROWSER_CREATE_PROFILE_KEY,
filterAndRankProfileRows,
groupProfilesByProviderModel,
modelBrowserModelKey,
modelBrowserProfileKey,
modelBrowserProviderKey,
moveModelBrowserActiveKey,
resolveActiveModelBrowserKey,
resolveInitialModelBrowserView,
resolveModelBrowserAllView,
resolveModelBrowserKeyCommand,
resolveModelBrowserNavItems,
resolveModelBrowserProjection,
filterAndRankProfileRows,
groupProfilesByProviderModel,
resolveModelBrowserScrolling,
} from "./model-browser-view";
@@ -292,486 +283,3 @@ describe("model browser profile search", () => {
expect(filterAndRankProfileRows(profiles, "")).toEqual(profiles);
});
});
describe("model browser keyboard navigation", () => {
const claude = provider("claude", "Claude Code", [
modelRow("claude", "Claude Code", "opus-5", "Opus 5"),
modelRow("claude", "Claude Code", "sonnet-4.6", "Sonnet 4.6"),
]);
const codex = provider("codex", "Codex", [modelRow("codex", "Codex", "gpt-5.4", "GPT-5.4")]);
const providers = [claude, codex];
const reviewer = {
id: "reviewer",
provider: "claude",
name: "Reviewer",
summary: "Claude Code · Opus 5 · Plan",
};
const quick = {
id: "quick",
provider: "codex",
name: "Quick fix",
summary: "Codex · GPT-5.4",
};
const profiles = [reviewer, quick];
it("orders profiles before providers on the root browse view", () => {
const items = resolveModelBrowserNavItems({
view: { kind: "all" },
providers,
profiles,
showProfilesSection: true,
canCreateProfileRow: true,
normalizedQuery: "",
isSearchFocused: false,
hasCustomRootBrowseContent: false,
});
expect(items.map((item) => item.key)).toEqual([
modelBrowserProfileKey("reviewer"),
modelBrowserProfileKey("quick"),
modelBrowserProviderKey("claude"),
modelBrowserProviderKey("codex"),
]);
});
it("includes Create profile before providers when profiles are empty and editable", () => {
const items = resolveModelBrowserNavItems({
view: { kind: "all" },
providers,
profiles: [],
showProfilesSection: true,
canCreateProfileRow: true,
normalizedQuery: "",
isSearchFocused: false,
hasCustomRootBrowseContent: false,
});
expect(items.map((item) => item.key)).toEqual([
MODEL_BROWSER_CREATE_PROFILE_KEY,
modelBrowserProviderKey("claude"),
modelBrowserProviderKey("codex"),
]);
});
it("omits providers when custom root browse content replaces them", () => {
const items = resolveModelBrowserNavItems({
view: { kind: "all" },
providers,
profiles,
showProfilesSection: true,
canCreateProfileRow: true,
normalizedQuery: "",
isSearchFocused: false,
hasCustomRootBrowseContent: true,
});
expect(items.map((item) => item.key)).toEqual([
modelBrowserProfileKey("reviewer"),
modelBrowserProfileKey("quick"),
]);
});
it("orders matching profiles before matching models with model indexes in search results", () => {
const items = resolveModelBrowserNavItems({
view: { kind: "all" },
providers,
profiles,
showProfilesSection: true,
canCreateProfileRow: true,
normalizedQuery: "opus",
isSearchFocused: true,
hasCustomRootBrowseContent: false,
});
expect(items).toEqual([
{ key: modelBrowserProfileKey("reviewer"), kind: "profile", profileId: "reviewer" },
{
key: modelBrowserModelKey("claude:opus-5"),
kind: "model",
provider: "claude",
modelId: "opus-5",
modelIndex: 0,
},
]);
});
it("orders provider profiles before models inside a provider view and skips loading providers", () => {
const items = resolveModelBrowserNavItems({
view: { kind: "provider", providerId: "claude", providerLabel: "Claude Code" },
providers,
profiles,
showProfilesSection: true,
canCreateProfileRow: true,
normalizedQuery: "",
isSearchFocused: false,
hasCustomRootBrowseContent: false,
});
expect(items.map((item) => item.key)).toEqual([
modelBrowserProfileKey("reviewer"),
modelBrowserModelKey("claude:opus-5"),
modelBrowserModelKey("claude:sonnet-4.6"),
]);
const loadingItems = resolveModelBrowserNavItems({
view: { kind: "provider", providerId: "pi", providerLabel: "Pi" },
providers: [{ id: "pi", label: "Pi", modelSelection: { kind: "loading" } }],
profiles: null,
showProfilesSection: false,
canCreateProfileRow: false,
normalizedQuery: "",
isSearchFocused: false,
hasCustomRootBrowseContent: false,
});
expect(loadingItems).toEqual([]);
});
it("highlights the selected model in an unfiltered provider view and resets to first match on search", () => {
const view = { kind: "provider", providerId: "claude", providerLabel: "Claude Code" } as const;
const unfilteredItems = resolveModelBrowserNavItems({
view,
providers,
profiles,
showProfilesSection: true,
canCreateProfileRow: false,
normalizedQuery: "",
isSearchFocused: false,
hasCustomRootBrowseContent: false,
});
expect(
resolveActiveModelBrowserKey({
explicitActiveKey: null,
items: unfilteredItems,
view,
normalizedQuery: "",
selectedProvider: "claude",
selectedModel: "sonnet-4.6",
}),
).toBe(modelBrowserModelKey("claude:sonnet-4.6"));
expect(
resolveActiveModelBrowserKey({
explicitActiveKey: null,
items: unfilteredItems,
view,
normalizedQuery: "opus",
selectedProvider: "claude",
selectedModel: "sonnet-4.6",
}),
).toBe(modelBrowserProfileKey("reviewer"));
});
it("restores preferred provider highlight when returning to the root view", () => {
const items = resolveModelBrowserNavItems({
view: { kind: "all" },
providers,
profiles,
showProfilesSection: true,
canCreateProfileRow: false,
normalizedQuery: "",
isSearchFocused: false,
hasCustomRootBrowseContent: false,
});
expect(
resolveActiveModelBrowserKey({
explicitActiveKey: null,
items,
view: { kind: "all" },
normalizedQuery: "",
selectedProvider: "codex",
selectedModel: "gpt-5.4",
preferredKey: modelBrowserProviderKey("codex"),
}),
).toBe(modelBrowserProviderKey("codex"));
});
it("omits initial highlight when suppressed on native touch until an arrow key moves selection", () => {
const items = resolveModelBrowserNavItems({
view: { kind: "all" },
providers,
profiles,
showProfilesSection: true,
canCreateProfileRow: false,
normalizedQuery: "",
isSearchFocused: false,
hasCustomRootBrowseContent: false,
});
expect(
resolveActiveModelBrowserKey({
explicitActiveKey: null,
items,
view: { kind: "all" },
normalizedQuery: "",
selectedProvider: "claude",
selectedModel: "opus-5",
suppressInitialActive: true,
}),
).toBeNull();
const firstMove = moveModelBrowserActiveKey({ items, activeKey: null, key: "ArrowDown" });
expect(firstMove).toBe(modelBrowserProfileKey("reviewer"));
expect(
resolveActiveModelBrowserKey({
explicitActiveKey: firstMove,
items,
view: { kind: "all" },
normalizedQuery: "",
selectedProvider: "claude",
selectedModel: "opus-5",
suppressInitialActive: true,
}),
).toBe(modelBrowserProfileKey("reviewer"));
expect(moveModelBrowserActiveKey({ items, activeKey: null, key: "ArrowUp" })).toBe(
modelBrowserProviderKey("codex"),
);
});
it("projects rendered sections and keyboard nav items from a single model", () => {
const browse = resolveModelBrowserProjection({
view: { kind: "all" },
providers,
profiles,
showProfilesSection: true,
canCreateProfileRow: true,
normalizedQuery: "",
isSearchFocused: false,
hasCustomRootBrowseContent: false,
});
expect(browse.kind).toBe("browse");
if (browse.kind === "browse") {
expect(browse.profileSection).toEqual({ kind: "profiles", rows: profiles });
expect(browse.providers.map((entry) => entry.id)).toEqual(["claude", "codex"]);
expect(browse.showProvidersHeading).toBe(true);
expect(browse.isEmpty).toBe(false);
expect(browse.navItems.map((item) => item.key)).toEqual([
modelBrowserProfileKey("reviewer"),
modelBrowserProfileKey("quick"),
modelBrowserProviderKey("claude"),
modelBrowserProviderKey("codex"),
]);
}
const providerSearch = resolveModelBrowserProjection({
view: { kind: "provider", providerId: "claude", providerLabel: "Claude Code" },
providers,
profiles,
showProfilesSection: true,
canCreateProfileRow: true,
normalizedQuery: "opus",
isSearchFocused: true,
hasCustomRootBrowseContent: false,
});
expect(providerSearch.kind).toBe("modelList");
if (providerSearch.kind === "modelList") {
expect(providerSearch.showProviderLabel).toBe(false);
expect(providerSearch.profileSection).toEqual({
kind: "searchProfiles",
rows: [reviewer],
showModelsHeading: true,
});
expect(providerSearch.modelRows.map((row) => row.modelId)).toEqual(["opus-5"]);
expect(providerSearch.navItems.map((item) => item.key)).toEqual([
modelBrowserProfileKey("reviewer"),
modelBrowserModelKey("claude:opus-5"),
]);
}
expect(
resolveModelBrowserProjection({
view: { kind: "provider", providerId: "pi", providerLabel: "Pi" },
providers: [{ id: "pi", label: "Pi", modelSelection: { kind: "error", message: "boom" } }],
profiles: null,
showProfilesSection: false,
canCreateProfileRow: false,
normalizedQuery: "",
isSearchFocused: false,
hasCustomRootBrowseContent: false,
}),
).toEqual({
kind: "providerError",
providerId: "pi",
message: "boom",
navItems: [],
});
expect(
resolveModelBrowserProjection({
view: { kind: "all" },
providers,
profiles,
showProfilesSection: true,
canCreateProfileRow: true,
normalizedQuery: "zzzz",
isSearchFocused: true,
hasCustomRootBrowseContent: false,
}),
).toEqual({
kind: "noSearchMatches",
navItems: [],
});
});
it("wraps active key movement across all items", () => {
const items = resolveModelBrowserNavItems({
view: { kind: "all" },
providers,
profiles: [reviewer],
showProfilesSection: true,
canCreateProfileRow: false,
normalizedQuery: "",
isSearchFocused: false,
hasCustomRootBrowseContent: false,
});
expect(
moveModelBrowserActiveKey({
items,
activeKey: modelBrowserProfileKey("reviewer"),
key: "ArrowUp",
}),
).toBe(modelBrowserProviderKey("codex"));
expect(
moveModelBrowserActiveKey({
items,
activeKey: modelBrowserProviderKey("codex"),
key: "ArrowDown",
}),
).toBe(modelBrowserProfileKey("reviewer"));
});
it("resolves arrow, enter, drill-down, and back commands while respecting text editing and focused controls", () => {
const rootItems = resolveModelBrowserNavItems({
view: { kind: "all" },
providers,
profiles: [reviewer],
showProfilesSection: true,
canCreateProfileRow: false,
normalizedQuery: "",
isSearchFocused: false,
hasCustomRootBrowseContent: false,
});
expect(
resolveModelBrowserKeyCommand({
event: { key: "ArrowDown" },
view: { kind: "all" },
items: rootItems,
activeKey: modelBrowserProfileKey("reviewer"),
searchQuery: "",
canGoBack: true,
focusedControlOwnsEnter: false,
}),
).toEqual({ kind: "move", nextKey: modelBrowserProviderKey("claude") });
expect(
resolveModelBrowserKeyCommand({
event: { key: "ArrowDown", metaKey: true },
view: { kind: "all" },
items: rootItems,
activeKey: modelBrowserProfileKey("reviewer"),
searchQuery: "",
canGoBack: true,
focusedControlOwnsEnter: false,
}),
).toBeNull();
expect(
resolveModelBrowserKeyCommand({
event: { key: "ArrowRight" },
view: { kind: "all" },
items: rootItems,
activeKey: modelBrowserProviderKey("claude"),
searchQuery: "",
canGoBack: true,
focusedControlOwnsEnter: false,
}),
).toEqual({ kind: "drillDown", providerId: "claude", providerLabel: "Claude Code" });
// ArrowRight stays with the search input when query text exists.
expect(
resolveModelBrowserKeyCommand({
event: { key: "ArrowRight" },
view: { kind: "all" },
items: rootItems,
activeKey: modelBrowserProviderKey("claude"),
searchQuery: "cl",
canGoBack: true,
focusedControlOwnsEnter: false,
}),
).toBeNull();
// Enter yields when a secondary button (such as Back or Edit profiles) has DOM focus.
expect(
resolveModelBrowserKeyCommand({
event: { key: "Enter" },
view: { kind: "all" },
items: rootItems,
activeKey: modelBrowserProfileKey("reviewer"),
searchQuery: "",
canGoBack: true,
focusedControlOwnsEnter: true,
}),
).toBeNull();
expect(
resolveModelBrowserKeyCommand({
event: { key: "Enter" },
view: { kind: "all" },
items: rootItems,
activeKey: modelBrowserProfileKey("reviewer"),
searchQuery: "",
canGoBack: true,
focusedControlOwnsEnter: false,
}),
).toEqual({
kind: "activate",
item: { key: modelBrowserProfileKey("reviewer"), kind: "profile", profileId: "reviewer" },
});
const providerView = {
kind: "provider",
providerId: "claude",
providerLabel: "Claude Code",
} as const;
expect(
resolveModelBrowserKeyCommand({
event: { key: "ArrowLeft" },
view: providerView,
items: rootItems,
activeKey: modelBrowserProfileKey("reviewer"),
searchQuery: "",
canGoBack: true,
focusedControlOwnsEnter: false,
}),
).toEqual({ kind: "back", providerId: "claude" });
expect(
resolveModelBrowserKeyCommand({
event: { key: "Backspace" },
view: providerView,
items: rootItems,
activeKey: modelBrowserProfileKey("reviewer"),
searchQuery: "o",
canGoBack: true,
focusedControlOwnsEnter: false,
}),
).toBeNull();
expect(
resolveModelBrowserKeyCommand({
event: { key: "Backspace" },
view: providerView,
items: rootItems,
activeKey: modelBrowserProfileKey("reviewer"),
searchQuery: "",
canGoBack: false,
focusedControlOwnsEnter: false,
}),
).toBeNull();
});
});
@@ -1,9 +1,7 @@
import { compareMatchScores, scoreTextFields } from "@getpaseo/protocol/search/text-match";
import { getNextActiveIndex } from "@/components/ui/combobox-keyboard";
import {
filterAndRankModelRows,
getAllProviderModelRows,
getProviderModelRows,
type ProviderSelectionModelRow,
type ProviderSelectorProvider,
} from "@/provider-selection/provider-selection";
@@ -137,455 +135,3 @@ export function resolveInitialModelBrowserView({
return { kind: "all" };
}
export const MODEL_BROWSER_KEYBOARD_KEYS = [
"ArrowDown",
"ArrowUp",
"ArrowRight",
"ArrowLeft",
"Backspace",
"Enter",
] as const;
export const MODEL_BROWSER_CREATE_PROFILE_KEY = "create-profile";
export function modelBrowserProfileKey(profileId: string): string {
return `profile:${profileId}`;
}
export function modelBrowserProviderKey(providerId: string): string {
return `provider:${providerId}`;
}
export function modelBrowserModelKey(favoriteKey: string): string {
return `model:${favoriteKey}`;
}
/** A profile row shape needed to build the ordered keyboard navigation list. */
export interface NavigableProfileRow extends SearchableProfileRow {
id: string;
provider: string;
}
export type ModelBrowserNavItem =
| { key: string; kind: "profile"; profileId: string }
| { key: typeof MODEL_BROWSER_CREATE_PROFILE_KEY; kind: "createProfile" }
| { key: string; kind: "provider"; providerId: string; providerLabel: string }
| { key: string; kind: "model"; provider: string; modelId: string; modelIndex: number };
export type ModelBrowserProfileSection<TProfile extends NavigableProfileRow = NavigableProfileRow> =
| { kind: "none" }
| { kind: "createProfile" }
| { kind: "profiles"; rows: TProfile[] }
| { kind: "searchProfiles"; rows: TProfile[]; showModelsHeading: boolean };
export type ModelBrowserProjection<TProfile extends NavigableProfileRow = NavigableProfileRow> =
| { kind: "providerLoading"; navItems: ModelBrowserNavItem[] }
| { kind: "providerError"; providerId: string; message: string; navItems: ModelBrowserNavItem[] }
| { kind: "empty"; navItems: ModelBrowserNavItem[] }
| { kind: "noSearchMatches"; navItems: ModelBrowserNavItem[] }
| {
kind: "modelList";
profileSection: ModelBrowserProfileSection<TProfile>;
modelRows: ProviderSelectionModelRow[];
showProviderLabel: boolean;
navItems: ModelBrowserNavItem[];
}
| {
kind: "browse";
profileSection: ModelBrowserProfileSection<TProfile>;
providers: ProviderSelectorProvider[];
showProvidersHeading: boolean;
isEmpty: boolean;
navItems: ModelBrowserNavItem[];
};
export interface ModelBrowserProjectionInput<
TProfile extends NavigableProfileRow = NavigableProfileRow,
> {
view: ModelBrowserView;
providers: ProviderSelectorProvider[];
profiles: readonly TProfile[] | null;
showProfilesSection: boolean;
canCreateProfileRow: boolean;
normalizedQuery: string;
isSearchFocused: boolean;
hasCustomRootBrowseContent: boolean;
}
function toProfileNavItems(rows: readonly NavigableProfileRow[]): ModelBrowserNavItem[] {
return rows.map((row) => ({
key: modelBrowserProfileKey(row.id),
kind: "profile",
profileId: row.id,
}));
}
function profileSectionToNavItems<TProfile extends NavigableProfileRow>(
section: ModelBrowserProfileSection<TProfile>,
): ModelBrowserNavItem[] {
if (section.kind === "none") return [];
if (section.kind === "createProfile") {
return [{ key: MODEL_BROWSER_CREATE_PROFILE_KEY, kind: "createProfile" }];
}
return toProfileNavItems(section.rows);
}
function resolveBrowseProfileSection<TProfile extends NavigableProfileRow>(
rows: readonly TProfile[] | null,
showProfilesSection: boolean,
canCreateProfileRow: boolean,
): ModelBrowserProfileSection<TProfile> {
if (!showProfilesSection || rows === null) return { kind: "none" };
if (rows.length > 0) return { kind: "profiles", rows: [...rows] };
return canCreateProfileRow ? { kind: "createProfile" } : { kind: "none" };
}
function resolveProviderProfileSection<TProfile extends NavigableProfileRow>({
providerProfiles,
showProfilesSection,
canCreateProfileRow,
normalizedQuery,
hasModelRows,
}: {
providerProfiles: readonly TProfile[] | null;
showProfilesSection: boolean;
canCreateProfileRow: boolean;
normalizedQuery: string;
hasModelRows: boolean;
}): ModelBrowserProfileSection<TProfile> {
if (!showProfilesSection || providerProfiles === null) return { kind: "none" };
if (normalizedQuery.length === 0) {
return resolveBrowseProfileSection(providerProfiles, true, canCreateProfileRow);
}
const matched = filterAndRankProfileRows(providerProfiles, normalizedQuery);
return matched.length > 0
? { kind: "searchProfiles", rows: matched, showModelsHeading: hasModelRows }
: { kind: "none" };
}
function toProviderNavItems(providers: readonly ProviderSelectorProvider[]): ModelBrowserNavItem[] {
return providers.map((provider) => ({
key: modelBrowserProviderKey(provider.id),
kind: "provider",
providerId: provider.id,
providerLabel: provider.label,
}));
}
function toModelNavItems(rows: readonly ProviderSelectionModelRow[]): ModelBrowserNavItem[] {
return rows.map((row, modelIndex) => ({
key: modelBrowserModelKey(row.favoriteKey),
kind: "model",
provider: row.provider,
modelId: row.modelId,
modelIndex,
}));
}
function resolveProviderProjection<TProfile extends NavigableProfileRow>({
providerId,
providers,
profiles,
showProfilesSection,
canCreateProfileRow,
normalizedQuery,
}: {
providerId: string;
providers: ProviderSelectorProvider[];
profiles: readonly TProfile[] | null;
showProfilesSection: boolean;
canCreateProfileRow: boolean;
normalizedQuery: string;
}): ModelBrowserProjection<TProfile> {
const provider = providers.find((entry) => entry.id === providerId) ?? null;
if (!provider) return { kind: "empty", navItems: [] };
if (provider.modelSelection.kind === "loading") return { kind: "providerLoading", navItems: [] };
if (provider.modelSelection.kind === "error") {
return {
kind: "providerError",
providerId,
message: provider.modelSelection.message,
navItems: [],
};
}
const modelRows = filterAndRankModelRows(getProviderModelRows(provider), normalizedQuery);
const providerProfiles =
profiles !== null ? profiles.filter((row) => row.provider === providerId) : null;
const profileSection = resolveProviderProfileSection({
providerProfiles,
showProfilesSection,
canCreateProfileRow,
normalizedQuery,
hasModelRows: modelRows.length > 0,
});
if (modelRows.length === 0 && profileSection.kind === "none") {
return { kind: "empty", navItems: [] };
}
return {
kind: "modelList",
profileSection,
modelRows,
showProviderLabel: false,
navItems: [...profileSectionToNavItems(profileSection), ...toModelNavItems(modelRows)],
};
}
/**
* Single source of truth for what ModelBrowser renders and the flat keyboard navigation order.
* Deriving navItems directly from the projected sections keeps rendering and arrow keys in lockstep.
*/
export function resolveModelBrowserProjection<TProfile extends NavigableProfileRow>(
input: ModelBrowserProjectionInput<TProfile>,
): ModelBrowserProjection<TProfile> {
if (input.view.kind === "provider") {
return resolveProviderProjection({
providerId: input.view.providerId,
providers: input.providers,
profiles: input.profiles,
showProfilesSection: input.showProfilesSection,
canCreateProfileRow: input.canCreateProfileRow,
normalizedQuery: input.normalizedQuery,
});
}
const allView = resolveModelBrowserAllView({
providers: input.providers,
profiles: input.showProfilesSection && input.profiles ? input.profiles : [],
normalizedQuery: input.normalizedQuery,
isSearchFocused: input.isSearchFocused,
});
if (allView.kind === "noSearchMatches") {
return { kind: "noSearchMatches", navItems: [] };
}
if (allView.kind === "searchResults") {
const profileSection: ModelBrowserProfileSection<TProfile> =
allView.profiles.length > 0
? {
kind: "searchProfiles",
rows: allView.profiles,
showModelsHeading: allView.rows.length > 0,
}
: { kind: "none" };
return {
kind: "modelList",
profileSection,
modelRows: allView.rows,
showProviderLabel: true,
navItems: [...profileSectionToNavItems(profileSection), ...toModelNavItems(allView.rows)],
};
}
const profileSection = resolveBrowseProfileSection(
input.profiles,
input.showProfilesSection,
input.canCreateProfileRow,
);
const visibleProviders = input.hasCustomRootBrowseContent ? [] : input.providers;
const hasResults =
input.profiles !== null || input.providers.length > 0 || input.hasCustomRootBrowseContent;
return {
kind: "browse",
profileSection,
providers: visibleProviders,
showProvidersHeading: input.showProfilesSection && input.profiles !== null,
isEmpty: !hasResults,
navItems: [
...profileSectionToNavItems(profileSection),
...toProviderNavItems(visibleProviders),
],
};
}
/**
* Returns the flat visual order of keyboard-navigable rows for the current ModelBrowser state.
*/
export function resolveModelBrowserNavItems<TProfile extends NavigableProfileRow>(
input: ModelBrowserProjectionInput<TProfile>,
): ModelBrowserNavItem[] {
return resolveModelBrowserProjection(input).navItems;
}
export function resolveInitialModelBrowserActiveKey({
items,
view,
normalizedQuery,
selectedProvider,
selectedModel,
preferredKey,
}: {
items: readonly ModelBrowserNavItem[];
view: ModelBrowserView;
normalizedQuery: string;
selectedProvider: string;
selectedModel: string;
preferredKey?: string | null;
}): string | null {
if (items.length === 0) return null;
if (preferredKey && items.some((item) => item.key === preferredKey)) {
return preferredKey;
}
if (normalizedQuery.length > 0) {
return items[0].key;
}
if (view.kind === "provider" && selectedProvider.length > 0 && selectedModel.length > 0) {
const selectedItem = items.find(
(item) =>
item.kind === "model" &&
item.provider === selectedProvider &&
item.modelId === selectedModel,
);
if (selectedItem) return selectedItem.key;
}
return items[0].key;
}
export function resolveActiveModelBrowserKey({
explicitActiveKey,
items,
view,
normalizedQuery,
selectedProvider,
selectedModel,
preferredKey,
suppressInitialActive = false,
}: {
explicitActiveKey: string | null;
items: readonly ModelBrowserNavItem[];
view: ModelBrowserView;
normalizedQuery: string;
selectedProvider: string;
selectedModel: string;
preferredKey?: string | null;
/** Skip initial highlight on native touch surfaces until the user navigates with a keyboard. */
suppressInitialActive?: boolean;
}): string | null {
if (explicitActiveKey && items.some((item) => item.key === explicitActiveKey)) {
return explicitActiveKey;
}
if (suppressInitialActive) {
return null;
}
return resolveInitialModelBrowserActiveKey({
items,
view,
normalizedQuery,
selectedProvider,
selectedModel,
preferredKey,
});
}
export function moveModelBrowserActiveKey({
items,
activeKey,
key,
}: {
items: readonly ModelBrowserNavItem[];
activeKey: string | null;
key: "ArrowDown" | "ArrowUp";
}): string | null {
if (items.length === 0) return null;
const currentIndex = activeKey ? items.findIndex((item) => item.key === activeKey) : -1;
const nextIndex = getNextActiveIndex({ currentIndex, itemCount: items.length, key });
return nextIndex >= 0 ? (items[nextIndex]?.key ?? null) : null;
}
export type ModelBrowserKeyCommand =
| { kind: "move"; nextKey: string }
| { kind: "activate"; item: ModelBrowserNavItem }
| { kind: "drillDown"; providerId: string; providerLabel: string }
| { kind: "back"; providerId: string };
export interface ModelBrowserKeyEvent {
key: string;
metaKey?: boolean;
ctrlKey?: boolean;
altKey?: boolean;
shiftKey?: boolean;
}
function hasModifierKey(event: ModelBrowserKeyEvent): boolean {
return Boolean(event.metaKey || event.ctrlKey || event.altKey);
}
function resolveHierarchyKeyCommand({
key,
view,
activeItem,
searchQuery,
canGoBack,
}: {
key: string;
view: ModelBrowserView;
activeItem: ModelBrowserNavItem | null;
searchQuery: string;
canGoBack: boolean;
}): ModelBrowserKeyCommand | null {
if (searchQuery.length > 0) return null;
if (key === "ArrowRight" && activeItem?.kind === "provider") {
return {
kind: "drillDown",
providerId: activeItem.providerId,
providerLabel: activeItem.providerLabel,
};
}
if ((key === "ArrowLeft" || key === "Backspace") && view.kind === "provider" && canGoBack) {
return { kind: "back", providerId: view.providerId };
}
return null;
}
/**
* Resolves a keydown inside ModelBrowser into a navigation command, or null when the key
* belongs to text editing or a focused secondary control.
*/
export function resolveModelBrowserKeyCommand({
event,
view,
items,
activeKey,
searchQuery,
canGoBack,
focusedControlOwnsEnter,
}: {
event: ModelBrowserKeyEvent;
view: ModelBrowserView;
items: readonly ModelBrowserNavItem[];
activeKey: string | null;
searchQuery: string;
canGoBack: boolean;
focusedControlOwnsEnter: boolean;
}): ModelBrowserKeyCommand | null {
if (hasModifierKey(event)) return null;
if (event.key === "ArrowDown" || event.key === "ArrowUp") {
const nextKey = moveModelBrowserActiveKey({ items, activeKey, key: event.key });
return nextKey ? { kind: "move", nextKey } : null;
}
if (event.shiftKey) return null;
const activeItem = activeKey ? (items.find((item) => item.key === activeKey) ?? null) : null;
if (event.key === "Enter") {
return focusedControlOwnsEnter || !activeItem ? null : { kind: "activate", item: activeItem };
}
return resolveHierarchyKeyCommand({
key: event.key,
view,
activeItem,
searchQuery,
canGoBack,
});
}
File diff suppressed because it is too large Load Diff
@@ -49,7 +49,6 @@ interface AppRowExtras {
leading?: ReactNode;
/** A page outside the app that helps with this row, drawn under the hint as "Label ↗". */
link?: Pick<ExternalLinkProps, "href" | "label" | "accessibilityLabel">;
errorTestID?: string;
}
interface AppSettingsRowProps extends Omit<SettingsRowProps, "hint">, AppRowExtras {
@@ -78,7 +77,6 @@ export function SettingsRow({
hint,
link,
error,
errorTestID,
children,
testID,
}: AppSettingsRowProps) {
@@ -97,7 +95,7 @@ export function SettingsRow({
</View>
) : null}
{error ? (
<Text accessibilityRole="alert" style={settingsStyles.rowError} testID={errorTestID}>
<Text accessibilityRole="alert" style={settingsStyles.rowError}>
{error}
</Text>
) : null}
+74 -13
View File
@@ -1,4 +1,4 @@
import { memo, useCallback, useMemo, useRef, useState } from "react";
import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";
import {
FlatList,
Text,
@@ -6,6 +6,7 @@ import {
Pressable,
type ListRenderItemInfo,
type PressableStateCallbackType,
type ViewToken,
} from "react-native";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { useTranslation } from "react-i18next";
@@ -27,7 +28,6 @@ import { Button } from "./button";
import { HighlightedText } from "./highlighted-text";
import { mutedIconColorMapping } from "./icon-color";
import { LoadingSpinner } from "./loading-spinner";
import { useRevealActiveFlatListRow } from "./scroll-reveal";
import { StatusBadge } from "./status-badge";
export type AutocompleteOptionIcon =
@@ -247,6 +247,8 @@ function endSelected(
return null;
}
const FULLY_VISIBLE = { itemVisiblePercentThreshold: 100 };
function ListPadding() {
return <View style={styles.listPadding} />;
}
@@ -278,12 +280,71 @@ function AutocompleteRows({
}: AutocompleteRowsProps) {
const isCompact = useIsCompactFormFactor();
const listRef = useRef<FlatList<AutocompleteOption>>(null);
const reveal = useRevealActiveFlatListRow({
listRef,
itemCount: rows.length,
activeIndex: selectedRow < 0 ? null : selectedRow,
waitForViewable: true,
});
const fullyVisibleRows = useRef<{ first: number; last: number } | null>(null);
// The row the keyboard selected, until it has been brought into the viewport. The row at the
// other end is never revealed here: selecting it gives the list a scroller that rests there.
const pendingReveal = useRef<number | null>(null);
const isPendingRowMeasured = useRef(true);
const revealPendingRow = useCallback(() => {
const list = listRef.current;
const row = pendingReveal.current;
const visible = fullyVisibleRows.current;
if (!list || row === null || !visible) return;
const span = visible.last - visible.first;
if (row >= visible.first && row <= visible.last) {
pendingReveal.current = null;
} else if (row === 0) {
list.scrollToOffset({ offset: 0, animated: false });
pendingReveal.current = null;
fullyVisibleRows.current = { first: 0, last: span };
} else {
// The row comes in at the edge it was beyond.
const isNearer = row < visible.first;
isPendingRowMeasured.current = true;
list.scrollToIndex({ index: row, viewPosition: isNearer ? 0 : 1, animated: false });
// A row that has not mounted has no position yet: the list was sent towards it instead, and
// is asked again as rows mount.
if (!isPendingRowMeasured.current) return;
pendingReveal.current = null;
// The list reports what it shows after it has scrolled; the next key press may come first.
fullyVisibleRows.current = isNearer
? { first: row, last: row + span }
: { first: row - span, last: row };
}
}, []);
const handleScrollToIndexFailed = useCallback(
(info: { index: number; averageItemLength: number }) => {
isPendingRowMeasured.current = false;
listRef.current?.scrollToOffset({
offset: info.index * info.averageItemLength,
animated: false,
});
},
[],
);
useEffect(() => {
pendingReveal.current = selectedRow < 0 ? null : selectedRow;
revealPendingRow();
}, [revealPendingRow, selectedRow]);
const handleViewableItemsChanged = useCallback(
({ viewableItems }: { viewableItems: ViewToken<AutocompleteOption>[] }) => {
const indexes = viewableItems.flatMap((token) => (token.index === null ? [] : [token.index]));
if (indexes.length === 0) return;
fullyVisibleRows.current = { first: Math.min(...indexes), last: Math.max(...indexes) };
revealPendingRow();
},
[revealPendingRow],
);
// A viewport that got shorter can leave the selected row outside it.
const handleLayout = useCallback(() => {
// The list reports the rows its new height shows before the row is checked against them.
listRef.current?.recordInteraction();
pendingReveal.current = selectedRow < 0 ? null : selectedRow;
revealPendingRow();
}, [revealPendingRow, selectedRow]);
const renderRow = useCallback(
({ item, index }: ListRenderItemInfo<AutocompleteOption>) => (
@@ -307,11 +368,11 @@ function AutocompleteRows({
// The first commit fills the tallest popover, so the popover never opens short and grows.
initialNumToRender={Math.ceil(maxHeight / ROW_MIN_HEIGHT) + 1}
removeClippedSubviews={false}
viewabilityConfig={reveal.viewabilityConfig}
onViewableItemsChanged={reveal.onViewableItemsChanged}
onLayout={reveal.onLayout}
onContentSizeChange={reveal.onContentSizeChange}
onScrollToIndexFailed={reveal.onScrollToIndexFailed}
viewabilityConfig={FULLY_VISIBLE}
onViewableItemsChanged={handleViewableItemsChanged}
onLayout={handleLayout}
onContentSizeChange={revealPendingRow}
onScrollToIndexFailed={handleScrollToIndexFailed}
// The list's padding. As a header and footer it counts in the list's own scroll positions.
ListHeaderComponent={ListPadding}
ListFooterComponent={ListPadding}
+5 -42
View File
@@ -59,7 +59,6 @@ import {
InlineHeaderView,
SheetHeaderView,
type SheetHeader,
type SheetKeyboard,
} from "@/components/adaptive-modal-sheet";
import { FloatingSurface } from "@/components/ui/floating";
import { useDismissKeyboardOnOpen } from "@/components/ui/keyboard-dismiss";
@@ -148,11 +147,6 @@ export interface ComboboxProps {
anchorRef: React.RefObject<View | null>;
/** Where focus goes when the picker closes. Defaults to whatever had focus when it opened. */
restoreFocusRef?: React.RefObject<unknown>;
/**
* Keys custom `children` handle while the combobox is the top overlay. Escape always
* closes the combobox. Return true from `onKeyDown` to claim the key.
*/
keyboard?: SheetKeyboard;
children?: ReactNode;
}
@@ -1301,16 +1295,12 @@ function DesktopComboboxOptionsBody(props: {
function DesktopComboboxBody(props: DesktopBodyProps): ReactElement | null {
const active = useRetainedPanelActive();
const setOverlayScope = props.setOverlayScope;
// Floating UI allocates a fresh `refs` object per render; keep the callback ref stable so
// React does not detach and re-register the overlay focus scope on every state update.
const setFloatingFnRef = useRef(props.refs.setFloating);
setFloatingFnRef.current = props.refs.setFloating;
const setFloatingRef = useCallback(
(node: View | null) => {
setFloatingFnRef.current(node);
props.refs.setFloating(node);
setOverlayScope(node);
},
[setOverlayScope],
[props.refs, setOverlayScope],
);
// Remove the portal before a retained chat can freeze its closing update.
@@ -1440,7 +1430,6 @@ export function Combobox({
keepOpenOnSelect = false,
anchorRef,
restoreFocusRef,
keyboard,
children,
}: ComboboxProps): ReactElement | null {
const { t } = useTranslation();
@@ -1727,42 +1716,16 @@ export function Combobox({
[],
);
const hasChildren = Boolean(children);
const overlayKeys = useMemo<readonly string[]>(() => {
if (keyboard) return ["Escape", ...keyboard.keys];
return hasChildren ? ["Escape"] : ["Escape", "Enter", "ArrowUp", "ArrowDown"];
}, [hasChildren, keyboard]);
const handleOverlayKeyDown = useCallback(
(event: KeyboardInputEvent) => {
if (keyboard) {
if (event.key === "Escape") {
event.preventDefault();
handleClose();
return true;
}
if (!keyboard.onKeyDown(event)) return false;
event.preventDefault();
return true;
}
if (hasChildren) {
if (event.key !== "Escape") return false;
event.preventDefault();
handleClose();
return true;
}
return isDesktopKey(event.key) ? handleDesktopKey(event.key, event) : false;
},
[handleClose, handleDesktopKey, hasChildren, keyboard],
);
const setOverlayScope = useOverlayRegistration({
active: isOpen,
layer: floatingLayer,
keys: overlayKeys,
onKeyDown: handleOverlayKeyDown,
keys: ["Escape", "Enter", "ArrowUp", "ArrowDown"],
onKeyDown: (event) => (isDesktopKey(event.key) ? handleDesktopKey(event.key, event) : false),
restoreFocusRef,
});
const effectiveSearchPlaceholder = searchPlaceholder ?? resolvedPlaceholder;
const hasChildren = Boolean(children);
if (isMobile) {
return (
+1 -142
View File
@@ -1,12 +1,10 @@
import { useCallback, useEffect, useLayoutEffect, useRef, type RefObject } from "react";
import { useCallback, useLayoutEffect, useRef, type RefObject } from "react";
import type {
FlatList,
LayoutChangeEvent,
NativeScrollEvent,
NativeSyntheticEvent,
ScrollView,
View,
ViewToken,
} from "react-native";
export function getScrollOffsetToRevealItem(args: {
@@ -109,142 +107,3 @@ export function useRevealActiveItem(options: {
return { activeItemRef, contentRef, onItemLayout: reveal, onViewportLayout, onScroll };
}
export const FULLY_VISIBLE_VIEWABILITY = { itemVisiblePercentThreshold: 100 };
export interface RevealActiveFlatListHandlers<T> {
viewabilityConfig: typeof FULLY_VISIBLE_VIEWABILITY;
onViewableItemsChanged: (info: { viewableItems: ViewToken<T>[] }) => void;
onScrollToIndexFailed: (info: { index: number; averageItemLength: number }) => void;
onContentSizeChange: () => void;
onLayout: () => void;
}
interface VisibleRange {
first: number;
last: number;
}
function nextVisibleRangeAfterReveal(
visible: VisibleRange | null,
row: number,
isNearer: boolean,
): VisibleRange | null {
if (!visible) return null;
const span = visible.last - visible.first;
return isNearer ? { first: row, last: row + span } : { first: row - span, last: row };
}
/**
* Keeps the keyboard-active row visible inside a virtualized FlatList. Tracks
* fully visible rows via viewability callbacks, retries unmeasured rows as they
* mount after scrollToIndexFailed, and supports scrolling to offset 0 when a
* header item above row 0 is active.
*/
export function useRevealActiveFlatListRow<T>({
listRef,
itemCount,
activeIndex,
hasHeader = false,
waitForViewable = false,
listKey,
}: {
listRef: RefObject<FlatList<T> | null>;
itemCount: number;
activeIndex: number | "top" | null;
hasHeader?: boolean;
waitForViewable?: boolean;
listKey?: unknown;
}): RevealActiveFlatListHandlers<T> {
const fullyVisibleRows = useRef<VisibleRange | null>(null);
const pendingReveal = useRef<number | null>(null);
const isPendingRowMeasured = useRef(true);
const itemCountRef = useRef(itemCount);
itemCountRef.current = itemCount;
const hasHeaderRef = useRef(hasHeader);
hasHeaderRef.current = hasHeader;
const waitForViewableRef = useRef(waitForViewable);
waitForViewableRef.current = waitForViewable;
const revealPendingRow = useCallback(() => {
const list = listRef.current;
const row = pendingReveal.current;
if (!list || row === null || row < 0 || row >= itemCountRef.current) return;
const visible = fullyVisibleRows.current;
if (waitForViewableRef.current && !visible) return;
if (visible && row >= visible.first && row <= visible.last) {
pendingReveal.current = null;
return;
}
if (row === 0 && !hasHeaderRef.current) {
list.scrollToOffset({ offset: 0, animated: false });
pendingReveal.current = null;
fullyVisibleRows.current = nextVisibleRangeAfterReveal(visible, 0, true);
return;
}
const isNearer = visible !== null && row < visible.first;
let viewPosition = 0.5;
if (visible !== null) {
viewPosition = isNearer ? 0 : 1;
}
isPendingRowMeasured.current = true;
list.scrollToIndex({ index: row, viewPosition, animated: false });
if (!isPendingRowMeasured.current) return;
pendingReveal.current = null;
fullyVisibleRows.current = nextVisibleRangeAfterReveal(visible, row, isNearer);
}, [listRef]);
const handleScrollToIndexFailed = useCallback(
(info: { index: number; averageItemLength: number }) => {
isPendingRowMeasured.current = false;
if (info.index >= itemCountRef.current - 1) {
listRef.current?.scrollToEnd({ animated: false });
return;
}
listRef.current?.scrollToOffset({
offset: info.index * info.averageItemLength,
animated: false,
});
},
[listRef],
);
const handleViewableItemsChanged = useCallback(
({ viewableItems }: { viewableItems: ViewToken<T>[] }) => {
const indexes = viewableItems.flatMap((token) => (token.index === null ? [] : [token.index]));
if (indexes.length === 0) return;
fullyVisibleRows.current = { first: Math.min(...indexes), last: Math.max(...indexes) };
revealPendingRow();
},
[revealPendingRow],
);
useEffect(() => {
if (activeIndex === "top") {
pendingReveal.current = null;
listRef.current?.scrollToOffset({ offset: 0, animated: false });
return;
}
pendingReveal.current = activeIndex !== null && activeIndex >= 0 ? activeIndex : null;
revealPendingRow();
}, [activeIndex, listKey, listRef, revealPendingRow]);
// A viewport that got shorter can leave the selected row outside it.
const handleLayout = useCallback(() => {
listRef.current?.recordInteraction();
pendingReveal.current =
typeof activeIndex === "number" && activeIndex >= 0 ? activeIndex : null;
revealPendingRow();
}, [activeIndex, listRef, revealPendingRow]);
return {
viewabilityConfig: FULLY_VISIBLE_VIEWABILITY,
onViewableItemsChanged: handleViewableItemsChanged,
onScrollToIndexFailed: handleScrollToIndexFailed,
onContentSizeChange: revealPendingRow,
onLayout: handleLayout,
};
}
@@ -347,7 +347,6 @@ export function CompactModelSheet({
onClose={close}
snapPoints={SNAP_POINTS}
scrollable={false}
keyboard={rootBrowser.keyboard}
contentStyle={styles.sheetBody}
contextBridge={contextBridge}
testID="agent-controls-model-sheet"
@@ -397,7 +396,6 @@ export function CompactModelSheet({
snapPoints={SNAP_POINTS}
scrollable={false}
presentation="push"
keyboard={modelBrowser.keyboard}
contentStyle={styles.sheetBody}
contextBridge={contextBridge}
testID="agent-controls-model-browser-sheet"
@@ -3,7 +3,6 @@ import type { WorkspaceDescriptor } from "@/stores/session-store";
import {
clearWorkspaceArchivePending,
isWorkspaceArchivePending,
isWorkspaceArchiveUndoRestoringAgent,
markWorkspaceArchivePending,
markWorkspaceArchiveUndoPending,
shouldSuppressWorkspaceForLocalArchive,
@@ -157,24 +156,4 @@ describe("workspace archive undo intent", () => {
settleWorkspaceArchiveIntent(secondUndo);
});
it("marks only agents that were active at archive time as restoring during undo", () => {
const activeTarget = { serverId: "server-1", workspaceId: "/repo/worktree-agents" };
const undo = markWorkspaceArchiveUndoPending({
...activeTarget,
archivedAgentIds: new Set(["agent-active"]),
});
expect(isWorkspaceArchiveUndoRestoringAgent({ ...activeTarget, agentId: "agent-active" })).toBe(
true,
);
expect(
isWorkspaceArchiveUndoRestoringAgent({ ...activeTarget, agentId: "agent-pre-archived" }),
).toBe(false);
settleWorkspaceArchiveIntent(undo);
expect(isWorkspaceArchiveUndoRestoringAgent({ ...activeTarget, agentId: "agent-active" })).toBe(
false,
);
});
});
@@ -12,8 +12,6 @@ import { normalizeWorkspaceOpaqueId } from "@/utils/workspace-identity";
*/
export interface WorkspaceArchiveIntent {
readonly kind: "archive" | "undo";
/** Active agent IDs in the workspace when this client archived it, so undo only marks those agents as restoring. */
readonly archivedAgentIds?: ReadonlySet<string>;
}
const intentsByServer = new Map<string, Map<string, WorkspaceArchiveIntent>>();
@@ -46,10 +44,9 @@ function readIntent(input: WorkspaceIntentTarget): WorkspaceArchiveIntent | null
function setIntent(
input: WorkspaceIntentTarget,
kind: WorkspaceArchiveIntent["kind"],
archivedAgentIds?: ReadonlySet<string>,
): WorkspaceArchiveIntent {
const intent: WorkspaceArchiveIntent = { kind };
const target = resolveTarget(input);
const intent: WorkspaceArchiveIntent = archivedAgentIds ? { kind, archivedAgentIds } : { kind };
if (!target) return intent;
targetByIntent.set(intent, target);
const intents = intentsByServer.get(target.serverId) ?? new Map();
@@ -122,42 +119,14 @@ export function isWorkspaceArchivePending(input: WorkspaceIntentTarget): boolean
export function markWorkspaceArchiveUndoPending(input: {
serverId: string;
workspaceId: string;
archivedAgentIds?: ReadonlySet<string>;
}): WorkspaceArchiveIntent {
return setIntent(input, "undo", input.archivedAgentIds);
return setIntent(input, "undo");
}
export function isWorkspaceArchiveUndoPending(input: WorkspaceIntentTarget): boolean {
return readIntent(input)?.kind === "undo";
}
/** Returns the active agent IDs captured by a pending workspace undo, if any. */
export function getWorkspaceArchiveUndoArchivedAgentIds(
input: WorkspaceIntentTarget,
): ReadonlySet<string> | null {
const intent = readIntent(input);
if (intent?.kind !== "undo") return null;
return intent.archivedAgentIds ?? null;
}
/**
* True while this client's workspace undo is pending and `agentId` was active in that
* workspace when archived. Agents that were already archived before the workspace archive
* return false so they are not mislabeled as unarchiving.
*/
export function isWorkspaceArchiveUndoRestoringAgent(input: {
serverId: string;
workspaceId?: string | null;
agentId?: string | null;
}): boolean {
const intent = readIntent(input);
if (intent?.kind !== "undo") return false;
const agentId = input.agentId?.trim();
if (!agentId) return false;
if (!intent.archivedAgentIds) return false;
return intent.archivedAgentIds.has(agentId);
}
export function shouldSuppressWorkspaceForLocalArchive(input: {
serverId: string;
workspace: WorkspaceDescriptor;
@@ -37,7 +37,7 @@ export function useEnableBuiltInDaemonOption(): EnableBuiltInDaemonOption {
void (async () => {
const result = await enable();
if (result?.kind === "enabled") {
router.push(buildSettingsHostSectionRoute(result.newStatus.serverId, "daemon"));
router.push(buildSettingsHostSectionRoute(result.newStatus.serverId, "host"));
}
})();
}, [enable]);
+34 -118
View File
@@ -1,18 +1,7 @@
import { useCallback, useMemo } from "react";
import { Text, View } from "react-native";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { RotateCw } from "lucide-react-native";
import { useTranslation } from "react-i18next";
import { StyleSheet } from "react-native-unistyles";
import {
SettingsAction,
SettingsRow,
SettingsRowChildren,
SettingsSwitch,
} from "@/components/settings";
import { Button } from "@/components/ui/button";
import { Switch } from "@/components/ui/switch";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { SettingsAction, SettingsRowChildren, SettingsSwitch } from "@/components/settings";
import { useToast } from "@/contexts/toast-context";
import { useFetchQuery } from "@/data/query";
import { useHostRuntimeClient, useHostRuntimeSnapshot } from "@/runtime/host-runtime";
@@ -20,7 +9,6 @@ import { useSessionStore } from "@/stores/session-store";
import { confirmDialog } from "@/utils/confirm-dialog";
import { copyToClipboard } from "@/utils/copy-to-clipboard";
import { describeTailscale } from "./tailscale-hint";
import { resolveTailscaleControlState } from "./tailscale-state";
const UPDATES_DOCS_URL = "https://paseo.sh/docs/updates";
const TAILSCALE_DOWNLOAD_URL = "https://tailscale.com/download";
@@ -77,53 +65,18 @@ function TailscaleControl({ serverId, client }: { serverId: string; client: Host
() => ({ href: TAILSCALE_DOWNLOAD_URL, label: t("devices.tailscale.install") }),
[t],
);
const refreshLabel = t(
tailscale.refreshing ? "devices.tailscale.refreshing" : "devices.tailscale.refresh",
);
const refreshButton = tailscale.showRefresh ? (
<Tooltip delayDuration={0} enabledOnDesktop enabledOnMobile={false}>
<TooltipTrigger asChild>
<Button
variant="outline"
leftIcon={RotateCw}
onPress={tailscale.refresh}
loading={tailscale.refreshing}
disabled={tailscale.refreshDisabled}
accessibilityLabel={refreshLabel}
testID="devices-tailscale-refresh"
/>
</TooltipTrigger>
<TooltipContent side="top" align="center" offset={6}>
<Text style={styles.tooltipText}>{refreshLabel}</Text>
</TooltipContent>
</Tooltip>
) : null;
const switchControl = tailscale.showSwitch ? (
<Switch
value={tailscale.value}
onValueChange={tailscale.setEnabled}
disabled={tailscale.switchDisabled}
accessibilityLabel={LABEL}
/>
) : null;
return (
<>
<SettingsRow
<SettingsSwitch
label={LABEL}
hint={status ? describeTailscale(status, t) : t("devices.tailscale.hint")}
link={tailscale.showInstallLink ? installLink : undefined}
link={status?.state === "unavailable" ? installLink : undefined}
error={tailscale.error}
>
{refreshButton && switchControl ? (
<View style={styles.controls}>
{refreshButton}
{switchControl}
</View>
) : (
(refreshButton ?? switchControl)
)}
</SettingsRow>
value={tailscale.value}
disabled={!status || status.state === "unavailable" || Boolean(status.lockedBy)}
onValueChange={tailscale.setEnabled}
/>
{tailscale.address ? <TailscaleAddress address={tailscale.address} /> : null}
</>
);
@@ -165,18 +118,16 @@ function useTailscale(serverId: string, client: HostClient) {
const { t } = useTranslation();
const queryClient = useQueryClient();
const queryKey = useMemo(() => ["tailscale-status", serverId], [serverId]);
const fetchStatus = useCallback(async () => {
const { tailscale } = await client.getDaemonStatus({ includeProviders: false });
if (!tailscale) throw new Error("Host did not report Tailscale status");
return tailscale;
}, [client]);
const query = useFetchQuery({
queryKey,
queryFn: fetchStatus,
// Tailscale can come up after the host does; polling and returning to the window pick it up.
queryFn: async () => {
const { tailscale } = await client.getDaemonStatus({ includeProviders: false });
if (!tailscale) throw new Error("Host did not report Tailscale status");
return tailscale;
},
// Tailscale can come up after the host does; polling moves "waiting" to "on" on its own.
refetchInterval: 2_000,
refetchOnWindowFocus: true,
staleTimeMs: 0,
dataShape: "value",
});
@@ -189,30 +140,13 @@ function useTailscale(serverId: string, client: HostClient) {
onSuccess: (result) => queryClient.setQueryData(queryKey, result.tailscale),
});
const refreshMutation = useMutation({
mutationFn: async () => {
await queryClient.cancelQueries({ queryKey });
return fetchStatus();
},
onSuccess: (tailscale) => queryClient.setQueryData(queryKey, tailscale),
});
const status = query.data;
const control = resolveTailscaleControlState({
status,
statusUpdatedAt: query.dataUpdatedAt,
statusError: query.isError,
changePending: change.isPending,
changePendingEnabled: change.variables?.enabled,
changeError: change.isError,
changeErrorEnabled: change.variables?.enabled,
refreshPending: refreshMutation.isPending,
refreshError: refreshMutation.isError,
refreshSubmittedAt: refreshMutation.submittedAt,
});
const pending = change.isPending ? change.variables.enabled : undefined;
const on = status?.state === "on" || status?.state === "waiting";
// Not known until the host first answers.
const value = pending ?? (status ? on : null);
const { mutate, reset: resetChange } = change;
const { mutate: runRefresh, reset: resetRefresh } = refreshMutation;
const { mutate } = change;
const confirmTurnOff = useCallback(
() =>
confirmDialog({
@@ -225,11 +159,8 @@ function useTailscale(serverId: string, client: HostClient) {
[t],
);
const turnOffConfirmed = useCallback(async () => {
if (await confirmTurnOff()) {
resetRefresh();
mutate({ enabled: false, confirmed: true });
}
}, [confirmTurnOff, mutate, resetRefresh]);
if (await confirmTurnOff()) mutate({ enabled: false, confirmed: true });
}, [confirmTurnOff, mutate]);
const disconnects = status?.disconnectsCurrentConnection === true;
const setEnabled = useCallback(
(enabled: boolean) => {
@@ -237,7 +168,6 @@ function useTailscale(serverId: string, client: HostClient) {
void turnOffConfirmed();
return;
}
resetRefresh();
mutate(
{ enabled, confirmed: false },
{
@@ -249,38 +179,24 @@ function useTailscale(serverId: string, client: HostClient) {
},
);
},
[disconnects, mutate, resetRefresh, turnOffConfirmed],
[disconnects, mutate, turnOffConfirmed],
);
const refresh = useCallback(() => {
resetChange();
runRefresh();
}, [resetChange, runRefresh]);
let error: string | undefined;
if (change.isError) {
error = t(
change.variables.enabled ? "devices.tailscale.turnOnError" : "devices.tailscale.turnOffError",
);
} else if (query.isError && !status) {
error = t("devices.tailscale.statusError");
}
return {
status,
value: control.value,
showSwitch: control.showSwitch,
switchDisabled: control.switchDisabled,
showRefresh: control.showRefresh,
refreshing: control.refreshing,
refreshDisabled: control.refreshDisabled,
showInstallLink: control.showInstallLink,
error: control.errorKey ? t(control.errorKey) : undefined,
value,
error,
// A tap is ignored until the host answers the one before it.
setEnabled: control.switchDisabled ? undefined : setEnabled,
refresh: control.refreshDisabled ? undefined : refresh,
address: control.address,
setEnabled: change.isPending ? undefined : setEnabled,
address: status?.state === "on" && value ? status.address : null,
};
}
const styles = StyleSheet.create((theme) => ({
controls: {
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[2],
},
tooltipText: {
color: theme.colors.foreground,
fontSize: theme.fontSize.sm,
},
}));
@@ -1,203 +0,0 @@
import { describe, expect, it } from "vitest";
import type { TailscaleStatus } from "@getpaseo/protocol/messages";
import { resolveTailscaleControlState, type TailscaleControlStateInput } from "./tailscale-state";
const baseInput: TailscaleControlStateInput = {
status: undefined,
statusUpdatedAt: 0,
statusError: false,
changePending: false,
changeError: false,
refreshPending: false,
refreshError: false,
refreshSubmittedAt: 0,
};
const unavailable: TailscaleStatus = { ip: null, address: null, state: "unavailable" };
const waiting: TailscaleStatus = { ip: null, address: "100.101.102.103:6767", state: "waiting" };
const off: TailscaleStatus = { ip: "100.101.102.103", address: null, state: "off" };
const on: TailscaleStatus = { ip: "100.101.102.103", address: "100.101.102.103:6767", state: "on" };
describe("resolveTailscaleControlState", () => {
it("reserves the switch space without Refresh during initial load", () => {
expect(resolveTailscaleControlState(baseInput)).toEqual({
value: null,
showSwitch: true,
switchDisabled: true,
showRefresh: false,
refreshing: false,
refreshDisabled: false,
showInstallLink: false,
address: null,
errorKey: null,
});
});
it("shows Refresh, install link, and a disabled switch when Tailscale is unavailable", () => {
expect(
resolveTailscaleControlState({
...baseInput,
status: unavailable,
statusUpdatedAt: 1000,
}),
).toEqual({
value: false,
showSwitch: true,
switchDisabled: true,
showRefresh: true,
refreshing: false,
refreshDisabled: false,
showInstallLink: true,
address: null,
errorKey: null,
});
});
it("shows Refresh alongside the enabled switch when Tailscale is waiting", () => {
expect(
resolveTailscaleControlState({
...baseInput,
status: waiting,
statusUpdatedAt: 1000,
}),
).toEqual({
value: true,
showSwitch: true,
switchDisabled: false,
showRefresh: true,
refreshing: false,
refreshDisabled: false,
showInstallLink: false,
address: null,
errorKey: null,
});
});
it("hides Refresh once Tailscale becomes available or active", () => {
expect(
resolveTailscaleControlState({
...baseInput,
status: off,
statusUpdatedAt: 2000,
}),
).toMatchObject({
value: false,
showSwitch: true,
switchDisabled: false,
showRefresh: false,
showInstallLink: false,
address: null,
});
expect(
resolveTailscaleControlState({
...baseInput,
status: on,
statusUpdatedAt: 3000,
}),
).toMatchObject({
value: true,
showSwitch: true,
switchDisabled: false,
showRefresh: false,
showInstallLink: false,
address: "100.101.102.103:6767",
});
});
it("shows Refresh without an empty switch spacer when initial status check fails, and keeps it visible while retrying", () => {
expect(
resolveTailscaleControlState({
...baseInput,
statusError: true,
}),
).toEqual({
value: null,
showSwitch: false,
switchDisabled: true,
showRefresh: true,
refreshing: false,
refreshDisabled: false,
showInstallLink: false,
address: null,
errorKey: "devices.tailscale.statusError",
});
expect(
resolveTailscaleControlState({
...baseInput,
statusError: true,
refreshPending: true,
refreshSubmittedAt: 1500,
}),
).toEqual({
value: null,
showSwitch: false,
switchDisabled: true,
showRefresh: true,
refreshing: true,
refreshDisabled: true,
showInstallLink: false,
address: null,
errorKey: null,
});
});
it("surfaces a failed manual refresh even when a prior status is loaded, and clears it once a newer status arrives", () => {
expect(
resolveTailscaleControlState({
...baseInput,
status: unavailable,
statusUpdatedAt: 1000,
refreshError: true,
refreshSubmittedAt: 2000,
}),
).toMatchObject({
showRefresh: true,
errorKey: "devices.tailscale.statusError",
});
expect(
resolveTailscaleControlState({
...baseInput,
status: unavailable,
statusUpdatedAt: 3000,
refreshError: true,
refreshSubmittedAt: 2000,
}),
).toMatchObject({
showRefresh: true,
errorKey: null,
});
});
it("prevents concurrent refresh and toggle actions", () => {
expect(
resolveTailscaleControlState({
...baseInput,
status: waiting,
statusUpdatedAt: 1000,
refreshPending: true,
}),
).toMatchObject({
switchDisabled: true,
refreshing: true,
refreshDisabled: true,
});
expect(
resolveTailscaleControlState({
...baseInput,
status: waiting,
statusUpdatedAt: 1000,
changePending: true,
changePendingEnabled: false,
}),
).toMatchObject({
value: false,
switchDisabled: true,
refreshing: false,
refreshDisabled: true,
});
});
});
@@ -1,87 +0,0 @@
import type { TailscaleStatus } from "@getpaseo/protocol/messages";
export type TailscaleErrorKey =
| "devices.tailscale.turnOnError"
| "devices.tailscale.turnOffError"
| "devices.tailscale.statusError";
export interface TailscaleControlStateInput {
status: TailscaleStatus | undefined;
statusUpdatedAt: number;
statusError: boolean;
changePending: boolean;
changePendingEnabled?: boolean;
changeError: boolean;
changeErrorEnabled?: boolean;
refreshPending: boolean;
refreshError: boolean;
refreshSubmittedAt: number;
}
export interface TailscaleControlState {
value: boolean | null;
showSwitch: boolean;
switchDisabled: boolean;
showRefresh: boolean;
refreshing: boolean;
refreshDisabled: boolean;
showInstallLink: boolean;
address: string | null;
errorKey: TailscaleErrorKey | null;
}
function resolveSwitchValue(input: TailscaleControlStateInput): boolean | null {
if (input.changePending) return input.changePendingEnabled ?? null;
if (!input.status) return null;
return input.status.state === "on" || input.status.state === "waiting";
}
function shouldShowRefresh(input: TailscaleControlStateInput): boolean {
if (!input.status) {
return input.statusError || input.refreshError || input.refreshPending;
}
return input.status.state === "unavailable" || input.status.state === "waiting";
}
function resolveErrorKey(input: TailscaleControlStateInput): TailscaleErrorKey | null {
if (input.changeError) {
return input.changeErrorEnabled
? "devices.tailscale.turnOnError"
: "devices.tailscale.turnOffError";
}
if (input.refreshError && input.refreshSubmittedAt >= input.statusUpdatedAt) {
return "devices.tailscale.statusError";
}
if (!input.refreshPending && input.statusError && !input.status) {
return "devices.tailscale.statusError";
}
return null;
}
/**
* Derives the Tailscale row's controls and error state from the host status query and the latest
* toggle or manual refresh attempt.
*/
export function resolveTailscaleControlState(
input: TailscaleControlStateInput,
): TailscaleControlState {
const { status } = input;
const value = resolveSwitchValue(input);
const busy = input.changePending || input.refreshPending;
const showRefresh = shouldShowRefresh(input);
const showSwitch = Boolean(status) || !showRefresh;
const switchDisabled =
!status || status.state === "unavailable" || Boolean(status.lockedBy) || busy;
return {
value,
showSwitch,
switchDisabled,
showRefresh,
refreshing: input.refreshPending,
refreshDisabled: busy,
showInstallLink: status?.state === "unavailable",
address: status?.state === "on" && value ? status.address : null,
errorKey: resolveErrorKey(input),
};
}
@@ -1,6 +1,7 @@
import { useCallback, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import { SettingsCard, SettingsDetailRow, SettingsSection } from "@/components/settings";
import { StatusBadge } from "@/components/ui/status-badge";
import { PairDeviceModal } from "./pair-device-modal";
import { CONNECTIVITY_DOCS_URL } from "./pair-device-section";
import { TailscaleRow } from "./tailscale-row";
@@ -14,6 +15,10 @@ export function WaysToConnect({ serverId }: { serverId: string }) {
const [pairing, setPairing] = useState(false);
const openPairing = useCallback(() => setPairing(true), []);
const closePairing = useCallback(() => setPairing(false), []);
const recommended = useMemo(
() => <StatusBadge size="xs" variant="success" label={t("devices.recommended")} />,
[t],
);
const docsLink = useMemo(
() => ({
href: CONNECTIVITY_DOCS_URL,
@@ -28,6 +33,7 @@ export function WaysToConnect({ serverId }: { serverId: string }) {
<SettingsCard>
<SettingsDetailRow
label={t("devices.relay.title")}
labelAccessory={recommended}
hint={t("devices.relay.hint")}
onPress={openPairing}
testID="devices-relay"
@@ -681,56 +681,4 @@ describe("deriveAgentScreenViewState", () => {
expect(sync.ui).toBe("status");
expect(result.memory.hadInitialSyncFailure).toBe(false);
});
it("stays ready without reverting to boot when an archived agent unarchives", () => {
const archivedAgent = {
...createAgent("agent-1"),
archivedAt: new Date("2026-02-19T00:01:00.000Z"),
};
const archivedResult = deriveAgentScreenViewState({
input: {
...createBaseInput(),
agent: archivedAgent,
isArchived: true,
hasHydratedHistoryBefore: false,
needsAuthoritativeSync: true,
isHistorySyncing: true,
visibilityCatchUpStatus: "pending",
},
memory: createBaseMemory(),
});
expectReadyState(archivedResult.state);
expect(archivedResult.memory.hasRenderedReady).toBe(true);
const unarchivedAgent = {
...createAgent("agent-1"),
archivedAt: null,
};
const unarchivedInput = {
...createBaseInput(),
agent: unarchivedAgent,
isArchived: false,
hasHydratedHistoryBefore: false,
needsAuthoritativeSync: true,
isHistorySyncing: true,
visibilityCatchUpStatus: "pending" as const,
};
// Without prior ready render, the same unarchived input stays in boot.
const freshBoot = deriveAgentScreenViewState({
input: unarchivedInput,
memory: createBaseMemory(),
});
expect(freshBoot.state.tag).toBe("boot");
// Because this screen already rendered ready while archived, unarchiving stays ready.
const unarchivedResult = deriveAgentScreenViewState({
input: unarchivedInput,
memory: archivedResult.memory,
});
const ready = expectReadyState(unarchivedResult.state);
expect(ready.agent.id).toBe("agent-1");
expect(ready.source).toBe("authoritative");
expect(ready.sync).toEqual({ status: "catching_up", ui: "overlay" });
});
});
@@ -266,7 +266,7 @@ export function deriveAgentScreenViewState({
};
}
if (candidateAgent && shouldBlockReadyState && !nextMemory.hasRenderedReady) {
if (candidateAgent && shouldBlockReadyState) {
return {
state: {
tag: "boot",
@@ -1,150 +0,0 @@
import { describe, expect, it, vi } from "vitest";
import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
import { deliverUnarchiveError } from "@/components/archived-agent-callout";
import { runAgentUnarchive } from "@/hooks/use-unarchive-agent";
import { useSessionStore } from "@/stores/session-store";
import {
beginAgentUnarchive,
clearUnarchiveAgentPending,
clearUnarchiveAgentPendingForServer,
finishAgentUnarchive,
isAgentUnarchiving,
} from "@/stores/unarchive-agent-store";
describe("unarchive-agent-store", () => {
it("tracks pending unarchive state per server and agent", () => {
const first = { serverId: "server-1", agentId: "agent-a" };
const second = { serverId: "server-1", agentId: "agent-b" };
const otherServer = { serverId: "server-2", agentId: "agent-a" };
expect(isAgentUnarchiving(first)).toBe(false);
beginAgentUnarchive(first);
expect(isAgentUnarchiving(first)).toBe(true);
expect(isAgentUnarchiving(second)).toBe(false);
expect(isAgentUnarchiving(otherServer)).toBe(false);
clearUnarchiveAgentPending(first);
expect(isAgentUnarchiving(first)).toBe(false);
});
it("ignores stale attempt tokens when a newer unarchive attempt owns the agent", () => {
const target = { serverId: "server-token", agentId: "agent-1" };
const firstToken = beginAgentUnarchive(target);
const secondToken = beginAgentUnarchive(target);
finishAgentUnarchive(target, firstToken);
expect(isAgentUnarchiving(target)).toBe(true);
finishAgentUnarchive(target, secondToken);
expect(isAgentUnarchiving(target)).toBe(false);
});
it("clears pending unarchive entries for a server when its session clears", () => {
const serverA = { serverId: "server-clear-a", agentId: "agent-1" };
const serverB = { serverId: "server-clear-b", agentId: "agent-1" };
const store = useSessionStore.getState();
store.initializeSession(serverA.serverId, null as unknown as DaemonClient);
beginAgentUnarchive(serverA);
beginAgentUnarchive(serverB);
store.clearSession(serverA.serverId);
expect(isAgentUnarchiving(serverA)).toBe(false);
expect(isAgentUnarchiving(serverB)).toBe(true);
clearUnarchiveAgentPendingForServer(serverB.serverId);
});
it("ignores blank server or agent ids", () => {
expect(beginAgentUnarchive({ serverId: " ", agentId: "agent-a" })).toBe(0);
expect(isAgentUnarchiving({ serverId: " ", agentId: "agent-a" })).toBe(false);
expect(beginAgentUnarchive({ serverId: "server-1", agentId: "" })).toBe(0);
expect(isAgentUnarchiving({ serverId: "server-1", agentId: "" })).toBe(false);
});
});
describe("runAgentUnarchive", () => {
it("guards against missing client, disconnected host, and duplicate concurrent attempts", async () => {
const refreshAgent = vi.fn(async () => {});
const target = { serverId: "server-run", agentId: "agent-guard" };
expect(await runAgentUnarchive({ ...target, client: null, isConnected: true })).toBe(false);
expect(
await runAgentUnarchive({ ...target, client: { refreshAgent }, isConnected: false }),
).toBe(false);
expect(refreshAgent).not.toHaveBeenCalled();
let resolveRefresh!: () => void;
const inflightClient = {
refreshAgent: vi.fn(
() =>
new Promise<void>((resolve) => {
resolveRefresh = resolve;
}),
),
};
const first = runAgentUnarchive({ ...target, client: inflightClient, isConnected: true });
expect(isAgentUnarchiving(target)).toBe(true);
// Duplicate click while first attempt is in flight is ignored.
expect(await runAgentUnarchive({ ...target, client: inflightClient, isConnected: true })).toBe(
false,
);
expect(inflightClient.refreshAgent).toHaveBeenCalledTimes(1);
resolveRefresh();
expect(await first).toBe(true);
expect(isAgentUnarchiving(target)).toBe(false);
});
it("releases pending state in finally and rethrows when refreshAgent fails", async () => {
const target = { serverId: "server-fail", agentId: "agent-fail" };
const failingClient = {
refreshAgent: vi.fn(async () => {
expect(isAgentUnarchiving(target)).toBe(true);
throw new Error("Resume failed");
}),
};
await expect(
runAgentUnarchive({ ...target, client: failingClient, isConnected: true }),
).rejects.toThrow("Resume failed");
expect(isAgentUnarchiving(target)).toBe(false);
});
});
describe("deliverUnarchiveError", () => {
it("shows an inline error when still mounted on the same agent and falls back to toast otherwise", () => {
const inlineErrors: Array<{ targetKey: string; message: string }> = [];
const toastErrors: string[] = [];
deliverUnarchiveError({
error: new Error("Failed to resume"),
attemptKey: "srv:agent-1",
isMounted: true,
currentTargetKey: "srv:agent-1",
onInlineError: (state) => inlineErrors.push(state),
onToastError: (message) => toastErrors.push(message),
});
expect(inlineErrors).toEqual([{ targetKey: "srv:agent-1", message: "Failed to resume" }]);
expect(toastErrors).toEqual([]);
deliverUnarchiveError({
error: new Error("Unmounted failure"),
attemptKey: "srv:agent-1",
isMounted: false,
currentTargetKey: "srv:agent-1",
onInlineError: (state) => inlineErrors.push(state),
onToastError: (message) => toastErrors.push(message),
});
deliverUnarchiveError({
error: new Error("Switched agent failure"),
attemptKey: "srv:agent-1",
isMounted: true,
currentTargetKey: "srv:agent-2",
onInlineError: (state) => inlineErrors.push(state),
onToastError: (message) => toastErrors.push(message),
});
expect(toastErrors).toEqual(["Unmounted failure", "Switched agent failure"]);
});
});
@@ -1,52 +0,0 @@
import { useCallback, useSyncExternalStore } from "react";
import { useHostRuntimeClient, useHostRuntimeIsConnected } from "@/runtime/host-runtime";
import {
beginAgentUnarchive,
finishAgentUnarchive,
isAgentUnarchiving,
subscribeUnarchiveAgentPending,
type UnarchiveAgentTarget,
} from "@/stores/unarchive-agent-store";
export type { UnarchiveAgentTarget };
function useIsAgentUnarchiving({ serverId, agentId }: UnarchiveAgentTarget): boolean {
const read = useCallback(() => isAgentUnarchiving({ serverId, agentId }), [agentId, serverId]);
return useSyncExternalStore(subscribeUnarchiveAgentPending, read, read);
}
export async function runAgentUnarchive(input: {
serverId: string;
agentId: string;
client: { refreshAgent: (agentId: string) => Promise<unknown> } | null;
isConnected: boolean;
}): Promise<boolean> {
const { serverId, agentId, client, isConnected } = input;
if (!client || !isConnected || isAgentUnarchiving({ serverId, agentId })) {
return false;
}
const token = beginAgentUnarchive({ serverId, agentId });
try {
await client.refreshAgent(agentId);
return true;
} finally {
finishAgentUnarchive({ serverId, agentId }, token);
}
}
export function useUnarchiveAgent({ serverId, agentId }: UnarchiveAgentTarget) {
const client = useHostRuntimeClient(serverId);
const isConnected = useHostRuntimeIsConnected(serverId);
const isUnarchiving = useIsAgentUnarchiving({ serverId, agentId });
const unarchive = useCallback(async (): Promise<void> => {
await runAgentUnarchive({ serverId, agentId, client, isConnected });
}, [agentId, client, isConnected, serverId]);
return {
unarchive,
isUnarchiving,
isConnected,
canUnarchive: Boolean(client && isConnected && !isUnarchiving),
};
}
+3 -24
View File
@@ -294,7 +294,6 @@ export const ar: TranslationResources = {
archived: {
callout: "تمت أرشفة هذا الوكيل",
unarchive: "إلغاء الأرشفة",
unarchiving: "جارٍ إلغاء الأرشفة...",
},
},
sessions: {
@@ -1892,13 +1891,12 @@ export const ar: TranslationResources = {
waysToConnect: "طرق الاتصال",
docs: "الوثائق",
docsAccessibility: "افتح وثائق الاتصال",
relay: { title: "التتابع", hint: "دون إعداد، مشفّر من طرف إلى طرف، امسح رمز QR" },
recommended: "موصى به",
relay: { title: "التتابع", hint: "مشفّر من طرف إلى طرف، امسح رمز QR" },
tailscale: {
hint: "اتصال مباشر عبر شبكة tailnet الخاصة بك، أدخل عنوانًا",
unavailable: "Tailscale لا يعمل على هذا المضيف",
install: "احصل على Tailscale",
refresh: "تحديث",
refreshing: "جارٍ التحديث...",
waiting: "في انتظار بدء Tailscale على هذا المضيف",
alwaysOn: "مفعّل دائمًا، لأن هذا المضيف يقبل اتصالات Tailscale بالفعل",
socket: "متوقف، لأن هذا المضيف يستمع على مقبس محلي",
@@ -2416,7 +2414,7 @@ export const ar: TranslationResources = {
title: "إعدادات",
loading: "جارٍ تحميل الإعدادات...",
groups: {
app: "هذا الجهاز",
app: "برنامج",
host: "Host",
},
hostPicker: {
@@ -2434,9 +2432,7 @@ export const ar: TranslationResources = {
groupInfo: "حول{{title}}",
sections: {
general: "عام",
hosts: "المضيفون",
chat: "الدردشة",
chatAndPanes: "الدردشة والأجزاء",
appearance: "مظهر",
sidebar: "الشريط الجانبي",
terminal: "الطرفية",
@@ -2450,16 +2446,6 @@ export const ar: TranslationResources = {
diagnostics: "التشخيص",
about: "عن",
},
clientHosts: {
title: "المضيفون المحفوظون",
info: "المضيفون الذين يتصل بهم هذا الجهاز. الأسماء والأيقونات والشارات والمسارات هنا تؤثر على هذا الجهاز فقط.",
backToHosts: "العودة إلى المضيفين",
routesTitle: "كيف يتصل هذا الجهاز",
routesInfo:
"المسارات المحفوظة التي يستخدمها هذا الجهاز للوصول إلى هذا المضيف. يختار Paseo أسرع مسار متاح.",
addRoute: "إضافة مسار",
activeRoute: "نشط",
},
layout: en.settings.layout,
editor: {
title: "المحرر",
@@ -2493,7 +2479,6 @@ export const ar: TranslationResources = {
projects: "المشاريع",
connections: "اتصالات",
agents: "Agents",
tools: "الأدوات والتعليمات",
agentProfiles: "ملفات الوكيل",
metadata: "البيانات الوصفية",
voice: "الصوت",
@@ -2503,7 +2488,6 @@ export const ar: TranslationResources = {
terminals: "Terminals",
plugins: "Plugins",
host: "نظرة عامة",
daemon: "الخدمة",
},
plugins: pluginSettings.ar,
metadataGeneration: {
@@ -3041,10 +3025,6 @@ export const ar: TranslationResources = {
delete: "حذف المهارة",
},
},
tools: {
instructionsTitle: "التعليمات",
toolsTitle: "أدوات الوكلاء",
},
orchestration: {
title: "التنسيق",
unavailable: "اتصل بهذا المضيف لإدارة التنسيق",
@@ -3171,7 +3151,6 @@ export const ar: TranslationResources = {
},
},
daemon: {
runtimeTitle: "بيئة تشغيل الوكلاء",
rename: {
editLabel: "تحرير التسمية",
title: "إعادة تسمية المضيف",
+6 -27
View File
@@ -293,7 +293,6 @@ export const en = {
archived: {
callout: "This agent is archived",
unarchive: "Unarchive",
unarchiving: "Unarchiving...",
},
},
sessions: {
@@ -1921,13 +1920,12 @@ export const en = {
waysToConnect: "Ways to connect",
docs: "Docs",
docsAccessibility: "Open connectivity documentation",
relay: { title: "Relay", hint: "No setup, end-to-end encrypted, scan a QR code" },
recommended: "Recommended",
relay: { title: "Relay", hint: "End-to-end encrypted, scan a QR code" },
tailscale: {
hint: "Direct over your tailnet, enter an address",
unavailable: "Tailscale is not running on this host",
install: "Get Tailscale",
refresh: "Refresh",
refreshing: "Refreshing...",
waiting: "Waiting for Tailscale to start on this host",
alwaysOn: "Always on, because this host already accepts Tailscale connections",
socket: "Off, because this host listens on a local socket",
@@ -2410,7 +2408,7 @@ export const en = {
title: "Settings",
loading: "Loading settings...",
groups: {
app: "This device",
app: "App",
host: "Host",
},
hostPicker: {
@@ -2428,9 +2426,7 @@ export const en = {
groupInfo: "About {{title}}",
sections: {
general: "General",
hosts: "Hosts",
chat: "Chat",
chatAndPanes: "Chat & panes",
appearance: "Appearance",
sidebar: "Sidebar",
editor: "Editor",
@@ -2444,16 +2440,6 @@ export const en = {
diagnostics: "Diagnostics",
about: "About",
},
clientHosts: {
title: "Saved hosts",
info: "Hosts this device connects to. Names, icons, badges, and routes here only affect this device.",
backToHosts: "Back to hosts",
routesTitle: "How this device connects",
routesInfo:
"Saved routes this device uses to reach this host. Paseo picks the fastest available route.",
addRoute: "Add route",
activeRoute: "Active",
},
layout: {
openInSidePane: {
title: "Open location",
@@ -2525,7 +2511,6 @@ export const en = {
projects: "Projects",
connections: "Connections",
agents: "Agents",
tools: "Tools & prompts",
agentProfiles: "Agent profiles",
metadata: "Metadata",
voice: "Voice",
@@ -2535,7 +2520,6 @@ export const en = {
terminals: "Terminals",
plugins: "Plugins",
host: "Overview",
daemon: "Daemon",
},
plugins: {
gallery: pluginGallery.en,
@@ -3100,9 +3084,9 @@ export const en = {
rowTitle: "Pair a device",
},
skills: {
sectionTitle: "Skills",
title: "Paseo skills",
description: "Install bundled help, plugin, and orchestration skills",
sectionTitle: "Orchestration skills",
title: "Orchestration skills",
description: "Teach your agents how to use Paseo tools",
docs: "Skills",
openDocs: "Open skills documentation",
unavailable: "Connect to this host to manage orchestration skills",
@@ -3140,10 +3124,6 @@ export const en = {
delete: "Delete skill",
},
},
tools: {
instructionsTitle: "Instructions",
toolsTitle: "Agent tools",
},
orchestration: {
title: "Orchestration",
unavailable: "Connect to this host to manage orchestration",
@@ -3270,7 +3250,6 @@ export const en = {
},
},
daemon: {
runtimeTitle: "Agent runtime",
rename: {
editLabel: "Edit label",
title: "Rename host",
+3 -27
View File
@@ -299,7 +299,6 @@ export const es: TranslationResources = {
archived: {
callout: "Este agente está archivado.",
unarchive: "Desarchivar",
unarchiving: "Desarchivando...",
},
},
sessions: {
@@ -1942,16 +1941,12 @@ export const es: TranslationResources = {
waysToConnect: "Formas de conectarse",
docs: "Docs",
docsAccessibility: "Abrir la documentación de conectividad",
relay: {
title: "Relé",
hint: "Sin configuración, cifrado de extremo a extremo, escanea un código QR",
},
recommended: "Recomendado",
relay: { title: "Relé", hint: "Cifrado de extremo a extremo, escanea un código QR" },
tailscale: {
hint: "Conexión directa por tu tailnet, introduce una dirección",
unavailable: "Tailscale no se está ejecutando en este host",
install: "Obtener Tailscale",
refresh: "Actualizar",
refreshing: "Actualizando...",
waiting: "Esperando a que Tailscale se inicie en este host",
alwaysOn: "Siempre activado, porque este host ya acepta conexiones de Tailscale",
socket: "Desactivado, porque este host escucha en un socket local",
@@ -2436,7 +2431,7 @@ export const es: TranslationResources = {
title: "Ajustes",
loading: "Cargando configuración...",
groups: {
app: "Este dispositivo",
app: "Aplicación",
host: "Host",
},
hostPicker: {
@@ -2454,9 +2449,7 @@ export const es: TranslationResources = {
groupInfo: "Acerca de{{title}}",
sections: {
general: "General",
hosts: "Hosts",
chat: "Chat",
chatAndPanes: "Chat y paneles",
appearance: "Apariencia",
sidebar: "Barra lateral",
terminal: "Terminal",
@@ -2470,16 +2463,6 @@ export const es: TranslationResources = {
diagnostics: "Diagnóstico",
about: "Acerca de",
},
clientHosts: {
title: "Hosts guardados",
info: "Hosts a los que se conecta este dispositivo. Los nombres, iconos, insignias y rutas aquí solo afectan a este dispositivo.",
backToHosts: "Volver a hosts",
routesTitle: "Cómo se conecta este dispositivo",
routesInfo:
"Rutas guardadas que usa este dispositivo para llegar a este host. Paseo elige la más rápida disponible.",
addRoute: "Añadir ruta",
activeRoute: "Activa",
},
layout: en.settings.layout,
editor: {
title: "Editor",
@@ -2513,7 +2496,6 @@ export const es: TranslationResources = {
projects: "Proyectos",
connections: "Conexiones",
agents: "Agents",
tools: "Herramientas e instrucciones",
agentProfiles: "Perfiles de agente",
metadata: "Metadatos",
voice: "Voz",
@@ -2523,7 +2505,6 @@ export const es: TranslationResources = {
terminals: "Terminals",
plugins: "Plugins",
host: "Resumen",
daemon: "Daemon",
},
plugins: pluginSettings.es,
metadataGeneration: {
@@ -3072,10 +3053,6 @@ export const es: TranslationResources = {
delete: "Eliminar habilidad",
},
},
tools: {
instructionsTitle: "Instrucciones",
toolsTitle: "Herramientas de agentes",
},
orchestration: {
title: "Orquestación",
unavailable: "Conéctese a este host para administrar la orquestación",
@@ -3203,7 +3180,6 @@ export const es: TranslationResources = {
},
},
daemon: {
runtimeTitle: "Ejecución de agentes",
rename: {
editLabel: "Editar etiqueta",
title: "Cambiar nombre de host",
+3 -27
View File
@@ -299,7 +299,6 @@ export const fr: TranslationResources = {
archived: {
callout: "Cet agent est archivé",
unarchive: "Désarchiver",
unarchiving: "Désarchivage...",
},
},
sessions: {
@@ -1940,16 +1939,12 @@ export const fr: TranslationResources = {
waysToConnect: "Moyens de connexion",
docs: "Docs",
docsAccessibility: "Ouvrir la documentation sur la connectivité",
relay: {
title: "Relais",
hint: "Aucune configuration, chiffré de bout en bout, scannez un QR code",
},
recommended: "Recommandé",
relay: { title: "Relais", hint: "Chiffré de bout en bout, scannez un QR code" },
tailscale: {
hint: "Connexion directe via votre tailnet, saisissez une adresse",
unavailable: "Tailscale ne fonctionne pas sur cet hôte",
install: "Obtenir Tailscale",
refresh: "Actualiser",
refreshing: "Actualisation...",
waiting: "En attente du démarrage de Tailscale sur cet hôte",
alwaysOn: "Toujours activé, car cet hôte accepte déjà les connexions Tailscale",
socket: "Désactivé, car cet hôte écoute sur un socket local",
@@ -2435,7 +2430,7 @@ export const fr: TranslationResources = {
title: "Paramètres",
loading: "Chargement des paramètres…",
groups: {
app: "Cet appareil",
app: "Application",
host: "Hôte",
},
hostPicker: {
@@ -2453,9 +2448,7 @@ export const fr: TranslationResources = {
groupInfo: "À propos de {{title}}",
sections: {
general: "Général",
hosts: "Hôtes",
chat: "Discussion",
chatAndPanes: "Chat et panneaux",
appearance: "Apparence",
sidebar: "Barre latérale",
terminal: "Terminal",
@@ -2469,16 +2462,6 @@ export const fr: TranslationResources = {
diagnostics: "Diagnostic",
about: "À propos",
},
clientHosts: {
title: "Hôtes enregistrés",
info: "Hôtes auxquels cet appareil se connecte. Les noms, icônes, badges et routes ici ne concernent que cet appareil.",
backToHosts: "Retour aux hôtes",
routesTitle: "Comment cet appareil se connecte",
routesInfo:
"Routes enregistrées utilisées par cet appareil pour joindre cet hôte. Paseo choisit la plus rapide disponible.",
addRoute: "Ajouter une route",
activeRoute: "Active",
},
layout: en.settings.layout,
editor: {
title: "Éditeur",
@@ -2512,7 +2495,6 @@ export const fr: TranslationResources = {
projects: "Projets",
connections: "Connexions",
agents: "Agents",
tools: "Outils et instructions",
agentProfiles: "Profils d’agent",
metadata: "Métadonnées",
voice: "Voix",
@@ -2522,7 +2504,6 @@ export const fr: TranslationResources = {
terminals: "Terminaux",
plugins: "Plugins",
host: "Aperçu",
daemon: "Daemon",
},
plugins: pluginSettings.fr,
metadataGeneration: {
@@ -3073,10 +3054,6 @@ export const fr: TranslationResources = {
delete: "Supprimer le skill",
},
},
tools: {
instructionsTitle: "Instructions",
toolsTitle: "Outils des agents",
},
orchestration: {
title: "Orchestration",
unavailable: "Connectez-vous à cet hôte pour gérer l’orchestration",
@@ -3206,7 +3183,6 @@ export const fr: TranslationResources = {
},
},
daemon: {
runtimeTitle: "Exécution des agents",
rename: {
editLabel: "Modifier le libellé",
title: "Renommer l’hôte",
+3 -24
View File
@@ -299,7 +299,6 @@ export const ja: TranslationResources = {
archived: {
callout: "このエージェントはアーカイブされています",
unarchive: "アーカイブ解除",
unarchiving: "アーカイブ解除中...",
},
},
sessions: {
@@ -1913,13 +1912,12 @@ export const ja: TranslationResources = {
waysToConnect: "接続方法",
docs: "ドキュメント",
docsAccessibility: "接続のドキュメントを開く",
relay: { title: "リレー", hint: "設定不要、エンドツーエンド暗号化、QR コードをスキャン" },
recommended: "おすすめ",
relay: { title: "リレー", hint: "エンドツーエンド暗号化、QR コードをスキャン" },
tailscale: {
hint: "tailnet 経由で直接接続、アドレスを入力",
unavailable: "このホストで Tailscale が動作していません",
install: "Tailscale を入手",
refresh: "更新",
refreshing: "更新中...",
waiting: "このホストで Tailscale が起動するのを待っています",
alwaysOn: "常にオン。このホストはすでに Tailscale からの接続を受け付けています",
socket: "オフ。このホストはローカルソケットで待ち受けています",
@@ -2405,7 +2403,7 @@ export const ja: TranslationResources = {
title: "設定",
loading: "設定を読み込み中...",
groups: {
app: "このデバイス",
app: "アプリ",
host: "ホスト",
},
hostPicker: {
@@ -2423,9 +2421,7 @@ export const ja: TranslationResources = {
groupInfo: "{{title}}について",
sections: {
general: "一般",
hosts: "ホスト",
chat: "チャット",
chatAndPanes: "チャットとペイン",
appearance: "外観",
sidebar: "サイドバー",
terminal: "ターミナル",
@@ -2439,16 +2435,6 @@ export const ja: TranslationResources = {
diagnostics: "診断",
about: "アプリ情報",
},
clientHosts: {
title: "保存済みホスト",
info: "このデバイスが接続するホストです。ここでの名前、アイコン、バッジ、経路はこのデバイスにのみ反映されます。",
backToHosts: "ホスト一覧に戻る",
routesTitle: "このデバイスの接続経路",
routesInfo:
"このデバイスがこのホストに到達するために保存された経路です。Paseoは利用可能な最速の経路を選びます。",
addRoute: "経路を追加",
activeRoute: "接続中",
},
layout: en.settings.layout,
editor: {
title: "エディター",
@@ -2482,7 +2468,6 @@ export const ja: TranslationResources = {
projects: "プロジェクト",
connections: "接続",
agents: "エージェント",
tools: "ツールとプロンプト",
agentProfiles: "エージェントプロファイル",
metadata: "メタデータ",
voice: "音声",
@@ -2492,7 +2477,6 @@ export const ja: TranslationResources = {
terminals: "ターミナル",
plugins: "プラグイン",
host: "概要",
daemon: "デーモン",
},
plugins: pluginSettings.ja,
metadataGeneration: {
@@ -3035,10 +3019,6 @@ export const ja: TranslationResources = {
delete: "スキルを削除",
},
},
tools: {
instructionsTitle: "指示",
toolsTitle: "エージェントツール",
},
orchestration: {
title: "オーケストレーション",
unavailable: "オーケストレーションを管理するにはこのホストに接続してください",
@@ -3167,7 +3147,6 @@ export const ja: TranslationResources = {
},
},
daemon: {
runtimeTitle: "エージェントランタイム",
rename: {
editLabel: "ラベルを編集",
title: "ホストの名前を変更",
+3 -24
View File
@@ -295,7 +295,6 @@ export const ko: TranslationResources = {
archived: {
callout: "이 에이전트는 보관되었습니다",
unarchive: "보관 해제",
unarchiving: "보관 해제 중...",
},
},
sessions: {
@@ -1904,13 +1903,12 @@ export const ko: TranslationResources = {
waysToConnect: "연결 방법",
docs: "문서",
docsAccessibility: "연결 문서 열기",
relay: { title: "릴레이", hint: "설정 불필요, 엔드투엔드 암호화, QR 코드를 스캔하세요" },
recommended: "권장",
relay: { title: "릴레이", hint: "엔드투엔드 암호화, QR 코드를 스캔하세요" },
tailscale: {
hint: "tailnet으로 직접 연결, 주소 입력",
unavailable: "이 호스트에서 Tailscale이 실행 중이 아닙니다",
install: "Tailscale 받기",
refresh: "새로 고침",
refreshing: "새로 고치는 중...",
waiting: "이 호스트에서 Tailscale이 시작되기를 기다리는 중",
alwaysOn: "항상 켜짐. 이 호스트가 이미 Tailscale 연결을 받고 있습니다",
socket: "꺼짐. 이 호스트가 로컬 소켓에서 수신 대기 중입니다",
@@ -2392,7 +2390,7 @@ export const ko: TranslationResources = {
title: "설정",
loading: "설정 불러오는 중...",
groups: {
app: "이 기기",
app: "앱",
host: "호스트",
},
hostPicker: {
@@ -2410,9 +2408,7 @@ export const ko: TranslationResources = {
groupInfo: "{{title}} 정보",
sections: {
general: "일반",
hosts: "호스트",
chat: "채팅",
chatAndPanes: "채팅 및 패널",
appearance: "모양",
sidebar: "사이드바",
terminal: "터미널",
@@ -2426,16 +2422,6 @@ export const ko: TranslationResources = {
diagnostics: "진단",
about: "정보",
},
clientHosts: {
title: "저장된 호스트",
info: "이 기기가 연결하는 호스트입니다. 이름, 아이콘, 배지 및 경로는 이 기기에만 적용됩니다.",
backToHosts: "호스트로 돌아가기",
routesTitle: "이 기기의 연결 방식",
routesInfo:
"이 기기가 이 호스트에 연결할 때 사용하는 저장된 경로입니다. Paseo가 가장 빠른 경로를 선택합니다.",
addRoute: "경로 추가",
activeRoute: "활성",
},
layout: en.settings.layout,
editor: {
title: "편집기",
@@ -2469,7 +2455,6 @@ export const ko: TranslationResources = {
projects: "프로젝트",
connections: "연결",
agents: "에이전트",
tools: "도구 및 프롬프트",
agentProfiles: "에이전트 프로필",
metadata: "메타데이터",
voice: "음성",
@@ -2479,7 +2464,6 @@ export const ko: TranslationResources = {
terminals: "터미널",
plugins: "플러그인",
host: "개요",
daemon: "데몬",
},
plugins: pluginSettings.ko,
metadataGeneration: {
@@ -3020,10 +3004,6 @@ export const ko: TranslationResources = {
delete: "스킬 삭제",
},
},
tools: {
instructionsTitle: "지침",
toolsTitle: "에이전트 도구",
},
orchestration: {
title: "오케스트레이션",
unavailable: "오케스트레이션을 관리하려면 이 호스트에 연결하세요",
@@ -3151,7 +3131,6 @@ export const ko: TranslationResources = {
},
},
daemon: {
runtimeTitle: "에이전트 런타임",
rename: {
editLabel: "레이블 편집",
title: "호스트 이름 변경",
+3 -27
View File
@@ -298,7 +298,6 @@ export const ptBR: TranslationResources = {
archived: {
callout: "Este agente está arquivado",
unarchive: "Desarquivar",
unarchiving: "Desarquivando...",
},
},
sessions: {
@@ -1926,16 +1925,12 @@ export const ptBR: TranslationResources = {
waysToConnect: "Formas de conexão",
docs: "Docs",
docsAccessibility: "Abrir documentação de conectividade",
relay: {
title: "Relay",
hint: "Sem configuração, criptografia de ponta a ponta, escaneie um código QR",
},
recommended: "Recomendado",
relay: { title: "Relay", hint: "Criptografia de ponta a ponta, escaneie um código QR" },
tailscale: {
hint: "Conexão direta pela sua tailnet, digite um endereço",
unavailable: "O Tailscale não está em execução neste host",
install: "Baixar o Tailscale",
refresh: "Atualizar",
refreshing: "Atualizando...",
waiting: "Aguardando o Tailscale iniciar neste host",
alwaysOn: "Sempre ativado, porque este host já aceita conexões do Tailscale",
socket: "Desativado, porque este host escuta em um socket local",
@@ -2420,7 +2415,7 @@ export const ptBR: TranslationResources = {
title: "Configurações",
loading: "Carregando configurações...",
groups: {
app: "Este dispositivo",
app: "App",
host: "Host",
},
hostPicker: {
@@ -2438,9 +2433,7 @@ export const ptBR: TranslationResources = {
groupInfo: "Sobre {{title}}",
sections: {
general: "Geral",
hosts: "Hosts",
chat: "Chat",
chatAndPanes: "Chat e painéis",
appearance: "Aparência",
sidebar: "Barra lateral",
terminal: "Terminal",
@@ -2454,16 +2447,6 @@ export const ptBR: TranslationResources = {
diagnostics: "Diagnósticos",
about: "Sobre",
},
clientHosts: {
title: "Hosts salvos",
info: "Hosts aos quais este dispositivo se conecta. Nomes, ícones, selos e rotas aqui afetam apenas este dispositivo.",
backToHosts: "Voltar para hosts",
routesTitle: "Como este dispositivo se conecta",
routesInfo:
"Rotas salvas que este dispositivo usa para alcançar este host. O Paseo escolhe a mais rápida disponível.",
addRoute: "Adicionar rota",
activeRoute: "Ativa",
},
layout: en.settings.layout,
editor: {
title: "Editor",
@@ -2497,7 +2480,6 @@ export const ptBR: TranslationResources = {
projects: "Projetos",
connections: "Conexões",
agents: "Agentes",
tools: "Ferramentas e instruções",
agentProfiles: "Perfis de agente",
metadata: "Metadados",
voice: "Voz",
@@ -2507,7 +2489,6 @@ export const ptBR: TranslationResources = {
terminals: "Terminais",
plugins: "Plugins",
host: "Visão geral",
daemon: "Daemon",
},
plugins: pluginSettings["pt-BR"],
metadataGeneration: {
@@ -3052,10 +3033,6 @@ export const ptBR: TranslationResources = {
delete: "Excluir skill",
},
},
tools: {
instructionsTitle: "Instruções",
toolsTitle: "Ferramentas de agentes",
},
orchestration: {
title: "Orquestração",
unavailable: "Conecte-se a este host para gerenciar a orquestração",
@@ -3184,7 +3161,6 @@ export const ptBR: TranslationResources = {
},
},
daemon: {
runtimeTitle: "Execução de agentes",
rename: {
editLabel: "Editar rótulo",
title: "Renomear host",
+6 -30
View File
@@ -298,7 +298,6 @@ export const ru: TranslationResources = {
archived: {
callout: "Этот агент находится в архиве",
unarchive: "Разархивировать",
unarchiving: "Разархивация...",
},
},
sessions: {
@@ -1926,16 +1925,12 @@ export const ru: TranslationResources = {
waysToConnect: "Способы подключения",
docs: "Документация",
docsAccessibility: "Открыть документацию по подключению",
relay: {
title: "Ретранслятор",
hint: "Без настройки, сквозное шифрование, отсканируйте QR-код",
},
recommended: "Рекомендуется",
relay: { title: "Ретранслятор", hint: "Сквозное шифрование, отсканируйте QR-код" },
tailscale: {
hint: "Прямое подключение через ваш tailnet, по адресу",
unavailable: "Tailscale не запущен на этом хосте",
install: "Скачать Tailscale",
refresh: "Обновить",
refreshing: "Обновление...",
waiting: "Ожидаем запуска Tailscale на этом хосте",
alwaysOn: "Всегда включено, так как хост уже принимает подключения Tailscale",
socket: "Выключено, так как хост слушает локальный сокет",
@@ -2421,7 +2416,7 @@ export const ru: TranslationResources = {
title: "Настройки",
loading: "Загрузка настроек...",
groups: {
app: "Это устройство",
app: "Приложение",
host: "Хост",
},
hostPicker: {
@@ -2439,9 +2434,7 @@ export const ru: TranslationResources = {
groupInfo: "О разделе «{{title}}»",
sections: {
general: "Основные",
hosts: "Хосты",
chat: "Чат",
chatAndPanes: "Чат и панели",
appearance: "Оформление",
sidebar: "Боковая панель",
terminal: "Терминал",
@@ -2455,16 +2448,6 @@ export const ru: TranslationResources = {
diagnostics: "Диагностика",
about: "О приложении",
},
clientHosts: {
title: "Сохранённые хосты",
info: "Хосты, к которым подключается это устройство. Имена, значки, бейджи и маршруты здесь влияют только на это устройство.",
backToHosts: "Назад к хостам",
routesTitle: "Как подключается это устройство",
routesInfo:
"Сохранённые маршруты, по которым это устройство подключается к хосту. Paseo выбирает самый быстрый.",
addRoute: "Добавить маршрут",
activeRoute: "Активный",
},
layout: en.settings.layout,
editor: {
title: "Редактор",
@@ -2498,7 +2481,6 @@ export const ru: TranslationResources = {
projects: "Проекты",
connections: "Подключения",
agents: "Агенты",
tools: "Инструменты и промпты",
agentProfiles: "Профили агентов",
metadata: "Метаданные",
voice: "Голос",
@@ -2508,7 +2490,6 @@ export const ru: TranslationResources = {
terminals: "Терминалы",
plugins: "Плагины",
host: "Обзор",
daemon: "Демон",
},
plugins: pluginSettings.ru,
metadataGeneration: {
@@ -3021,9 +3002,9 @@ export const ru: TranslationResources = {
rowTitle: "Подключить устройство",
},
skills: {
sectionTitle: "Навыки",
title: "Навыки Paseo",
description: "Установить встроенные навыки справки, плагинов и оркестрации",
sectionTitle: "Навыки оркестрации",
title: "Навыки оркестрации",
description: "Научите агентов пользоваться инструментами Paseo",
docs: "Навыки",
openDocs: "Открыть документацию по навыкам",
unavailable: "Подключитесь к этому хосту, чтобы управлять навыками оркестрации",
@@ -3061,10 +3042,6 @@ export const ru: TranslationResources = {
delete: "Удалить навык",
},
},
tools: {
instructionsTitle: "Инструкции",
toolsTitle: "Инструменты агентов",
},
orchestration: {
title: "Оркестрация",
unavailable: "Подключитесь к этому хосту, чтобы управлять оркестрацией.",
@@ -3193,7 +3170,6 @@ export const ru: TranslationResources = {
},
},
daemon: {
runtimeTitle: "Среда выполнения агентов",
rename: {
editLabel: "Изменить название",
title: "Переименовать хост",
+3 -23
View File
@@ -294,7 +294,6 @@ export const zhCN: TranslationResources = {
archived: {
callout: "此 Agent 已归档",
unarchive: "取消归档",
unarchiving: "正在取消归档...",
},
},
sessions: {
@@ -1874,13 +1873,12 @@ export const zhCN: TranslationResources = {
waysToConnect: "连接方式",
docs: "文档",
docsAccessibility: "打开连接文档",
relay: { title: "中继", hint: "无需配置,端到端加密,扫描二维码" },
recommended: "推荐",
relay: { title: "中继", hint: "端到端加密,扫描二维码" },
tailscale: {
hint: "通过你的 tailnet 直连,输入地址即可",
unavailable: "此主机未运行 Tailscale",
install: "获取 Tailscale",
refresh: "刷新",
refreshing: "刷新中...",
waiting: "正在等待此主机上的 Tailscale 启动",
alwaysOn: "始终开启,因为此主机已接受 Tailscale 连接",
socket: "已关闭,因为此主机监听的是本地套接字",
@@ -2357,7 +2355,7 @@ export const zhCN: TranslationResources = {
title: "设置",
loading: "正在加载设置...",
groups: {
app: "此设备",
app: "应用",
host: "主机",
},
hostPicker: {
@@ -2375,9 +2373,7 @@ export const zhCN: TranslationResources = {
groupInfo: "关于 {{title}}",
sections: {
general: "通用",
hosts: "主机",
chat: "聊天",
chatAndPanes: "聊天与面板",
appearance: "外观",
sidebar: "侧边栏",
terminal: "终端",
@@ -2391,15 +2387,6 @@ export const zhCN: TranslationResources = {
diagnostics: "诊断",
about: "关于",
},
clientHosts: {
title: "已保存的主机",
info: "此设备连接的主机。这里的名称、图标、徽章和连接路径仅影响此设备。",
backToHosts: "返回主机",
routesTitle: "此设备的连接方式",
routesInfo: "此设备连接到该主机的已保存路径。Paseo 会自动选择最快的可用路径。",
addRoute: "添加路径",
activeRoute: "当前使用",
},
layout: en.settings.layout,
editor: {
title: "编辑器",
@@ -2433,7 +2420,6 @@ export const zhCN: TranslationResources = {
projects: "项目",
connections: "连接",
agents: "Agents",
tools: "工具与提示词",
agentProfiles: "智能体配置文件",
metadata: "元数据",
voice: "语音",
@@ -2443,7 +2429,6 @@ export const zhCN: TranslationResources = {
terminals: "Terminals",
plugins: "插件",
host: "概览",
daemon: "守护进程",
},
plugins: pluginSettings["zh-CN"],
metadataGeneration: {
@@ -2974,10 +2959,6 @@ export const zhCN: TranslationResources = {
delete: "删除 skill",
},
},
tools: {
instructionsTitle: "指令",
toolsTitle: "代理工具",
},
orchestration: {
title: "编排",
unavailable: "连接到这个 Host 以管理编排",
@@ -3104,7 +3085,6 @@ export const zhCN: TranslationResources = {
},
},
daemon: {
runtimeTitle: "代理运行时",
rename: {
editLabel: "编辑标签",
title: "重命名 Host",
@@ -4,14 +4,12 @@ import {
navigateToLastWorkspace,
} from "@/stores/navigation-active-workspace-store";
import {
buildClientHostSettingsRoute,
buildOpenProjectRoute,
buildProjectSettingsRoute,
buildProjectsSettingsRoute,
buildProviderSettingsRoute,
buildSettingsHostSectionRoute,
buildSettingsRoute,
buildSettingsSectionRoute,
type HostSectionSlug,
type SettingsSectionSlug,
} from "@/utils/host-routes";
@@ -42,17 +40,12 @@ export type SettingsView =
| { kind: "pluginListing"; serverId: string; listingId: string }
| { kind: "root" }
| { kind: "section"; section: SettingsSectionSlug }
| { kind: "clientHost"; serverId: string }
| { kind: "host"; serverId: string; section: HostSectionSlug }
| { kind: "project"; serverId: string; projectId: string }
| { kind: "provider"; serverId: string; providerId: string };
export function openHostOverview(serverId: string): void {
router.push(buildSettingsHostSectionRoute(serverId, "daemon"));
}
export function openClientHostSettings(serverId: string): void {
router.push(buildClientHostSettingsRoute(serverId));
router.push(buildSettingsHostSectionRoute(serverId, "host"));
}
export function openProjectSettings(serverId: string, projectId: string): void {
@@ -84,7 +77,6 @@ export function returnFromSettings(view: SettingsView): void {
}
let parent: Href = buildSettingsRoute();
if (view.kind === "clientHost") parent = buildSettingsSectionRoute("hosts");
if (view.kind === "plugin" || view.kind === "pluginListing")
parent = buildSettingsHostSectionRoute(view.serverId, "plugins");
if (view.kind === "project") parent = buildProjectsSettingsRoute(view.serverId);
+6 -33
View File
@@ -66,7 +66,6 @@ import {
type AgentScreenReadySyncState,
} from "@/hooks/use-agent-screen-state-machine";
import { useArchiveAgent } from "@/hooks/use-archive-agent";
import { useWorkspaceArchiveUndoRestoringAgent } from "@/workspace/archive-undo";
import { useStableEvent } from "@/hooks/use-stable-event";
import { useContainerWidthBelow } from "@/hooks/use-container-width";
import { reconcileMissingAgentStateWithPresentAgent } from "@/panels/agent-panel-load-state";
@@ -722,22 +721,10 @@ function ChatAgentContent({
const historySyncGeneration = useSessionStore(
(state) => state.sessions[serverId]?.historySyncGeneration ?? 0,
);
const { replicaTimelineStatus, hasImmediatelyRevealableHistory } = useSessionStore(
useShallow((state) => {
if (!agentId) {
return {
replicaTimelineStatus: "cold" as const,
hasImmediatelyRevealableHistory: false,
};
}
const timeline = selectAgentTimelineState(state.sessions[serverId], agentId);
return {
replicaTimelineStatus: timeline.status,
hasImmediatelyRevealableHistory:
timeline.status === "painted" ||
(timeline.status === "synced" && timeline.older === "none"),
};
}),
const replicaTimelineStatus = useSessionStore((state) =>
agentId
? selectAgentTimelineState(state.sessions[serverId], agentId).status
: ("cold" as const),
);
const hasAppliedAuthoritativeHistory = replicaTimelineStatus === "synced";
const agentHistorySyncGeneration = useSessionStore((state) =>
@@ -1034,7 +1021,7 @@ function ChatAgentContent({
effectiveAgent={effectiveAgent}
routeBottomAnchorRequest={routeBottomAnchorRequest}
hasAppliedAuthoritativeHistory={hasAppliedAuthoritativeHistory}
hasCachedHistory={hasImmediatelyRevealableHistory}
hasCachedHistory={replicaTimelineStatus === "painted"}
toastApi={toastApi}
toast={toastState}
dismiss={dismissToast}
@@ -1117,11 +1104,6 @@ const ChatAgentReadyContent = memo(function ChatAgentReadyContent({
// The dock lays out fullscreen for the same session the composer edits in.
const composerEditingSession = useComposerEditingSession("chat");
const isComposerFullscreen = useComposerFullscreen(composerEditingSession);
const isWorkspaceRestoring = useWorkspaceArchiveUndoRestoringAgent({
serverId,
workspaceId,
agentId,
});
const hasActiveComposer = !agentState.archivedAt && !isArchivingCurrentAgent;
const focusRestoredComposer = useStableEvent(() => {
if (isPaneFocused && showsComposer && hasActiveComposer) {
@@ -1198,7 +1180,6 @@ const ChatAgentReadyContent = memo(function ChatAgentReadyContent({
serverId={serverId}
isPaneFocused={isPaneFocused}
isArchivingCurrentAgent={isArchivingCurrentAgent}
isWorkspaceRestoring={isWorkspaceRestoring}
archivedAt={agentState.archivedAt}
cwd={cwd}
isSubmitLoading={false}
@@ -1590,7 +1571,6 @@ const AgentComposerSection = memo(function AgentComposerSection({
serverId,
isPaneFocused,
isArchivingCurrentAgent,
isWorkspaceRestoring,
archivedAt,
cwd,
isSubmitLoading,
@@ -1605,7 +1585,6 @@ const AgentComposerSection = memo(function AgentComposerSection({
serverId: string;
isPaneFocused: boolean;
isArchivingCurrentAgent: boolean;
isWorkspaceRestoring: boolean;
archivedAt: Date | null;
cwd: string;
isSubmitLoading: boolean;
@@ -1620,13 +1599,7 @@ const AgentComposerSection = memo(function AgentComposerSection({
return null;
}
if (archivedAt) {
return (
<ArchivedAgentCallout
serverId={serverId}
agentId={agentId}
isWorkspaceRestoring={isWorkspaceRestoring}
/>
);
return <ArchivedAgentCallout serverId={serverId} agentId={agentId} />;
}
if (isArchivingCurrentAgent) {
return null;
@@ -6,7 +6,6 @@ import { buildAgentDirectoryState, type AgentDirectoryDelta } from "@/utils/agen
import { derivePendingPermissionKey, normalizeAgentSnapshot } from "@/utils/agent-snapshots";
import { resolveProjectPlacement } from "@/utils/project-placement";
import { clearArchiveAgentPending } from "@/hooks/use-archive-agent";
import { clearUnarchiveAgentPending } from "@/stores/unarchive-agent-store";
import { queryClient } from "@/data/query-client";
import { buildDraftStoreKey } from "@/stores/draft-keys";
import { useDraftStore } from "@/stores/draft-store";
@@ -78,8 +77,7 @@ export class AgentStoreProjection {
accept(agent: Agent): Agent {
let accepted = agent;
const store = useSessionStore.getState();
store.setAgents(this.serverId, (current) => {
useSessionStore.getState().setAgents(this.serverId, (current) => {
const previous = current.get(agent.id);
const winner = acceptAgentDirectoryUpdate(previous, mergeSnapshotTurn(previous, agent));
accepted = previous ? keepUnchangedFields(previous, winner) : winner;
@@ -88,10 +86,6 @@ export class AgentStoreProjection {
next.set(agent.id, accepted);
return next;
});
if (!accepted.archivedAt) {
clearUnarchiveAgentPending({ serverId: this.serverId, agentId: accepted.id });
store.setAgentDetails(this.serverId, withoutAgent(accepted.id));
}
return accepted;
}
@@ -147,8 +141,6 @@ export class AgentStoreProjection {
agents.set(agentId, existing ? keepUnchangedFields(existing, merged) : merged);
if (fetchedAgent.archivedAt) {
clearArchiveAgentPending({ queryClient, serverId: this.serverId, agentId });
} else {
clearUnarchiveAgentPending({ serverId: this.serverId, agentId });
}
}
store.setAgents(this.serverId, agents);
@@ -184,15 +176,7 @@ export class AgentStoreProjection {
const removeKey = withoutAgent(agentId);
clearArchiveAgentPending({ queryClient, serverId: this.serverId, agentId });
store.setAgents(this.serverId, removeKey);
// Leaving the active directory (for example an archived agent loaded for history) must not
// wipe an archived detail snapshot that an open pane is currently displaying.
store.setAgentDetails(this.serverId, (current) => {
const existing = current.get(agentId);
if (!existing || existing.archivedAt != null) return current;
const next = new Map(current);
next.delete(agentId);
return next;
});
store.setAgentDetails(this.serverId, removeKey);
store.setQueuedMessages(this.serverId, removeKey);
store.setInitializingAgents(this.serverId, removeKey);
store.setPendingPermissions(this.serverId, (current) => {
@@ -214,7 +198,6 @@ export class AgentStoreProjection {
remove(agentId: string): void {
this.removeFromDirectory(agentId);
useSessionStore.getState().setAgentDetails(this.serverId, withoutAgent(agentId));
useDraftStore.getState().clearDraftInput({
draftKey: buildDraftStoreKey({ serverId: this.serverId, agentId }),
});
@@ -1,90 +0,0 @@
import { expect, it } from "vitest";
import { normalizeProjectDescriptor, normalizeWorkspaceDescriptor } from "@/stores/session-store";
import { ReplicaCache } from ".";
import { createIndexedDbReplicaRowStore } from "./row-store.web";
const SERVER_ID = "shared-host";
const noLegacyCleanup = { clearLegacyCache: async () => undefined };
// Each browser tab opens its own ReplicaCache over the same IndexedDB database.
function openTab(databaseName: string, maxBytes?: number): ReplicaCache {
const store = createIndexedDbReplicaRowStore({ databaseName, schemaVersion: 1 });
const cache = new ReplicaCache(store, { ...noLegacyCleanup, ...(maxBytes ? { maxBytes } : {}) });
cache.setHosts([SERVER_ID]);
return cache;
}
function workspace(name: string) {
return normalizeWorkspaceDescriptor({
id: "workspace-1",
projectId: "project-1",
projectDisplayName: "Paseo",
projectRootPath: "/repo/paseo",
workspaceDirectory: "/repo/paseo",
projectKind: "git",
workspaceKind: "local_checkout",
name,
status: "running",
statusEnteredAt: "2026-07-18T08:00:00.000Z",
activityAt: null,
archivingAt: null,
diffStat: null,
scripts: [],
});
}
const project = normalizeProjectDescriptor({
projectId: "project-1",
projectDisplayName: "Paseo",
projectRootPath: "/repo/paseo",
projectKind: "git",
});
const checkpoint = {
projects: { generation: "g", afterSeq: 31 },
workspaces: { generation: "g:background", afterSeq: 1494 },
};
// #10206: one tab evicts the host while another tab keeps writing directory deltas.
it("does not store a checkpoint for rows that another tab evicted", async () => {
const databaseName = `replica-cross-tab-${crypto.randomUUID()}`;
const syncingTab = openTab(databaseName);
syncingTab.replaceDirectoryBaseline(SERVER_ID, {
agents: new Map(),
workspaces: new Map([["workspace-1", workspace("main")]]),
projects: new Map([["project-1", project]]),
checkpoint,
});
await syncingTab.flush();
const evictingTab = openTab(databaseName, 8_192);
await evictingTab.readDirectory(SERVER_ID);
evictingTab.commitTimeline(SERVER_ID, "agent-1", {
agentId: "agent-1",
items: [
{
kind: "assistant_message",
id: "message-1",
text: "x".repeat(16_384),
timestamp: new Date("2026-07-18T08:02:00.000Z"),
timelineCursor: { epoch: "epoch-1", seq: 12 },
},
],
range: { epoch: "epoch-1", startSeq: 1, endSeq: 12 },
hasOlder: false,
});
await evictingTab.flush();
expect((await openTab(databaseName).readDirectory(SERVER_ID)).checkpoint).toBeUndefined();
syncingTab.commitDirectoryMutations(
SERVER_ID,
[{ kind: "workspace", type: "upsert", id: "workspace-1", value: workspace("renamed") }],
{ ...checkpoint, workspaces: { generation: "g:background", afterSeq: 1495 } },
);
await syncingTab.flush();
// The second tab wrote over a directory it never saw evicted, so the store rejected the write.
const newTab = await openTab(databaseName).readDirectory(SERVER_ID);
expect(newTab.projects.size).toBe(0);
expect(newTab.checkpoint).toBeUndefined();
});
+10 -20
View File
@@ -402,9 +402,9 @@ const DirectoryCheckpointSchema = z.strictObject({
// A checkpoint is trusted only when this version wrote it. Earlier writers could store one for a
// directory the cache no longer held: unversioned ones after an overlapping refresh, version 1
// after an eviction, version 2 after another tab evicted the host. Rejecting them revalidates
// directory contents once without evicting cached rows or timelines.
const DIRECTORY_CHECKPOINT_VERSION = 3;
// after an eviction. Rejecting them revalidates directory contents once without evicting cached
// rows or timelines.
const DIRECTORY_CHECKPOINT_VERSION = 2;
const StoredDirectoryCheckpointSchema = z.strictObject({
version: z.literal(DIRECTORY_CHECKPOINT_VERSION),
@@ -1180,12 +1180,11 @@ export class ReplicaCache {
// A repair is queued behind writes that can evict its host. If one did, the host has no
// directory left for the repaired checkpoint to describe, so only the deletes still apply.
// A shared store also rejects the repair when another connection rewrote the directory.
private applyRepair(serverId: string, changes: ReplicaRowChanges): Promise<void> {
return this.queueOperation(async () => {
const applied = this.invalidatedHosts.has(serverId) ? { ...changes, upserts: [] } : changes;
const accepted = await this.rowStore.apply(applied, { directoryBaselines: new Set() });
this.applyStoredChanges(accepted ?? applied);
await this.rowStore.apply(applied);
this.applyStoredChanges(applied);
});
}
@@ -1324,21 +1323,12 @@ export class ReplicaCache {
await this.ensureStoredIndex();
const changes = this.materializePendingChanges(pending);
const { changes: boundedChanges, evicted } = await this.fitChangesToBudget(changes);
const baselines = new Set(
[...pending.baselines].filter((serverId) => !evicted.has(serverId)),
);
if (
baselines.size > 0 ||
boundedChanges.upserts.length > 0 ||
boundedChanges.deletes.length > 0
) {
const accepted = await this.rowStore.apply(boundedChanges, {
directoryBaselines: baselines,
});
this.applyStoredChanges(accepted ?? boundedChanges);
if (boundedChanges.upserts.length > 0 || boundedChanges.deletes.length > 0) {
await this.rowStore.apply(boundedChanges);
this.applyStoredChanges(boundedChanges);
}
for (const serverId of baselines) {
this.invalidatedHosts.delete(serverId);
for (const serverId of pending.baselines) {
if (!evicted.has(serverId)) this.invalidatedHosts.delete(serverId);
}
} catch {
this.restorePendingChanges(pending);
@@ -17,12 +17,6 @@ export interface ReplicaRowChanges {
deletes: ReplicaRowKey[];
}
export interface ReplicaRowApplyOptions {
// Hosts whose whole directory these changes replace. Passing the option, even empty, asks a
// shared store to reject directory changes for hosts another connection rewrote since.
directoryBaselines?: ReadonlySet<string>;
}
export interface ReplicaHostRows {
serverId: string;
rows: ReplicaRow[];
@@ -36,12 +30,7 @@ export interface ReplicaRowStore {
ids?: readonly string[],
): Promise<ReplicaRow[]>;
readAll(): Promise<ReplicaHostRows[]>;
// Shared stores can reject directory deltas that no longer match their baseline.
// Return the accepted changes when they differ from the requested changes.
apply(
changes: ReplicaRowChanges,
options?: ReplicaRowApplyOptions,
): Promise<ReplicaRowChanges | void>;
apply(changes: ReplicaRowChanges): Promise<void>;
deleteHost(serverId: string): Promise<void>;
renameHost(oldServerId: string, newServerId: string): Promise<void>;
clear(): Promise<void>;
@@ -1,48 +0,0 @@
import { expect, it } from "vitest";
import { createIndexedDbReplicaRowStore } from "./row-store.web";
import { REPLICA_SINGLETON_ROW_ID, type ReplicaRow } from "./row-store";
it("rejects directory deltas from a connection whose shared baseline was evicted", async () => {
const databaseName = `replica-eviction-${crypto.randomUUID()}`;
const first = createIndexedDbReplicaRowStore({ databaseName, schemaVersion: 1 });
const second = createIndexedDbReplicaRowStore({ databaseName, schemaVersion: 1 });
const serverId = "host";
const kinds = ["agent", "checkpoint", "project", "workspace"] as const;
const checkpoint: ReplicaRow = {
serverId,
kind: "checkpoint",
id: REPLICA_SINGLETON_ROW_ID,
payload: "checkpoint",
};
const project: ReplicaRow = { serverId, kind: "project", id: "project", payload: "project" };
const workspace: ReplicaRow = {
serverId,
kind: "workspace",
id: "workspace",
payload: "workspace",
};
const timeline: ReplicaRow = { serverId, kind: "timeline", id: "agent", payload: "timeline" };
const replace = { directoryBaselines: new Set([serverId]) };
const delta = {
upserts: [checkpoint, { ...workspace, payload: "updated workspace" }, timeline],
deletes: [],
};
const incremental = { directoryBaselines: new Set<string>() };
const baseline = { upserts: [checkpoint, project, workspace], deletes: [] };
await first.open();
await second.open();
await first.apply(baseline, replace);
expect(await second.read(serverId, kinds)).toEqual([checkpoint, project, workspace]);
await second.apply(delta, incremental);
expect(await first.read(serverId, kinds)).toEqual([checkpoint, project, delta.upserts[1]]);
await first.deleteHost(serverId);
await second.apply(delta, incremental);
expect(await first.read(serverId, kinds)).toEqual([]);
expect(await first.read(serverId, ["timeline"])).toEqual([timeline]);
await first.apply(baseline, replace);
await second.apply(delta, incremental);
expect(await first.read(serverId, kinds)).toEqual([checkpoint, project, workspace]);
});
@@ -1,11 +1,5 @@
import type {
ReplicaHostRows,
ReplicaRow,
ReplicaRowApplyOptions,
ReplicaRowChanges,
ReplicaRowStore,
} from "./row-store";
import { REPLICA_ROW_STORE_SCHEMA_VERSION, REPLICA_SINGLETON_ROW_ID } from "./row-store-schema";
import type { ReplicaHostRows, ReplicaRow, ReplicaRowChanges, ReplicaRowStore } from "./row-store";
import { REPLICA_ROW_STORE_SCHEMA_VERSION } from "./row-store-schema";
export type {
ReplicaHostRows,
@@ -22,16 +16,6 @@ const DATABASE_VERSION = 1;
const ROWS_STORE = "rows";
const META_STORE = "meta";
const SCHEMA_VERSION_KEY = "schema_version";
const DIRECTORY_KINDS = ["agent", "checkpoint", "project", "workspace"] as const;
interface IndexedDbReplicaRow extends ReplicaRow {
directoryRevision?: string;
}
function withoutDirectoryRevision(row: IndexedDbReplicaRow): ReplicaRow {
if (row.directoryRevision === undefined) return row;
return { serverId: row.serverId, kind: row.kind, id: row.id, payload: row.payload };
}
interface IndexedDbReplicaRowStoreOptions {
databaseName: string;
@@ -107,12 +91,6 @@ export function createIndexedDbReplicaRowStore(
): ReplicaRowStore {
let database: IDBDatabase | null = null;
let opening: Promise<void> | null = null;
const observedDirectoryRevisions = new Map<string, string>();
function observeDirectoryRevision(serverId: string, revision: string | undefined): void {
if (revision === undefined) observedDirectoryRevisions.delete(serverId);
else observedDirectoryRevisions.set(serverId, revision);
}
function getDatabase(): IDBDatabase {
if (!database) throw new Error("Replica row store has not been opened");
@@ -147,14 +125,12 @@ export function createIndexedDbReplicaRowStore(
async function readAll(): Promise<ReplicaHostRows[]> {
const transaction = getDatabase().transaction(ROWS_STORE, "readonly");
const completion = transactionComplete(transaction);
const rows = await requestResult<IndexedDbReplicaRow[]>(
transaction.objectStore(ROWS_STORE).getAll(),
);
const rows = await requestResult<ReplicaRow[]>(transaction.objectStore(ROWS_STORE).getAll());
await completion;
const hosts = new Map<string, ReplicaRow[]>();
for (const row of rows) {
const hostRows = hosts.get(row.serverId) ?? [];
hostRows.push(withoutDirectoryRevision(row));
hostRows.push(row);
hosts.set(row.serverId, hostRows);
}
return Array.from(hosts, ([serverId, hostRows]) => ({ serverId, rows: hostRows }));
@@ -172,127 +148,36 @@ export function createIndexedDbReplicaRowStore(
const requests = ids
? kinds.flatMap((kind) =>
ids.map(async (id) => {
const row = await requestResult<IndexedDbReplicaRow | undefined>(
const row = await requestResult<ReplicaRow | undefined>(
store.get([serverId, kind, id]),
);
return row ? [row] : [];
}),
)
: kinds.map((kind) =>
requestResult<IndexedDbReplicaRow[]>(
requestResult<ReplicaRow[]>(
store.getAll(IDBKeyRange.bound([serverId, kind], [serverId, kind, []])),
),
);
const rows = (await Promise.all(requests)).flat();
await completion;
if (!ids && DIRECTORY_KINDS.every((kind) => kinds.includes(kind))) {
const checkpoint = rows.find(
(row) => row.kind === "checkpoint" && row.id === REPLICA_SINGLETON_ROW_ID,
);
observeDirectoryRevision(serverId, checkpoint?.directoryRevision);
}
return rows
.map(withoutDirectoryRevision)
.sort((left, right) =>
left.kind === right.kind
? left.id.localeCompare(right.id)
: left.kind.localeCompare(right.kind),
);
return rows.sort((left, right) =>
left.kind === right.kind
? left.id.localeCompare(right.id)
: left.kind.localeCompare(right.kind),
);
}
async function apply(
changes: ReplicaRowChanges,
{ directoryBaselines }: ReplicaRowApplyOptions = {},
): Promise<ReplicaRowChanges | void> {
let accepted = changes;
const nextRevisions = new Map<string, string | undefined>();
async function apply(changes: ReplicaRowChanges): Promise<void> {
await runTransaction(getDatabase(), ROWS_STORE, async (transaction) => {
const rows = transaction.objectStore(ROWS_STORE);
if (directoryBaselines) {
accepted = await prepareDirectoryWrite({
rows,
changes,
directoryBaselines,
nextRevisions,
});
}
for (const key of accepted.deletes) {
for (const key of changes.deletes) {
await requestResult(rows.delete([key.serverId, key.kind, key.id]));
}
for (const row of accepted.upserts) {
const directoryRevision =
row.kind === "checkpoint" ? nextRevisions.get(row.serverId) : undefined;
await requestResult(rows.put(directoryRevision ? { ...row, directoryRevision } : row));
for (const row of changes.upserts) {
await requestResult(rows.put(row));
}
});
for (const [serverId, revision] of nextRevisions) observeDirectoryRevision(serverId, revision);
return accepted === changes ? undefined : accepted;
}
async function prepareDirectoryWrite(input: {
rows: IDBObjectStore;
changes: ReplicaRowChanges;
directoryBaselines: ReadonlySet<string>;
nextRevisions: Map<string, string | undefined>;
}): Promise<ReplicaRowChanges> {
const { rows, changes, directoryBaselines, nextRevisions } = input;
const hosts = new Set(directoryBaselines);
const checkpoints = new Map<string, ReplicaRow>();
for (const row of changes.upserts) {
if (row.kind !== "timeline") hosts.add(row.serverId);
if (row.kind === "checkpoint") checkpoints.set(row.serverId, row);
}
for (const row of changes.deletes) {
if (row.kind !== "timeline") hosts.add(row.serverId);
}
const staleHosts = new Set<string>();
const unbasedHosts = new Set<string>();
for (const serverId of hosts) {
const replacingBaseline = directoryBaselines.has(serverId);
const current = replacingBaseline
? undefined
: await requestResult<IndexedDbReplicaRow | undefined>(
rows.get([serverId, "checkpoint", REPLICA_SINGLETON_ROW_ID]),
);
if (replacingBaseline) {
// A different tab may have added directory rows since this tab indexed the cache.
for (const kind of DIRECTORY_KINDS) {
await requestResult(
rows.delete(IDBKeyRange.bound([serverId, kind], [serverId, kind, []])),
);
}
} else if (current?.directoryRevision !== observedDirectoryRevisions.get(serverId)) {
staleHosts.add(serverId);
continue;
} else if (!current?.directoryRevision) {
// Targeted lookups can still use these rows, but they do not form a baseline.
unbasedHosts.add(serverId);
continue;
}
// Rotate the revision even on row-only writes. A tab that missed those changes
// must not publish a checkpoint over them.
const checkpoint = checkpoints.get(serverId);
const revision =
checkpoint || current ? crypto.getRandomValues(new Uint32Array(4)).join(":") : undefined;
nextRevisions.set(serverId, revision);
if (!checkpoint && current) {
await requestResult(rows.put({ ...current, directoryRevision: revision }));
}
}
if (staleHosts.size === 0 && unbasedHosts.size === 0) return changes;
return {
deletes: changes.deletes.filter(
(row) => row.kind === "timeline" || !staleHosts.has(row.serverId),
),
upserts: changes.upserts.filter(
(row) =>
row.kind === "timeline" ||
(!staleHosts.has(row.serverId) &&
(row.kind !== "checkpoint" || !unbasedHosts.has(row.serverId))),
),
};
}
async function deleteHost(serverId: string): Promise<void> {
@@ -314,11 +199,6 @@ export function createIndexedDbReplicaRowStore(
await requestResult(rows.delete([row.serverId, row.kind, row.id]));
}
});
const revision = observedDirectoryRevisions.get(oldServerId);
if (revision !== undefined) {
observedDirectoryRevisions.delete(oldServerId);
observeDirectoryRevision(newServerId, revision);
}
}
async function clear(): Promise<void> {
+186 -111
View File
@@ -18,24 +18,30 @@ import {
Settings,
Palette,
Server,
Network,
Bot,
Boxes,
Gauge,
Keyboard,
Stethoscope,
Info,
Bell,
Shield,
Puzzle,
Plus,
FolderOpen,
FolderGit2,
SquareTerminal,
Code2,
Files,
Smartphone,
Sparkles,
Mic,
Blocks,
Globe,
PanelLeft,
MessageSquare,
ChevronRight,
Layers,
Laptop,
} from "lucide-react-native";
import { DropdownTrigger } from "@/components/ui/dropdown-trigger";
import { ComboboxTrigger } from "@/components/ui/combobox-trigger";
@@ -55,7 +61,8 @@ import {
type AppSettings,
type Settings as EffectiveSettings,
} from "@/hooks/use-settings";
import { useHosts } from "@/runtime/host-runtime";
import { useHostRuntimeIsConnected, useHosts } from "@/runtime/host-runtime";
import { useSessionStore } from "@/stores/session-store";
import {
orderHostsLocalFirst,
resolveActiveHostServerId,
@@ -95,22 +102,23 @@ import {
type SupportedLocale,
} from "@/i18n/locales";
import {
HostConnectionsPage,
HostDevicesPage,
HostToolsPage,
HostAgentsPage,
HostAgentProfilesPage,
HostDaemonPage,
HostWorkspacesPage,
HostSettingsPage,
HostProvidersPage,
HostUsagePage,
HostWorkspacesPage,
HostTerminalsPage,
} from "@/screens/settings/host-page";
import { ClientHostDetailPage, ClientHostsSection } from "@/screens/settings/client-hosts-page";
import {
PluginGalleryMenu,
PluginGalleryPage,
PluginPage,
type PluginPageSubject,
} from "@/plugins/gallery";
import { MetadataGenerationPage } from "@/screens/settings/metadata-generation-page";
import { HostVoicePage } from "@/screens/settings/voice/voice-page";
import ProjectsScreen from "@/screens/projects-screen";
import ProjectSettingsScreen from "@/screens/project-settings-screen";
@@ -127,7 +135,6 @@ import {
useEnableBuiltInDaemonOption,
} from "@/desktop/hooks/use-enable-built-in-daemon-option";
import {
buildClientHostSettingsRoute,
buildSettingsHostSectionRoute,
buildSettingsSectionRoute,
type HostSectionSlug,
@@ -159,7 +166,6 @@ interface SidebarSectionItem {
const SIDEBAR_SECTION_ITEMS: SidebarSectionItem[] = [
{ id: "general", labelKey: "settings.sections.general", icon: Settings },
{ id: "hosts", labelKey: "settings.sections.hosts", icon: Laptop },
{
id: "appearance",
labelKey: "settings.sections.appearance",
@@ -172,7 +178,28 @@ const SIDEBAR_SECTION_ITEMS: SidebarSectionItem[] = [
icon: PanelLeft,
Content: SidebarNavSection,
},
{ id: "chat", labelKey: "settings.sections.chatAndPanes", icon: MessageSquare },
{ id: "chat", labelKey: "settings.sections.chat", icon: MessageSquare, Content: ChatSection },
{
id: "terminal",
labelKey: "settings.sections.terminal",
icon: SquareTerminal,
Content: TerminalSection,
},
{
id: "browser",
labelKey: "settings.sections.browser",
icon: Globe,
desktopOnly: true,
Content: BrowserDataSection,
},
{
id: "editor",
labelKey: "settings.sections.editor",
icon: Code2,
webOnly: true,
Content: EditorSection,
},
{ id: "files", labelKey: "settings.sections.files", icon: Files, Content: FilesSection },
{
id: "shortcuts",
labelKey: "settings.sections.shortcuts",
@@ -180,12 +207,28 @@ const SIDEBAR_SECTION_ITEMS: SidebarSectionItem[] = [
hardwareKeyboardOnly: true,
Content: KeyboardShortcutsSection,
},
{
id: "integrations",
labelKey: "settings.sections.integrations",
icon: Puzzle,
desktopOnly: true,
Content: IntegrationsSection,
},
{
id: "notifications",
labelKey: "settings.sections.notifications",
icon: Bell,
desktopOnly: true,
Content: DesktopNotificationsSection,
},
{
id: "permissions",
labelKey: "settings.sections.permissions",
icon: Shield,
desktopOnly: true,
Content: DesktopPermissionsSection,
},
{ id: "diagnostics", labelKey: "settings.sections.diagnostics", icon: Stethoscope },
{ id: "about", labelKey: "settings.sections.about", icon: Info },
];
@@ -205,44 +248,53 @@ interface HostSectionItem {
}
const HOST_SECTION_ITEMS: HostSectionItem[] = [
{ id: "providers", labelKey: "settings.hostSections.providers", icon: Boxes },
{ id: "host", labelKey: "settings.hostSections.host", icon: Server },
{ id: "projects", labelKey: "settings.hostSections.projects", icon: FolderGit2 },
{ id: "connections", labelKey: "settings.hostSections.connections", icon: Network },
{ id: "devices", labelKey: "devices.title", icon: Smartphone },
{ id: "agents", labelKey: "settings.hostSections.agents", icon: Bot },
{ id: "agent-profiles", labelKey: "settings.hostSections.agentProfiles", icon: Layers },
{ id: "tools", labelKey: "settings.hostSections.tools", icon: Sparkles },
{ id: "projects", labelKey: "settings.projects", icon: FolderOpen },
{ id: "workspaces", labelKey: "settings.hostSections.workspaces", icon: FolderGit2 },
{ id: "metadata", labelKey: "settings.hostSections.metadata", icon: Sparkles },
{ id: "voice", labelKey: "settings.hostSections.voice", icon: Mic },
{ id: "workspaces", labelKey: "settings.hostSections.workspaces", icon: FolderGit2 },
{ id: "providers", labelKey: "settings.hostSections.providers", icon: Boxes },
{ id: "usage", labelKey: "settings.hostSections.usage", icon: Gauge },
{ id: "terminals", labelKey: "settings.hostSections.terminals", icon: SquareTerminal },
{ id: "plugins", labelKey: "settings.hostSections.plugins", icon: Blocks },
{ id: "devices", labelKey: "devices.title", icon: Smartphone },
{ id: "daemon", labelKey: "settings.hostSections.daemon", icon: Server },
];
function renderHostSettingsContent(view: Extract<SettingsView, { kind: "host" }>): ReactNode {
function renderHostSettingsContent(
view: Extract<SettingsView, { kind: "host" }>,
onHostRemoved: () => void,
): ReactNode {
switch (view.section) {
case "providers":
return <HostProvidersPage serverId={view.serverId} />;
case "projects":
return <ProjectsScreen serverId={view.serverId} />;
case "connections":
return <HostConnectionsPage serverId={view.serverId} />;
case "devices":
return <HostDevicesPage serverId={view.serverId} />;
case "agents":
return <HostAgentsPage serverId={view.serverId} />;
case "agent-profiles":
// Rendered directly in SettingsScreen so AgentProfilesPage owns its wide PageLayout + drawer split.
return null;
case "tools":
return <HostToolsPage serverId={view.serverId} />;
case "projects":
return <ProjectsScreen serverId={view.serverId} />;
case "workspaces":
return <HostWorkspacesPage serverId={view.serverId} />;
case "metadata":
return <MetadataGenerationPage serverId={view.serverId} />;
case "voice":
return <HostVoicePage serverId={view.serverId} />;
case "workspaces":
return <HostWorkspacesPage serverId={view.serverId} />;
case "providers":
return <HostProvidersPage serverId={view.serverId} />;
case "usage":
return <HostUsagePage serverId={view.serverId} />;
case "terminals":
return <HostTerminalsPage serverId={view.serverId} />;
case "plugins":
return <PluginGalleryPage serverId={view.serverId} />;
case "devices":
return <HostDevicesPage serverId={view.serverId} />;
case "daemon":
return <HostDaemonPage serverId={view.serverId} />;
case "host":
return <HostSettingsPage serverId={view.serverId} onHostRemoved={onHostRemoved} />;
}
}
@@ -424,12 +476,12 @@ function DiagnosticsSection({
}
interface AboutSectionProps {
appVersion: string | null;
appVersionText: string;
isDesktopApp: boolean;
diagnostics: DiagnosticsSectionProps;
}
function AboutSection({ appVersionText, isDesktopApp, diagnostics }: AboutSectionProps) {
function AboutSection({ appVersion, appVersionText, isDesktopApp }: AboutSectionProps) {
const { t } = useTranslation();
return (
<>
@@ -446,7 +498,7 @@ function AboutSection({ appVersionText, isDesktopApp, diagnostics }: AboutSectio
{isDesktopApp ? <DesktopAppUpdateRow /> : null}
</View>
</SettingsSection>
<DiagnosticsSection {...diagnostics} />
<ConnectedHostsSection clientVersion={appVersion} />
<View style={styles.aboutCommunity}>
<CommunityLinks />
</View>
@@ -481,6 +533,88 @@ function WhatsNewRow() {
);
}
function normalizeVersion(version: string | null | undefined): string | null {
const trimmed = version?.trim();
if (!trimmed) return null;
return trimmed.replace(/^v/i, "");
}
function ConnectedHostsSection({ clientVersion }: { clientVersion: string | null }) {
const { t } = useTranslation();
const hosts = useHosts();
if (hosts.length === 0) {
return null;
}
return (
<SettingsSection title={t("settings.about.connectedHosts")}>
<View style={settingsStyles.card}>
{hosts.map((host, index) => (
<HostVersionRow
key={host.serverId}
host={host}
showBorder={index > 0}
clientVersion={clientVersion}
/>
))}
</View>
</SettingsSection>
);
}
function HostVersionRow({
host,
showBorder,
clientVersion,
}: {
host: HostProfile;
showBorder: boolean;
clientVersion: string | null;
}) {
const { t } = useTranslation();
const isConnected = useHostRuntimeIsConnected(host.serverId);
const daemonVersion = useSessionStore(
(state) => state.sessions[host.serverId]?.serverInfo?.version ?? null,
);
const rowStyle = useMemo(
() => [settingsStyles.row, showBorder && settingsStyles.rowBorder],
[showBorder],
);
const normalizedHost = normalizeVersion(daemonVersion);
const normalizedClient = normalizeVersion(clientVersion);
const isMismatch =
normalizedHost !== null && normalizedClient !== null && normalizedHost !== normalizedClient;
let valueText: string;
if (!isConnected) {
valueText = t("settings.about.offline");
} else if (normalizedHost) {
valueText = formatVersionWithPrefix(normalizedHost);
} else {
valueText = "—";
}
const valueStyle = useMemo(
() => [styles.aboutValue, isMismatch && styles.aboutVersionMismatch],
[isMismatch],
);
return (
<View style={rowStyle}>
<View style={settingsStyles.rowContent}>
<Text style={settingsStyles.rowTitle} numberOfLines={1}>
{host.label}
</Text>
{isMismatch ? (
<Text style={settingsStyles.rowHint}>{t("settings.about.versionDiffers")}</Text>
) : null}
</View>
<Text style={valueStyle}>{valueText}</Text>
</View>
);
}
function getUpdateButtonLabel(
t: TFunction,
input: {
@@ -768,7 +902,6 @@ function SidebarSectionButton({
accessibilityRole="button"
accessibilityState={accessibilityState}
onPress={handlePress}
testID={`settings-section-${itemId}`}
style={isSelected ? selectedSidebarItemStyle : sidebarItemStyle}
>
<IconComponent
@@ -964,12 +1097,7 @@ function SettingsSidebar({
() => [{ flex: 1 }, isDesktop ? { paddingTop: insets.top } : null],
[insets.top, isDesktop],
);
let selectedSectionId: SettingsSectionSlug | null = null;
if (view.kind === "section") {
selectedSectionId = view.section;
} else if (view.kind === "clientHost") {
selectedSectionId = "hosts";
}
const selectedSectionId = view.kind === "section" ? view.section : null;
let selectedHostSection: HostSectionSlug | null = null;
if (view.kind === "host") selectedHostSection = view.section;
if (view.kind === "project") selectedHostSection = "projects";
@@ -1185,8 +1313,7 @@ function SettingsDetailPane({
}) {
const isStandaloneAgentProfilesView = view.kind === "host" && view.section === "agent-profiles";
const pageTitle =
!isCompactLayout &&
(view.kind === "project" || view.kind === "provider" || view.kind === "clientHost")
!isCompactLayout && (view.kind === "project" || view.kind === "provider")
? undefined
: detailTitle;
@@ -1306,7 +1433,7 @@ export default function SettingsScreen({ view }: SettingsScreenProps) {
const handleHostAdded = useCallback(
(serverId: string) => {
selectSettingsHost(serverId);
const target = buildClientHostSettingsRoute(serverId);
const target = buildSettingsHostSectionRoute(serverId, "host");
if (isCompactLayout) {
router.push(target);
} else {
@@ -1317,7 +1444,6 @@ export default function SettingsScreen({ view }: SettingsScreenProps) {
);
const handleAddHost = useAddHost({ onAdded: handleHostAdded });
const enableBuiltInDaemonOption = useEnableBuiltInDaemonOption();
const { registerBeforeLeave, guardNavigation } = useSettingsBeforeLeaveGuard();
const navigateRoute = useCallback(
@@ -1389,32 +1515,18 @@ export default function SettingsScreen({ view }: SettingsScreenProps) {
[activeHostServerId, guardNavigation, handleAddHost, navigateRoute, view],
);
const handleSelectClientHost = useCallback(
(serverId: string) => {
const target = buildClientHostSettingsRoute(serverId);
guardNavigation(() => navigateRoute(target));
},
[guardNavigation, navigateRoute],
);
const handleHostRemoved = useCallback(() => {
const target = buildSettingsSectionRoute("hosts");
const fallback = buildSettingsSectionRoute("general");
if (isCompactLayout) {
router.dismissTo(target);
router.replace("/settings");
} else {
router.replace(target);
router.replace(fallback);
}
}, [isCompactLayout, router]);
const handleBackFromDetail = useCallback(() => {
guardNavigation(() => {
if (view.kind === "clientHost" && !isCompactLayout) {
router.replace(buildSettingsSectionRoute("hosts"));
return;
}
returnFromSettings(view);
});
}, [guardNavigation, isCompactLayout, router, view]);
guardNavigation(() => returnFromSettings(view));
}, [guardNavigation, view]);
const handleBackToWorkspace = useCallback(() => {
guardNavigation(() => returnFromSettings({ kind: "root" }));
@@ -1442,9 +1554,6 @@ export default function SettingsScreen({ view }: SettingsScreenProps) {
const item = SIDEBAR_SECTION_ITEMS.find((s) => s.id === view.section);
return item ? t(item.labelKey) : undefined;
}
if (view.kind === "clientHost") {
return t("settings.sections.hosts");
}
if (view.kind === "project") {
return t("settings.projects");
}
@@ -1462,16 +1571,6 @@ export default function SettingsScreen({ view }: SettingsScreenProps) {
// The gallery and a plugin's page share one width, so opening a plugin keeps the page edges put.
const detailWidth = pluginGalleryServerId || pluginPage ? "wide" : "default";
const aboutDiagnostics = useMemo(
() => ({
voiceAudioEngine,
isPlaybackTestRunning,
playbackTestResult,
handlePlaybackTest,
}),
[handlePlaybackTest, isPlaybackTestRunning, playbackTestResult, voiceAudioEngine],
);
const content: ReactNode = (() => {
if (pluginPage)
return (
@@ -1481,18 +1580,8 @@ export default function SettingsScreen({ view }: SettingsScreenProps) {
onBack={handleBackFromDetail}
/>
);
if (view.kind === "clientHost") {
return (
<ClientHostDetailPage
serverId={view.serverId}
onBack={handleBackFromDetail}
onAddHost={handleAddHost}
onHostRemoved={handleHostRemoved}
/>
);
}
if (view.kind === "host") {
return renderHostSettingsContent(view);
return renderHostSettingsContent(view, handleHostRemoved);
}
if (view.kind === "project") {
return (
@@ -1520,42 +1609,25 @@ export default function SettingsScreen({ view }: SettingsScreenProps) {
return (
<>
<GeneralSection settings={settings} handleLanguageChange={handleLanguageChange} />
{isDesktopApp ? <IntegrationsSection /> : null}
</>
);
case "hosts":
return (
<ClientHostsSection
onSelectHost={handleSelectClientHost}
onAddHost={handleAddHost}
enableBuiltInDaemonOption={enableBuiltInDaemonOption}
/>
);
case "chat":
return (
<>
<SendingSection />
<ChatSection />
{isDesktopApp ? <OpenLocationSection /> : null}
{isWeb ? <EditorSection /> : null}
<TerminalSection />
<FilesSection />
{isDesktopApp ? <BrowserDataSection /> : null}
</>
);
case "notifications":
case "diagnostics":
return (
<>
<DesktopNotificationsSection />
{isDesktopApp ? <DesktopPermissionsSection /> : null}
</>
<DiagnosticsSection
voiceAudioEngine={voiceAudioEngine}
isPlaybackTestRunning={isPlaybackTestRunning}
playbackTestResult={playbackTestResult}
handlePlaybackTest={handlePlaybackTest}
/>
);
case "about":
return (
<AboutSection
appVersion={appVersion}
appVersionText={appVersionText}
isDesktopApp={isDesktopApp}
diagnostics={aboutDiagnostics}
/>
);
default:
@@ -1655,6 +1727,9 @@ const styles = StyleSheet.create((theme) => ({
color: theme.colors.foregroundMuted,
fontSize: theme.fontSize.base,
},
aboutVersionMismatch: {
color: theme.colors.palette.amber[500],
},
aboutErrorText: {
color: theme.colors.palette.red[300],
fontSize: theme.fontSize.sm,
@@ -1,8 +1,7 @@
import React, { useCallback, useMemo } from "react";
import React, { useCallback } from "react";
import { Text, View } from "react-native";
import { useMutation } from "@tanstack/react-query";
import { useTranslation } from "react-i18next";
import { SettingsRow } from "@/components/settings";
import { Switch } from "@/components/ui/switch";
import { useDaemonConfig } from "@/hooks/use-daemon-config";
import { useHostRuntimeIsConnected } from "@/runtime/host-runtime";
@@ -13,7 +12,7 @@ import {
getBrowserToolsMutationViewState,
} from "./browser-tools-config";
export function BrowserToolsRow({ serverId }: { serverId: string }) {
export function BrowserToolsOptInCard({ serverId }: { serverId: string }) {
const { t } = useTranslation();
const isConnected = useHostRuntimeIsConnected(serverId);
const { config, patchConfig } = useDaemonConfig(serverId);
@@ -39,36 +38,33 @@ export function BrowserToolsRow({ serverId }: { serverId: string }) {
[mutation],
);
const hint = useMemo(
() => (
<View>
<Text style={settingsStyles.rowHint}>{state.warning}</Text>
{mutationView.loadingText ? (
<Text style={settingsStyles.rowHint} testID="host-page-browser-tools-loading">
{mutationView.loadingText}
</Text>
) : null}
</View>
),
[mutationView.loadingText, state.warning],
);
if (!state.isVisible) return null;
return (
<SettingsRow
label={state.title}
hint={hint}
error={mutationView.errorText ?? undefined}
testID="host-page-browser-tools-card"
>
<Switch
value={state.isEnabled}
onValueChange={handleValueChange}
disabled={mutationView.isSwitchDisabled}
accessibilityLabel="Enable browser tools"
testID="host-page-browser-tools-switch"
/>
</SettingsRow>
<View style={settingsStyles.card} testID="host-page-browser-tools-card">
<View style={settingsStyles.row}>
<View style={settingsStyles.rowContent}>
<Text style={settingsStyles.rowTitle}>{state.title}</Text>
<Text style={settingsStyles.rowHint}>{state.warning}</Text>
{mutationView.loadingText ? (
<Text style={settingsStyles.rowHint} testID="host-page-browser-tools-loading">
{mutationView.loadingText}
</Text>
) : null}
{mutationView.errorText ? (
<Text style={settingsStyles.rowError} testID="host-page-browser-tools-error">
{mutationView.errorText}
</Text>
) : null}
</View>
<Switch
value={state.isEnabled}
onValueChange={handleValueChange}
disabled={mutationView.isSwitchDisabled}
accessibilityLabel="Enable browser tools"
testID="host-page-browser-tools-switch"
/>
</View>
</View>
);
}
@@ -1,705 +0,0 @@
import { Plus, Server, Trash2 } from "lucide-react-native";
import type { TFunction } from "i18next";
import { useCallback, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import { Alert, Text, View } from "react-native";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { AdaptiveModalSheet, type SheetHeader } from "@/components/adaptive-modal-sheet";
import { HostStatusDot } from "@/components/host-status-dot";
import {
SettingsAddRow,
SettingsCard,
SettingsDetailHeader,
SettingsDetailRow,
SettingsRow,
SettingsSection,
} from "@/components/settings";
import { Button } from "@/components/ui/button";
import { StatusBadge } from "@/components/ui/status-badge";
import { useIsCompactFormFactor } from "@/constants/layout";
import { startDesktopDaemon, stopDesktopDaemon } from "@/desktop/daemon/desktop-daemon";
import type { EnableBuiltInDaemonOption } from "@/desktop/hooks/use-enable-built-in-daemon-option";
import { useDaemonStatus } from "@/desktop/hooks/use-daemon-status";
import { useDesktopSettings } from "@/desktop/settings/desktop-settings";
import { useIsLocalDaemon, useLocalDaemonServerId } from "@/hooks/use-is-local-daemon";
import { resolveHostIcon } from "@/hosts/appearance";
import { describeActiveConnection, describeHostConnection } from "@/hosts/connection-display";
import { HostIconGlyph } from "@/hosts/host-icon-glyph";
import { useHostMutations, useHostRuntimeSnapshot, useHosts } from "@/runtime/host-runtime";
import { HostAppearanceSection } from "@/screens/settings/host-appearance-section";
import { HostConnectionError } from "@/screens/settings/host-page";
import { useSessionStore } from "@/stores/session-store";
import { settingsStyles } from "@/styles/settings";
import { ICON_SIZE, type Theme } from "@/styles/theme";
import {
orderHostsLocalFirst,
type HostConnection,
type HostProfile,
} from "@/types/host-connection";
import { formatLatency } from "@/utils/latency";
const ThemedPlus = withUnistyles(Plus);
const ThemedServer = withUnistyles(Server);
const ThemedTrash2 = withUnistyles(Trash2);
const mutedColorMapping = (theme: Theme) => ({ color: theme.colors.foregroundMuted });
const destructiveColorMapping = (theme: Theme) => ({ color: theme.colors.destructive });
const addRouteIcon = <ThemedPlus size={ICON_SIZE.sm} uniProps={mutedColorMapping} />;
const enableDaemonIcon = <ThemedServer size={ICON_SIZE.md} uniProps={mutedColorMapping} />;
const removeHostIcon = <ThemedTrash2 size={ICON_SIZE.sm} uniProps={destructiveColorMapping} />;
function formatConnectionTitle(
connection: HostConnection,
isLocalHost: boolean,
t: TFunction,
): string {
const described = describeHostConnection(connection, { isLocalHost });
return t(`settings.host.connectionKinds.${described.kind}`);
}
function formatConnectionEndpoint(
connection: HostConnection,
isLocalHost: boolean,
hosts: readonly HostProfile[],
): string | undefined {
const described = describeHostConnection(connection, { isLocalHost });
if (described.kind === "routed" && described.endpoint) {
return hosts.find((host) => host.serverId === described.endpoint)?.label ?? described.endpoint;
}
return described.endpoint ?? undefined;
}
function formatDaemonVersion(version: string | null): string | undefined {
const trimmed = version?.trim();
if (!trimmed) return undefined;
return trimmed.startsWith("v") ? trimmed : `v${trimmed}`;
}
function ClientHostListRow({
host,
isLocalHost,
hosts,
onSelectHost,
}: {
host: HostProfile;
isLocalHost: boolean;
hosts: readonly HostProfile[];
onSelectHost: (serverId: string) => void;
}) {
const { t } = useTranslation();
const snapshot = useHostRuntimeSnapshot(host.serverId);
const serverInfo = useSessionStore((state) => state.sessions[host.serverId]?.serverInfo);
const detectedMachineKind = serverInfo?.machineKind ?? null;
const resolvedIcon = resolveHostIcon({ appearance: host.appearance, detectedMachineKind });
const handleOpen = useCallback(() => {
onSelectHost(host.serverId);
}, [host.serverId, onSelectHost]);
const status = snapshot?.connectionStatus;
const activeConnection = snapshot?.activeConnection ?? null;
const activeConnectionId = snapshot?.activeConnectionId;
const activeProbe = activeConnectionId
? snapshot?.probeByConnectionId.get(activeConnectionId)
: undefined;
const latencyMs =
status === "online" && activeProbe?.status === "available" ? activeProbe.latencyMs : null;
const fallbackConnection = useMemo(() => {
if (activeConnection || host.connections.length === 0) return null;
if (host.preferredConnectionId) {
const preferred = host.connections.find((c) => c.id === host.preferredConnectionId);
if (preferred) return preferred;
}
return host.connections[0] ?? null;
}, [activeConnection, host.connections, host.preferredConnectionId]);
const hint = useMemo(() => {
let described: ReturnType<typeof describeHostConnection> | null = null;
if (activeConnection) {
described = describeActiveConnection(activeConnection, { isLocalHost });
} else if (fallbackConnection) {
described = describeHostConnection(fallbackConnection, { isLocalHost });
}
const parts: string[] = [];
if (described) {
parts.push(t(`settings.host.connectionKinds.${described.kind}`));
if (described.endpoint) {
const endpoint =
described.kind === "routed"
? (hosts.find((candidate) => candidate.serverId === described.endpoint)?.label ??
described.endpoint)
: described.endpoint;
parts.push(endpoint);
}
}
if (latencyMs !== null) {
parts.push(formatLatency(latencyMs));
}
return parts.join(" · ") || undefined;
}, [activeConnection, fallbackConnection, hosts, isLocalHost, latencyMs, t]);
let summary: string | undefined;
if (status === "online") {
summary = formatDaemonVersion(serverInfo?.version ?? null);
} else if (status === "offline" || status === "error") {
summary = t("settings.about.offline");
}
const leading = useMemo(
() => (
<View style={styles.listLeading}>
<HostStatusDot serverId={host.serverId} />
<HostIconGlyph icon={resolvedIcon} color={host.appearance.color} size={ICON_SIZE.md} />
</View>
),
[host.appearance.color, host.serverId, resolvedIcon],
);
return (
<SettingsDetailRow
label={host.label}
leading={leading}
hint={hint}
summary={summary}
onPress={handleOpen}
testID={`client-host-row-${host.serverId}`}
/>
);
}
export function ClientHostsSection({
onSelectHost,
onAddHost,
enableBuiltInDaemonOption,
}: {
onSelectHost: (serverId: string) => void;
onAddHost: () => void;
enableBuiltInDaemonOption: EnableBuiltInDaemonOption;
}) {
const { t } = useTranslation();
const hosts = useHosts();
const localServerId = useLocalDaemonServerId();
const sortedHosts = useMemo(
() => orderHostsLocalFirst(hosts, localServerId),
[hosts, localServerId],
);
return (
<SettingsSection
title={t("settings.clientHosts.title")}
info={t("settings.clientHosts.info")}
testID="client-hosts-section"
>
<SettingsCard testID="client-hosts-card">
{sortedHosts.map((host) => (
<ClientHostListRow
key={host.serverId}
host={host}
isLocalHost={host.serverId === localServerId}
hosts={sortedHosts}
onSelectHost={onSelectHost}
/>
))}
<SettingsAddRow
label={t("settings.addHost")}
onPress={onAddHost}
testID="client-hosts-add-row"
/>
{enableBuiltInDaemonOption.visible ? (
<SettingsDetailRow
label={t("settings.enableBuiltInDaemon")}
leading={enableDaemonIcon}
onPress={enableBuiltInDaemonOption.onPress}
testID="client-hosts-enable-built-in-daemon"
/>
) : null}
</SettingsCard>
</SettingsSection>
);
}
function ClientHostRouteRow({
connection,
isActive,
isLocalHost,
hosts,
latencyMs,
latencyLoading,
latencyError,
onRemove,
}: {
connection: HostConnection;
isActive: boolean;
isLocalHost: boolean;
hosts: readonly HostProfile[];
latencyMs: number | null | undefined;
latencyLoading: boolean;
latencyError: boolean;
onRemove: (connection: HostConnection) => void;
}) {
const { t } = useTranslation();
const title = formatConnectionTitle(connection, isLocalHost, t);
const endpoint = formatConnectionEndpoint(connection, isLocalHost, hosts);
const latencyText = (() => {
if (latencyLoading) return "...";
if (latencyError) return t("settings.host.connections.timeout");
if (latencyMs != null) return formatLatency(latencyMs);
return "—";
})();
const handlePressRemove = useCallback(() => {
onRemove(connection);
}, [onRemove, connection]);
const activeBadge = useMemo(
() =>
isActive ? (
<StatusBadge label={t("settings.clientHosts.activeRoute")} variant="success" />
) : null,
[isActive, t],
);
return (
<SettingsRow label={title} labelAccessory={activeBadge} hint={endpoint}>
<View style={styles.routeTrailing}>
<Text style={latencyError ? styles.latencyError : styles.latencyText}>{latencyText}</Text>
<Button variant="ghost" textStyle={styles.destructiveText} onPress={handlePressRemove}>
{t("settings.host.connections.removeAction")}
</Button>
</View>
</SettingsRow>
);
}
function ClientHostRoutesSection({
host,
isLocalHost,
onAddHost,
}: {
host: HostProfile;
isLocalHost: boolean;
onAddHost: () => void;
}) {
const { t } = useTranslation();
const hosts = useHosts();
const { removeConnection } = useHostMutations();
const snapshot = useHostRuntimeSnapshot(host.serverId);
const probeByConnectionId = snapshot?.probeByConnectionId ?? new Map();
const activeConnectionId = snapshot?.activeConnectionId ?? null;
const [pendingRemoveConnection, setPendingRemoveConnection] = useState<{
connectionId: string;
title: string;
} | null>(null);
const [isRemovingConnection, setIsRemovingConnection] = useState(false);
const removeConnectionHeader = useMemo<SheetHeader>(
() => ({ title: t("settings.host.connections.removeTitle") }),
[t],
);
const handleRequestRemove = useCallback(
(connection: HostConnection) => {
const kindLabel = formatConnectionTitle(connection, isLocalHost, t);
const endpoint = formatConnectionEndpoint(connection, isLocalHost, hosts);
setPendingRemoveConnection({
connectionId: connection.id,
title: endpoint ? `${kindLabel} (${endpoint})` : kindLabel,
});
},
[hosts, isLocalHost, t],
);
const handleCloseConfirm = useCallback(() => {
if (isRemovingConnection) return;
setPendingRemoveConnection(null);
}, [isRemovingConnection]);
const handleCancelConfirm = useCallback(() => {
setPendingRemoveConnection(null);
}, []);
const handleConfirmRemove = useCallback(() => {
if (!pendingRemoveConnection) return;
const { connectionId } = pendingRemoveConnection;
setIsRemovingConnection(true);
void removeConnection(host.serverId, connectionId)
.then(() => setPendingRemoveConnection(null))
.catch((error) => {
console.error("[ClientHostDetail] Failed to remove connection", error);
Alert.alert(
t("settings.host.connections.removeErrorTitle"),
t("settings.host.connections.removeErrorMessage"),
);
})
.finally(() => setIsRemovingConnection(false));
}, [pendingRemoveConnection, removeConnection, host.serverId, t]);
const addRouteButton = useMemo(
() => (
<Button
variant="ghost"
leftIcon={addRouteIcon}
onPress={onAddHost}
testID="client-host-add-route"
>
{t("settings.clientHosts.addRoute")}
</Button>
),
[onAddHost, t],
);
return (
<SettingsSection
title={t("settings.clientHosts.routesTitle")}
info={t("settings.clientHosts.routesInfo")}
trailing={addRouteButton}
>
<SettingsCard testID="host-page-connections-card">
{host.connections.map((conn) => {
const probe = probeByConnectionId.get(conn.id);
return (
<ClientHostRouteRow
key={conn.id}
connection={conn}
isActive={snapshot?.connectionStatus === "online" && activeConnectionId === conn.id}
isLocalHost={isLocalHost}
hosts={hosts}
latencyMs={probe?.status === "available" ? probe.latencyMs : undefined}
latencyLoading={!probe || probe.status === "pending"}
latencyError={probe?.status === "unavailable"}
onRemove={handleRequestRemove}
/>
);
})}
</SettingsCard>
{pendingRemoveConnection ? (
<AdaptiveModalSheet
header={removeConnectionHeader}
visible
onClose={handleCloseConfirm}
testID="remove-connection-confirm-modal"
>
<Text style={styles.confirmText}>
{t("settings.host.connections.removeMessage", {
name: pendingRemoveConnection.title,
})}
</Text>
<View style={styles.confirmActions}>
<Button
variant="secondary"
style={FLEX_1_STYLE}
onPress={handleCancelConfirm}
disabled={isRemovingConnection}
>
{t("common.actions.cancel")}
</Button>
<Button
variant="destructive"
style={FLEX_1_STYLE}
onPress={handleConfirmRemove}
disabled={isRemovingConnection}
testID="remove-connection-confirm"
>
{t("settings.host.connections.removeAction")}
</Button>
</View>
</AdaptiveModalSheet>
) : null}
</SettingsSection>
);
}
function RemoveClientHostSection({
host,
isLocalDaemon,
onRemoved,
}: {
host: HostProfile;
isLocalDaemon: boolean;
onRemoved?: () => void;
}) {
const { t } = useTranslation();
const { removeHost } = useHostMutations();
const { updateSettings } = useDesktopSettings();
const { data: daemonStatusData, setStatus } = useDaemonStatus();
const [isConfirming, setIsConfirming] = useState(false);
const [isRemoving, setIsRemoving] = useState(false);
const daemonStatus = daemonStatusData?.status ?? null;
const stopsOwnedDaemon = isLocalDaemon && daemonStatus?.ownedByDesktop === true;
const removeHostHeader = useMemo<SheetHeader>(
() => ({
title: stopsOwnedDaemon
? t("settings.host.daemon.remove.localConfirmTitle")
: t("settings.host.daemon.remove.title"),
}),
[stopsOwnedDaemon, t],
);
const handleOpenConfirm = useCallback(() => setIsConfirming(true), []);
const handleCloseConfirm = useCallback(() => {
if (isRemoving) return;
setIsConfirming(false);
}, [isRemoving]);
const handleCancel = useCallback(() => setIsConfirming(false), []);
const rollbackLocalhostRemoval = useCallback(
async (shouldRestartDaemon: boolean) => {
await updateSettings({ daemon: { manageBuiltInDaemon: true } });
if (!shouldRestartDaemon) return;
setStatus(await startDesktopDaemon());
},
[setStatus, updateSettings],
);
const handleConfirmRemove = useCallback(() => {
setIsRemoving(true);
const remove = async () => {
let didDisableDaemonManagement = false;
let didStopDaemon = false;
if (isLocalDaemon) {
try {
await updateSettings({ daemon: { manageBuiltInDaemon: false } });
didDisableDaemonManagement = true;
if (daemonStatus?.status === "running" && daemonStatus.ownedByDesktop) {
setStatus(await stopDesktopDaemon("host_remove"));
didStopDaemon = true;
}
await removeHost(host.serverId);
} catch (error) {
if (didDisableDaemonManagement) {
try {
await rollbackLocalhostRemoval(didStopDaemon);
} catch (rollbackError) {
console.error(
"[ClientHostDetail] Failed to roll back localhost removal",
rollbackError,
);
}
}
throw error;
}
return;
}
await removeHost(host.serverId);
};
void remove()
.then(() => {
setIsConfirming(false);
onRemoved?.();
return;
})
.catch((error) => {
console.error("[ClientHostDetail] Failed to remove host", error);
Alert.alert(
t("settings.host.daemon.remove.errorTitle"),
isLocalDaemon
? t("settings.host.daemon.remove.localErrorMessage")
: t("settings.host.daemon.remove.errorMessage"),
);
})
.finally(() => setIsRemoving(false));
}, [
daemonStatus,
host.serverId,
isLocalDaemon,
onRemoved,
removeHost,
rollbackLocalhostRemoval,
setStatus,
t,
updateSettings,
]);
return (
<SettingsSection
title={t("settings.host.daemon.dangerZone")}
testID="host-page-remove-host-card"
>
<SettingsCard>
<SettingsRow
label={
isLocalDaemon
? t("settings.host.daemon.remove.localTitle")
: t("settings.host.daemon.remove.title")
}
hint={
stopsOwnedDaemon
? t("settings.host.daemon.remove.localHint")
: t("settings.host.daemon.remove.hint")
}
>
<Button
variant="outline"
leftIcon={removeHostIcon}
textStyle={styles.destructiveText}
onPress={handleOpenConfirm}
testID="host-page-remove-host-button"
>
{t("settings.host.connections.removeAction")}
</Button>
</SettingsRow>
</SettingsCard>
{isConfirming ? (
<AdaptiveModalSheet
header={removeHostHeader}
visible
onClose={handleCloseConfirm}
testID="remove-host-confirm-modal"
>
<Text style={styles.confirmText}>
{stopsOwnedDaemon
? t("settings.host.daemon.remove.localConfirmMessage")
: t("settings.host.daemon.remove.confirmMessage", { name: host.label })}
</Text>
<View style={styles.confirmActions}>
<Button
variant="secondary"
style={FLEX_1_STYLE}
onPress={handleCancel}
disabled={isRemoving}
>
{t("common.actions.cancel")}
</Button>
<Button
variant="destructive"
style={FLEX_1_STYLE}
onPress={handleConfirmRemove}
disabled={isRemoving}
testID="remove-host-confirm"
>
{t("settings.host.connections.removeAction")}
</Button>
</View>
</AdaptiveModalSheet>
) : null}
</SettingsSection>
);
}
export function ClientHostDetailPage({
serverId,
onBack,
onAddHost,
onHostRemoved,
}: {
serverId: string;
onBack: () => void;
onAddHost: () => void;
onHostRemoved?: () => void;
}) {
const { t } = useTranslation();
const isCompact = useIsCompactFormFactor();
const hosts = useHosts();
const host = hosts.find((entry) => entry.serverId === serverId) ?? null;
const isLocalDaemon = useIsLocalDaemon(serverId);
const detectedMachineKind = useSessionStore(
(state) => state.sessions[serverId]?.serverInfo?.machineKind ?? null,
);
const parent = useMemo(
() => ({
label: t("settings.sections.hosts"),
accessibilityLabel: t("settings.clientHosts.backToHosts"),
onPress: onBack,
testID: "client-host-detail-back",
}),
[onBack, t],
);
const resolvedIcon = host
? resolveHostIcon({ appearance: host.appearance, detectedMachineKind })
: "server";
const icon = useMemo(
() =>
host ? (
<HostIconGlyph
icon={resolvedIcon}
color={host.appearance.color}
size={isCompact ? ICON_SIZE.md : ICON_SIZE.lg}
/>
) : undefined,
[host, isCompact, resolvedIcon],
);
if (!host) {
return (
<View testID="client-host-detail-page">
<SettingsDetailHeader parent={parent} titleTestID="client-host-detail-title" />
<View style={[settingsStyles.card, styles.emptyCard]}>
<Text style={styles.emptyText}>{t("settings.host.notFound")}</Text>
</View>
</View>
);
}
return (
<View testID="client-host-detail-page">
<SettingsDetailHeader
parent={parent}
icon={icon}
title={host.label}
titleTestID="client-host-detail-title"
/>
<HostConnectionError serverId={serverId} />
<ClientHostRoutesSection host={host} isLocalHost={isLocalDaemon} onAddHost={onAddHost} />
<HostAppearanceSection host={host} />
<RemoveClientHostSection
host={host}
isLocalDaemon={isLocalDaemon}
onRemoved={onHostRemoved}
/>
</View>
);
}
const styles = StyleSheet.create((theme) => ({
listLeading: {
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[2],
},
routeTrailing: {
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[2],
},
latencyText: {
fontSize: theme.fontSize.sm,
color: theme.colors.foregroundMuted,
fontVariant: ["tabular-nums"],
},
latencyError: {
fontSize: theme.fontSize.sm,
color: theme.colors.statusDanger,
},
destructiveText: {
color: theme.colors.destructive,
},
confirmText: {
color: theme.colors.foregroundMuted,
fontSize: theme.fontSize.base,
},
confirmActions: {
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[2],
marginTop: theme.spacing[4],
},
emptyCard: {
padding: theme.spacing[4],
alignItems: "center",
},
emptyText: {
color: theme.colors.foregroundMuted,
fontSize: theme.fontSize.base,
},
}));
const FLEX_1_STYLE = { flex: 1 };
@@ -1,7 +1,7 @@
import { useCallback, useMemo } from "react";
import { useTranslation } from "react-i18next";
import type { TFunction } from "i18next";
import { View } from "react-native";
import { Text, View } from "react-native";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { SettingsCard, SettingsRow, SettingsSection } from "@/components/settings";
import { Button } from "@/components/ui/button";
@@ -16,6 +16,7 @@ import {
type FilePanelSettingsRow,
} from "@/file-panels";
import { PluginIconView } from "@/plugins/icons";
import { settingsStyles } from "@/styles/settings";
import type { Theme } from "@/styles/theme";
const MENU_ICON_SIZE = 16;
@@ -27,21 +28,26 @@ const mutedIconMapping = (theme: Theme) => ({ color: theme.colors.foregroundMute
export function FilesSection() {
const { t } = useTranslation();
const { rows, choose, askAgain } = useFilePanelSettings();
if (rows.length === 0) {
return null;
}
return (
<SettingsSection title={t("settings.files.title")} testID="file-panel-settings">
<SettingsCard testID="file-panel-settings-card">
{rows.map((row) => (
<FilePanelSettingsRowView
key={row.selectorKey}
row={row}
onChoose={choose}
onAskAgain={askAgain}
/>
))}
</SettingsCard>
{rows.length === 0 ? (
<View style={settingsStyles.card} testID="file-panel-settings-empty">
<View style={styles.emptyCard}>
<Text style={styles.emptyText}>{t("settings.files.empty")}</Text>
</View>
</View>
) : (
<SettingsCard testID="file-panel-settings-card">
{rows.map((row) => (
<FilePanelSettingsRowView
key={row.selectorKey}
row={row}
onChoose={choose}
onAskAgain={askAgain}
/>
))}
</SettingsCard>
)}
</SettingsSection>
);
}
@@ -147,4 +153,12 @@ const styles = StyleSheet.create((theme) => ({
alignItems: "center",
gap: theme.spacing[2],
},
emptyCard: {
padding: theme.spacing[4],
alignItems: "center",
},
emptyText: {
color: theme.colors.foregroundMuted,
fontSize: theme.fontSize.base,
},
}));
+441 -66
View File
@@ -24,7 +24,6 @@ import { AgentProfilesPage, type AgentProfilesBeforeLeaveGuard } from "@/agent-p
import { AgentSkillsSection } from "@/agent-skills";
import { AdaptiveModalSheet, type SheetHeader } from "@/components/adaptive-modal-sheet";
import { PageLayout } from "@/components/page-layout";
import { SettingsCard, SettingsRow, SettingsSection } from "@/components/settings";
import { SettingsTextAreaCard } from "@/components/settings-textarea";
import { Alert as InlineAlert } from "@/components/ui/alert";
import { Button } from "@/components/ui/button";
@@ -34,14 +33,17 @@ import {
ProfileDraft,
TerminalProfileEditModal,
} from "@/screens/settings/terminal-profile-edit-modal";
import { startDesktopDaemon, stopDesktopDaemon } from "@/desktop/daemon/desktop-daemon";
import { LocalDaemonSection } from "@/desktop/components/desktop-updates-section";
import { useDaemonStatus } from "@/desktop/hooks/use-daemon-status";
import { useDesktopSettings } from "@/desktop/settings/desktop-settings";
import { WaysToConnect } from "@/devices";
import { useDaemonConfig } from "@/hooks/use-daemon-config";
import { useIsLocalDaemon } from "@/hooks/use-is-local-daemon";
import { useHostFeature } from "@/runtime/host-features";
import {
getHostRuntimeStore,
isHostRuntimeConnected,
useHostMutations,
useHostRuntimeClient,
useHostRuntimeIsConnected,
useHostRuntimeSnapshot,
@@ -50,7 +52,8 @@ import {
import { ProviderList } from "@/provider-settings";
import { openProviderSettings } from "@/navigation/settings-navigation";
import { HostUsageSection } from "@/usage";
import { MetadataGenerationPage } from "@/screens/settings/metadata-generation-page";
import { HostAppearanceSection } from "@/screens/settings/host-appearance-section";
import { SettingsSection } from "@/components/settings/headings/settings-section";
import { useSessionStore } from "@/stores/session-store";
import { settingsStyles } from "@/styles/settings";
import type { HostConnection, HostProfile } from "@/types/host-connection";
@@ -58,13 +61,14 @@ import { confirmDialog } from "@/utils/confirm-dialog";
import { isVersionMismatch } from "@/desktop/updates/desktop-updates";
import { resolveAppVersion } from "@/utils/app-version";
import { formatConnectionStatus, getConnectionStatusTone } from "@/utils/daemons";
import { formatLatency } from "@/utils/latency";
import { ICON_SIZE } from "@/styles/theme";
import type { Theme } from "@/styles/theme";
import { useProviderIcon } from "@/components/provider-icons";
import { BrowserToolsRow } from "./browser-tools-card";
import { HostPaseoToolsRow } from "./paseo-tools-card";
import { RestartRecoveryRow } from "./restart-recovery-card";
import { IdleRuntimeCleanupRow } from "./idle-runtime-cleanup-card";
import { BrowserToolsOptInCard } from "./browser-tools-card";
import { PaseoToolsCard } from "./paseo-tools-card";
import { RestartRecoveryCard } from "./restart-recovery-card";
import { IdleRuntimeCleanupCard } from "./idle-runtime-cleanup-card";
import { restartDaemonFromSettings, updateDaemonFromSettings } from "./daemon-lifecycle";
const ThemedRestart = withUnistyles(RotateCw);
@@ -105,6 +109,20 @@ const editProfileIcon = <ThemedProfilePencil size={ICON_SIZE.sm} uniProps={muted
const removeProfileIcon = <ThemedTrash2 size={ICON_SIZE.sm} uniProps={destructiveColorMapping} />;
const addProfileIcon = <ThemedPlus size={ICON_SIZE.sm} uniProps={mutedColorMapping} />;
function formatHostConnectionLabel(connection: HostConnection, t: TFunction): string {
if (connection.type === "routed") return `Via ${connection.originServerId}`;
if (connection.type === "relay") {
return `${t("settings.host.badges.relay")} (${connection.relayEndpoint})`;
}
if (connection.type === "directSocket" || connection.type === "directPipe") {
return `${t("settings.host.badges.local")} (${connection.path})`;
}
if (connection.type === "remoteSsh") {
return `${t("settings.host.badges.remoteSsh")} (${connection.host})`;
}
return `TCP (${connection.endpoint})`;
}
function formatActiveConnectionBadge(
activeConnection: { type: HostConnection["type"]; display: string } | null,
theme: ReturnType<typeof useUnistyles>["theme"],
@@ -211,7 +229,7 @@ function HostStatusBadges({ serverId }: { serverId: string }) {
);
}
export function HostConnectionError({ serverId }: { serverId: string }) {
function HostConnectionError({ serverId }: { serverId: string }) {
const { t } = useTranslation();
const snapshot = useHostRuntimeSnapshot(serverId);
const lastError = snapshot?.lastError ?? null;
@@ -231,6 +249,21 @@ export function HostConnectionError({ serverId }: { serverId: string }) {
);
}
export function HostConnectionsPage({ serverId }: { serverId: string }) {
const host = useHostProfile(serverId);
if (!host) {
return <HostNotFound />;
}
return (
<View>
<HostConnectionError serverId={serverId} />
<ConnectionsSection host={host} />
</View>
);
}
export function HostDevicesPage({ serverId }: { serverId: string }) {
const host = useHostProfile(serverId);
@@ -241,7 +274,7 @@ export function HostDevicesPage({ serverId }: { serverId: string }) {
return <WaysToConnect serverId={serverId} />;
}
export function HostToolsPage({ serverId }: { serverId: string }) {
export function HostAgentsPage({ serverId }: { serverId: string }) {
const { t } = useTranslation();
const host = useHostProfile(serverId);
const isConnected = useHostRuntimeIsConnected(serverId);
@@ -253,19 +286,13 @@ export function HostToolsPage({ serverId }: { serverId: string }) {
return (
<View>
{isConnected ? (
<>
<SettingsSection title={t("settings.host.tools.instructionsTitle")}>
<SettingsCard>
<AppendSystemPromptRow serverId={serverId} />
</SettingsCard>
</SettingsSection>
<SettingsSection title={t("settings.host.tools.toolsTitle")}>
<SettingsCard testID="host-page-inject-mcp-card">
<HostPaseoToolsRow serverId={serverId} />
<BrowserToolsRow serverId={serverId} />
</SettingsCard>
</SettingsSection>
</>
<SettingsSection title={t("settings.hostSections.agents")}>
<PaseoToolsCard serverId={serverId} />
<BrowserToolsOptInCard serverId={serverId} />
<AppendSystemPromptCard serverId={serverId} />
<RestartRecoveryCard serverId={serverId} />
<IdleRuntimeCleanupCard serverId={serverId} />
</SettingsSection>
) : (
<View style={[settingsStyles.card, styles.emptyCard]}>
<Text style={styles.emptyText}>{t("settings.host.agents.unavailable")}</Text>
@@ -320,14 +347,10 @@ export function HostWorkspacesPage({ serverId }: { serverId: string }) {
return (
<View>
<HostConnectionError serverId={serverId} />
{isConnected ? (
<>
<SettingsSection title={t("settings.hostSections.workspaces")}>
<AutoArchiveMergedWorkspacesCard serverId={serverId} />
</SettingsSection>
<MetadataGenerationPage serverId={serverId} />
</>
<SettingsSection title={t("settings.hostSections.workspaces")}>
<AutoArchiveMergedWorkspacesCard serverId={serverId} />
</SettingsSection>
) : (
<View style={[settingsStyles.card, styles.emptyCard]}>
<Text style={styles.emptyText}>{t("settings.host.workspaces.unavailable")}</Text>
@@ -369,29 +392,13 @@ export function HostUsagePage({ serverId }: { serverId: string }) {
);
}
function HostAgentRuntimeSection({ serverId }: { serverId: string }) {
const { t } = useTranslation();
const isConnected = useHostRuntimeIsConnected(serverId);
const supportsResume = useHostFeature(serverId, "resumeOnStartupSetting");
const supportsIdleCleanup = useHostFeature(serverId, "idleRuntimeCleanupSetting");
const { config } = useDaemonConfig(serverId);
if (!isConnected || !config || (!supportsResume && !supportsIdleCleanup)) {
return null;
}
return (
<SettingsSection title={t("settings.host.daemon.runtimeTitle")}>
<SettingsCard>
{supportsResume ? <RestartRecoveryRow serverId={serverId} /> : null}
{supportsIdleCleanup ? <IdleRuntimeCleanupRow serverId={serverId} /> : null}
</SettingsCard>
</SettingsSection>
);
}
export function HostDaemonPage({ serverId }: { serverId: string }) {
const { t } = useTranslation();
export function HostSettingsPage({
serverId,
onHostRemoved,
}: {
serverId: string;
onHostRemoved?: () => void;
}) {
const host = useHostProfile(serverId);
const isLocalDaemon = useIsLocalDaemon(serverId);
@@ -404,15 +411,178 @@ export function HostDaemonPage({ serverId }: { serverId: string }) {
<HostStatusBadges serverId={serverId} />
<HostConnectionError serverId={serverId} />
<HostAppearanceSection host={host} />
{isLocalDaemon ? <LocalDaemonSection /> : null}
{!isLocalDaemon ? <UpdateDaemonCard key={host.serverId} host={host} /> : null}
<HostAgentRuntimeSection serverId={serverId} />
<RemoveHostSection host={host} isLocalDaemon={isLocalDaemon} onRemoved={onHostRemoved} />
</View>
);
}
<SettingsSection title={t("settings.host.daemon.dangerZone")}>
<RestartDaemonCard host={host} />
</SettingsSection>
function ConnectionsSection({ host }: { host: HostProfile }) {
const { t } = useTranslation();
const { removeConnection } = useHostMutations();
const snapshot = useHostRuntimeSnapshot(host.serverId);
const probeByConnectionId = snapshot?.probeByConnectionId ?? new Map();
const [pendingRemoveConnection, setPendingRemoveConnection] = useState<{
connectionId: string;
title: string;
} | null>(null);
const [isRemovingConnection, setIsRemovingConnection] = useState(false);
const removeConnectionHeader = useMemo<SheetHeader>(
() => ({ title: t("settings.host.connections.removeTitle") }),
[t],
);
const handleRequestRemove = useCallback(
(connection: HostConnection) => {
setPendingRemoveConnection({
connectionId: connection.id,
title: formatHostConnectionLabel(connection, t),
});
},
[t],
);
const handleCloseConfirm = useCallback(() => {
if (isRemovingConnection) return;
setPendingRemoveConnection(null);
}, [isRemovingConnection]);
const handleCancelConfirm = useCallback(() => {
setPendingRemoveConnection(null);
}, []);
const handleConfirmRemove = useCallback(() => {
if (!pendingRemoveConnection) return;
const { connectionId } = pendingRemoveConnection;
setIsRemovingConnection(true);
void removeConnection(host.serverId, connectionId)
.then(() => setPendingRemoveConnection(null))
.catch((error) => {
console.error("[HostPage] Failed to remove connection", error);
Alert.alert(
t("settings.host.connections.removeErrorTitle"),
t("settings.host.connections.removeErrorMessage"),
);
})
.finally(() => setIsRemovingConnection(false));
}, [pendingRemoveConnection, removeConnection, host.serverId, t]);
return (
<SettingsSection title={t("settings.host.connections.title")}>
<View style={settingsStyles.card} testID="host-page-connections-card">
{host.connections.map((conn, index) => {
const probe = probeByConnectionId.get(conn.id);
return (
<ConnectionRow
key={conn.id}
connection={conn}
showBorder={index > 0}
latencyMs={probe?.status === "available" ? probe.latencyMs : undefined}
latencyLoading={!probe || probe.status === "pending"}
latencyError={probe?.status === "unavailable"}
onRemove={handleRequestRemove}
/>
);
})}
</View>
{pendingRemoveConnection ? (
<AdaptiveModalSheet
header={removeConnectionHeader}
visible
onClose={handleCloseConfirm}
testID="remove-connection-confirm-modal"
>
<Text style={styles.confirmText}>
{t("settings.host.connections.removeMessage", {
name: pendingRemoveConnection.title,
})}
</Text>
<View style={styles.confirmActions}>
<Button
variant="secondary"
style={FLEX_1_STYLE}
onPress={handleCancelConfirm}
disabled={isRemovingConnection}
>
{t("common.actions.cancel")}
</Button>
<Button
variant="destructive"
style={FLEX_1_STYLE}
onPress={handleConfirmRemove}
disabled={isRemovingConnection}
testID="remove-connection-confirm"
>
{t("settings.host.connections.removeAction")}
</Button>
</View>
</AdaptiveModalSheet>
) : null}
</SettingsSection>
);
}
function ConnectionRow({
connection,
showBorder,
latencyMs,
latencyLoading,
latencyError,
onRemove,
}: {
connection: HostConnection;
showBorder: boolean;
latencyMs: number | null | undefined;
latencyLoading: boolean;
latencyError: boolean;
onRemove: (connection: HostConnection) => void;
}) {
const { t } = useTranslation();
const { theme } = useUnistyles();
const title = formatHostConnectionLabel(connection, t);
const latencyText = (() => {
if (latencyLoading) return "...";
if (latencyError) return t("settings.host.connections.timeout");
if (latencyMs != null) return formatLatency(latencyMs);
return "—";
})();
const latencyColor = latencyError ? theme.colors.palette.red[300] : theme.colors.foregroundMuted;
const handlePressRemove = useCallback(() => {
onRemove(connection);
}, [onRemove, connection]);
const rowStyle = useMemo(
() => [settingsStyles.row, showBorder && settingsStyles.rowBorder],
[showBorder],
);
const latencyTextStyle = useMemo(
() => [styles.connectionLatency, { color: latencyColor }],
[latencyColor],
);
const destructiveTextStyle = useMemo(
() => ({ color: theme.colors.destructive }),
[theme.colors.destructive],
);
return (
<View style={rowStyle}>
<View style={settingsStyles.rowContent}>
<Text style={settingsStyles.rowTitle} numberOfLines={1}>
{title}
</Text>
</View>
<Text style={latencyTextStyle}>{latencyText}</Text>
<Button variant="ghost" textStyle={destructiveTextStyle} onPress={handlePressRemove}>
{t("settings.host.connections.removeAction")}
</Button>
</View>
);
}
@@ -842,7 +1012,7 @@ function EnableTerminalAgentHooksCard({ serverId }: { serverId: string }) {
);
}
function AppendSystemPromptRow({ serverId }: { serverId: string }) {
function AppendSystemPromptCard({ serverId }: { serverId: string }) {
const { t } = useTranslation();
const isConnected = useHostRuntimeIsConnected(serverId);
const { config, patchConfig } = useDaemonConfig(serverId);
@@ -893,15 +1063,25 @@ function AppendSystemPromptRow({ serverId }: { serverId: string }) {
return (
<>
<SettingsRow
label={t("settings.host.orchestration.systemPrompt.title")}
hint={t("settings.host.orchestration.systemPrompt.hint")}
testID="host-page-append-system-prompt-card"
>
<Button variant="outline" onPress={handleOpen} testID="host-page-append-system-prompt-edit">
{t("settings.host.orchestration.systemPrompt.edit")}
</Button>
</SettingsRow>
<View style={settingsStyles.card} testID="host-page-append-system-prompt-card">
<View style={settingsStyles.row}>
<View style={settingsStyles.rowContent}>
<Text style={settingsStyles.rowTitle}>
{t("settings.host.orchestration.systemPrompt.title")}
</Text>
<Text style={settingsStyles.rowHint}>
{t("settings.host.orchestration.systemPrompt.hint")}
</Text>
</View>
<Button
variant="outline"
onPress={handleOpen}
testID="host-page-append-system-prompt-edit"
>
{t("settings.host.orchestration.systemPrompt.edit")}
</Button>
</View>
</View>
{isEditing ? (
<AdaptiveModalSheet
@@ -944,6 +1124,185 @@ function AppendSystemPromptRow({ serverId }: { serverId: string }) {
);
}
function RemoveHostSection({
host,
isLocalDaemon,
onRemoved,
}: {
host: HostProfile;
isLocalDaemon: boolean;
onRemoved?: () => void;
}) {
const { t } = useTranslation();
const { theme } = useUnistyles();
const { removeHost } = useHostMutations();
const { updateSettings } = useDesktopSettings();
const { data: daemonStatusData, setStatus } = useDaemonStatus();
const [isConfirming, setIsConfirming] = useState(false);
const [isRemoving, setIsRemoving] = useState(false);
const daemonStatus = daemonStatusData?.status ?? null;
const stopsOwnedDaemon = isLocalDaemon && daemonStatus?.ownedByDesktop === true;
const removeHostHeader = useMemo<SheetHeader>(
() => ({
title: stopsOwnedDaemon
? t("settings.host.daemon.remove.localConfirmTitle")
: t("settings.host.daemon.remove.title"),
}),
[stopsOwnedDaemon, t],
);
const destructiveTextStyle = useMemo(
() => ({ color: theme.colors.destructive }),
[theme.colors.destructive],
);
const handleOpenConfirm = useCallback(() => setIsConfirming(true), []);
const handleCloseConfirm = useCallback(() => {
if (isRemoving) return;
setIsConfirming(false);
}, [isRemoving]);
const handleCancel = useCallback(() => setIsConfirming(false), []);
const rollbackLocalhostRemoval = useCallback(
async (shouldRestartDaemon: boolean) => {
await updateSettings({ daemon: { manageBuiltInDaemon: true } });
if (!shouldRestartDaemon) {
return;
}
setStatus(await startDesktopDaemon());
},
[setStatus, updateSettings],
);
const handleConfirmRemove = useCallback(() => {
setIsRemoving(true);
const remove = async () => {
let didDisableDaemonManagement = false;
let didStopDaemon = false;
if (isLocalDaemon) {
try {
await updateSettings({ daemon: { manageBuiltInDaemon: false } });
didDisableDaemonManagement = true;
if (daemonStatus?.status === "running" && daemonStatus.ownedByDesktop) {
setStatus(await stopDesktopDaemon("host_remove"));
didStopDaemon = true;
}
await removeHost(host.serverId);
} catch (error) {
if (didDisableDaemonManagement) {
try {
await rollbackLocalhostRemoval(didStopDaemon);
} catch (rollbackError) {
console.error("[HostPage] Failed to roll back localhost removal", rollbackError);
}
}
throw error;
}
return;
}
await removeHost(host.serverId);
};
void remove()
.then(() => {
setIsConfirming(false);
onRemoved?.();
return;
})
.catch((error) => {
console.error("[HostPage] Failed to remove host", error);
Alert.alert(
t("settings.host.daemon.remove.errorTitle"),
isLocalDaemon
? t("settings.host.daemon.remove.localErrorMessage")
: t("settings.host.daemon.remove.errorMessage"),
);
})
.finally(() => setIsRemoving(false));
}, [
daemonStatus,
host.serverId,
isLocalDaemon,
onRemoved,
removeHost,
rollbackLocalhostRemoval,
setStatus,
t,
updateSettings,
]);
const removeIcon = useMemo(
() => <Trash2 size={theme.iconSize.sm} color={theme.colors.destructive} />,
[theme.iconSize.sm, theme.colors.destructive],
);
return (
<SettingsSection
title={t("settings.host.daemon.dangerZone")}
testID="host-page-remove-host-card"
>
<RestartDaemonCard host={host} />
<View style={settingsStyles.card}>
<View style={settingsStyles.row}>
<View style={settingsStyles.rowContent}>
<Text style={settingsStyles.rowTitle}>
{isLocalDaemon
? t("settings.host.daemon.remove.localTitle")
: t("settings.host.daemon.remove.title")}
</Text>
<Text style={settingsStyles.rowHint}>
{stopsOwnedDaemon
? t("settings.host.daemon.remove.localHint")
: t("settings.host.daemon.remove.hint")}
</Text>
</View>
<Button
variant="outline"
leftIcon={removeIcon}
textStyle={destructiveTextStyle}
onPress={handleOpenConfirm}
testID="host-page-remove-host-button"
>
{t("settings.host.connections.removeAction")}
</Button>
</View>
</View>
{isConfirming ? (
<AdaptiveModalSheet
header={removeHostHeader}
visible
onClose={handleCloseConfirm}
testID="remove-host-confirm-modal"
>
<Text style={styles.confirmText}>
{stopsOwnedDaemon
? t("settings.host.daemon.remove.localConfirmMessage")
: t("settings.host.daemon.remove.confirmMessage", { name: host.label })}
</Text>
<View style={styles.confirmActions}>
<Button
variant="secondary"
style={FLEX_1_STYLE}
onPress={handleCancel}
disabled={isRemoving}
>
{t("common.actions.cancel")}
</Button>
<Button
variant="destructive"
style={FLEX_1_STYLE}
onPress={handleConfirmRemove}
disabled={isRemoving}
testID="remove-host-confirm"
>
{t("settings.host.connections.removeAction")}
</Button>
</View>
</AdaptiveModalSheet>
) : null}
</SettingsSection>
);
}
// ---------------------------------------------------------------------------
// Terminal Profiles
// ---------------------------------------------------------------------------
@@ -1368,6 +1727,20 @@ const styles = StyleSheet.create((theme) => ({
connectionError: {
marginBottom: theme.spacing[6],
},
connectionLatency: {
fontSize: theme.fontSize.base,
marginRight: theme.spacing[2],
},
confirmText: {
color: theme.colors.foregroundMuted,
fontSize: theme.fontSize.base,
},
confirmActions: {
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[2],
marginTop: theme.spacing[4],
},
appendPromptActions: {
flexDirection: "row",
justifyContent: "flex-end",
@@ -1382,3 +1755,5 @@ const styles = StyleSheet.create((theme) => ({
fontSize: theme.fontSize.base,
},
}));
const FLEX_1_STYLE = { flex: 1 };
@@ -1,14 +1,17 @@
import { useCallback, useMemo } from "react";
import { useCallback } from "react";
import { Text, View } from "react-native";
import { useMutation } from "@tanstack/react-query";
import { useTranslation } from "react-i18next";
import { SettingsInfoTip, SettingsRow } from "@/components/settings";
import { StyleSheet } from "react-native-unistyles";
import { SettingsInfoTip } from "@/components/settings/headings/settings-info-tip";
import { Switch } from "@/components/ui/switch";
import { useDaemonConfig } from "@/hooks/use-daemon-config";
import { useHostFeature } from "@/runtime/host-features";
import { useHostRuntimeIsConnected } from "@/runtime/host-runtime";
import { settingsStyles } from "@/styles/settings";
// Host-wide, persisted, and applied live by the daemon.
export function IdleRuntimeCleanupRow({ serverId }: { serverId: string }) {
export function IdleRuntimeCleanupCard({ serverId }: { serverId: string }) {
const { t } = useTranslation();
const isConnected = useHostRuntimeIsConnected(serverId);
const isSupported = useHostFeature(serverId, "idleRuntimeCleanupSetting");
@@ -30,34 +33,46 @@ export function IdleRuntimeCleanupRow({ serverId }: { serverId: string }) {
[mutation],
);
const infoTip = useMemo(
() => (
<SettingsInfoTip
title={t("settings.host.agents.idleRuntimeCleanup.title")}
info={t("settings.host.agents.idleRuntimeCleanup.info")}
/>
),
[t],
);
if (!isConnected || !isSupported || !config) return null;
return (
<SettingsRow
label={t("settings.host.agents.idleRuntimeCleanup.title")}
labelAccessory={infoTip}
hint={t("settings.host.agents.idleRuntimeCleanup.hint")}
error={mutation.error?.message}
errorTestID="host-page-idle-runtime-cleanup-error"
testID="host-page-idle-runtime-cleanup-card"
>
<Switch
value={config.idleRuntimeCleanup !== false}
onValueChange={handleValueChange}
disabled={mutation.isPending}
accessibilityLabel={t("settings.host.agents.idleRuntimeCleanup.title")}
testID="host-page-idle-runtime-cleanup-switch"
/>
</SettingsRow>
<View style={settingsStyles.card} testID="host-page-idle-runtime-cleanup-card">
<View style={settingsStyles.row}>
<View style={settingsStyles.rowContent}>
<View style={styles.titleRow}>
<Text style={settingsStyles.rowTitle}>
{t("settings.host.agents.idleRuntimeCleanup.title")}
</Text>
<SettingsInfoTip
title={t("settings.host.agents.idleRuntimeCleanup.title")}
info={t("settings.host.agents.idleRuntimeCleanup.info")}
/>
</View>
<Text style={settingsStyles.rowHint}>
{t("settings.host.agents.idleRuntimeCleanup.hint")}
</Text>
{mutation.error ? (
<Text style={settingsStyles.rowError} testID="host-page-idle-runtime-cleanup-error">
{mutation.error.message}
</Text>
) : null}
</View>
<Switch
value={config.idleRuntimeCleanup !== false}
onValueChange={handleValueChange}
disabled={mutation.isPending}
accessibilityLabel={t("settings.host.agents.idleRuntimeCleanup.title")}
testID="host-page-idle-runtime-cleanup-switch"
/>
</View>
</View>
);
}
const styles = StyleSheet.create((theme) => ({
titleRow: {
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[2],
},
}));

Some files were not shown because too many files have changed in this diff Show More