mirror of
https://github.com/getpaseo/paseo.git
synced 2026-11-30 12:16:12 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d2d4105366 | ||
|
|
37cb22dac8 | ||
|
|
397d1e14d6 | ||
|
|
d193e419e9 | ||
|
|
bd20e3fe98 | ||
|
|
39eaba6181 | ||
|
|
63ede58d7d | ||
|
|
3986e8b808 | ||
|
|
9fd8921697 | ||
|
|
269fa33491 | ||
|
|
ebcea47942 | ||
|
|
fb9a1644f0 | ||
|
|
93278b217b | ||
|
|
5f453a2f74 | ||
|
|
01aced8cd2 | ||
|
|
9d994aca9b | ||
|
|
839d45103b | ||
|
|
96fee23fbd | ||
|
|
e31f379d54 | ||
|
|
f37991f8d4 | ||
|
|
dbc3983314 | ||
|
|
b5f56a70f6 | ||
|
|
5ef84c6bc0 | ||
|
|
1e8bf499af | ||
|
|
8849fd06c9 | ||
|
|
1cd2460a51 | ||
|
|
75abc739e6 | ||
|
|
728e09f0bb | ||
|
|
cf68bd76d4 | ||
|
|
7f2ece0556 | ||
|
|
f81d433afc | ||
|
|
a931ac1cd7 | ||
|
|
cdfc788946 | ||
|
|
8be985cb27 | ||
|
|
977049557a | ||
|
|
5d678b3848 | ||
|
|
26550ff73f |
@@ -59,7 +59,7 @@ jobs:
|
||||
filters: .github/ci-paths.yml
|
||||
|
||||
- name: Validate CI contracts
|
||||
run: node --test scripts/ci-workflow.test.mjs scripts/daemon-launch-contract.test.mjs scripts/changelog-utils.test.mjs scripts/release-version-utils.test.mjs scripts/publish-release-packages.test.mjs scripts/push-current-release-tag.test.mjs scripts/reconcile-release.test.mjs scripts/sync-fdroid-changelogs.test.mjs scripts/sync-release-notes-from-changelog.test.mjs scripts/upload-release-assets.test.mjs
|
||||
run: node --test scripts/ci-workflow.test.mjs scripts/daemon-launch-contract.test.mjs scripts/changelog-utils.test.mjs scripts/release-version-utils.test.mjs scripts/publish-release-packages.test.mjs scripts/push-current-release-tag.test.mjs scripts/reconcile-release.test.mjs scripts/sync-fdroid-changelogs.test.mjs scripts/sync-release-notes-from-changelog.test.mjs scripts/upload-release-assets.test.mjs scripts/precompress-assets.test.mjs
|
||||
|
||||
quality:
|
||||
name: quality
|
||||
|
||||
@@ -1,5 +1,98 @@
|
||||
# Changelog
|
||||
|
||||
## 0.18.2 - 2026-11-30
|
||||
|
||||
- **Redesigned model picker:** Pick models from a two-pane desktop view with cross-provider search, an in-place phone drawer with a thinking slider, and per-provider model lists in settings. ([#11186](https://github.com/getpaseo/paseo/pull/11186), [#11280](https://github.com/getpaseo/paseo/pull/11280), [#11295](https://github.com/getpaseo/paseo/pull/11295), [#11371](https://github.com/getpaseo/paseo/pull/11371), [#11313](https://github.com/getpaseo/paseo/pull/11313))
|
||||
- **File actions and filter:** Filter the Files tree by name, and reveal, open in your default app, download, or copy paths from chat file links, file tabs, and sidebar trees. ([#11073](https://github.com/getpaseo/paseo/pull/11073), [#11299](https://github.com/getpaseo/paseo/pull/11299), [#11320](https://github.com/getpaseo/paseo/pull/11320) by [@YASICJUNWOO](https://github.com/YASICJUNWOO), [@apple-ouyang](https://github.com/apple-ouyang), [@iqshen](https://github.com/iqshen), [@Ctrl-Creeper](https://github.com/Ctrl-Creeper), [@softyoda](https://github.com/softyoda))
|
||||
- **New butterfly app icons:** Desktop and mobile now share the updated butterfly icon, with proper macOS Dock sizing and system lighting. ([#11091](https://github.com/getpaseo/paseo/pull/11091))
|
||||
- **Live usage updates:** Claude and Codex usage summaries now update as turns finish instead of waiting for the five-minute poll. ([#11170](https://github.com/getpaseo/paseo/pull/11170) by [@Zayooo00](https://github.com/Zayooo00))
|
||||
- **Faster CLI startup:** Paseo CLI commands now start 7 to 22 times faster by loading only the requested command. ([#11155](https://github.com/getpaseo/paseo/pull/11155), [#11193](https://github.com/getpaseo/paseo/pull/11193), [#11363](https://github.com/getpaseo/paseo/pull/11363))
|
||||
- **Native ACP question cards:** Plugin ACP providers such as Antigravity now pause on interactive form questions with Paseo's question card instead of printing numbered lists. ([#11135](https://github.com/getpaseo/paseo/pull/11135) by [@djbclark](https://github.com/djbclark), [@krazyjakee](https://github.com/krazyjakee))
|
||||
- **OMP background jobs:** OMP agents now list running background tasks above the composer and let you stop them without interrupting the agent. ([#11270](https://github.com/getpaseo/paseo/pull/11270) by [@mcowger](https://github.com/mcowger))
|
||||
- **Plugin HTTP tunnels:** Plugins can now expose local HTTP services at public HTTPS URLs through tunnel providers, with built-in `cloudflared` and Tailscale Funnel support. ([#11036](https://github.com/getpaseo/paseo/pull/11036))
|
||||
|
||||
### Added
|
||||
|
||||
- Added `--all` to `paseo schedule ls` to list schedules targeting existing agents, and noted hidden schedules in table output ([#11243](https://github.com/getpaseo/paseo/pull/11243) by [@suniceman](https://github.com/suniceman))
|
||||
- Added `activeTurnBehavior: "queue"` support for non-agent senders so plugins and UI actions can queue prompts behind a running turn ([#11169](https://github.com/getpaseo/paseo/pull/11169))
|
||||
|
||||
### Improved
|
||||
|
||||
- Reduced app memory use by dropping duplicate in-memory copies of cached transcripts ([#11322](https://github.com/getpaseo/paseo/pull/11322))
|
||||
- Held the native launch splash until the restored workspace is on screen so mobile cold starts no longer flash empty frames or spinners ([#11348](https://github.com/getpaseo/paseo/pull/11348))
|
||||
- Added a neutral focus border to the message composer ([#11097](https://github.com/getpaseo/paseo/pull/11097), [#11272](https://github.com/getpaseo/paseo/pull/11272) by [@Zayooo00](https://github.com/Zayooo00))
|
||||
- Changed protocol parsing to ignore unknown newer fields and skip unrecognized list items instead of dropping whole messages ([#11284](https://github.com/getpaseo/paseo/pull/11284))
|
||||
- Improved workspace lookup speed on hosts with many workspaces by filtering before loading workspace configs ([#11266](https://github.com/getpaseo/paseo/pull/11266))
|
||||
|
||||
### Changed
|
||||
|
||||
- Changed unattended Hub agent runs and their subagents to automatically deny unexpected permission prompts instead of blocking until timeout ([#11179](https://github.com/getpaseo/paseo/pull/11179))
|
||||
- Changed delegated agent turn-end notices with pending work to appear as compact tool rows instead of peer message bubbles ([#11175](https://github.com/getpaseo/paseo/pull/11175))
|
||||
|
||||
### Fixed
|
||||
|
||||
- Fixed iOS composer buttons ignoring taps while the software keyboard is open and the model picker opening behind the keyboard on unfolded wide screens ([#11276](https://github.com/getpaseo/paseo/pull/11276))
|
||||
- Fixed tapping Fullscreen or Exit fullscreen in the mobile composer closing the keyboard and flashing misaligned frames ([#11326](https://github.com/getpaseo/paseo/pull/11326))
|
||||
- Fixed phone photos and large Android image batches failing to send by uploading images as chunked files and downscaling HEIC photos ([#11137](https://github.com/getpaseo/paseo/pull/11137), [#9328](https://github.com/getpaseo/paseo/pull/9328), [#11281](https://github.com/getpaseo/paseo/pull/11281) by [@Brandon168](https://github.com/Brandon168))
|
||||
- Fixed Android's system Bold text setting clipping trailing characters and labels across the app ([#11162](https://github.com/getpaseo/paseo/pull/11162) by [@JustinJoshi](https://github.com/JustinJoshi))
|
||||
- Fixed the discovered Models list in Android provider settings failing to scroll ([#11350](https://github.com/getpaseo/paseo/pull/11350) by [@ilteoood](https://github.com/ilteoood))
|
||||
- Fixed mobile sending push notifications for the active chat by counting native touches and typing as presence ([#8070](https://github.com/getpaseo/paseo/pull/8070) by [@truelecter](https://github.com/truelecter))
|
||||
- Fixed SVG files opening as blank image previews on iOS and Android ([#9094](https://github.com/getpaseo/paseo/pull/9094))
|
||||
- Fixed reconnects on hosts with many workspaces causing mobile freezes and 60-second request timeouts ([#11145](https://github.com/getpaseo/paseo/pull/11145) by [@TheUnlimited64](https://github.com/TheUnlimited64))
|
||||
- Fixed desktop browser tabs controlled by an agent stealing keyboard focus from chat composers ([#11158](https://github.com/getpaseo/paseo/pull/11158) by [@puchkoff](https://github.com/puchkoff))
|
||||
- Fixed the web and desktop image lightbox staying stuck on screen after switching to another session ([#11358](https://github.com/getpaseo/paseo/pull/11358) by [@matchy233](https://github.com/matchy233))
|
||||
- Fixed long desktop and web chats crashing with React error #185 during scroll re-measurement ([#11138](https://github.com/getpaseo/paseo/pull/11138) by [@kogekiplay](https://github.com/kogekiplay))
|
||||
- Fixed scrolling older history crashing desktop when a timeline plugin reuses output IDs across messages ([#8498](https://github.com/getpaseo/paseo/pull/8498) by [@kevinle128](https://github.com/kevinle128), [@ykurilov](https://github.com/ykurilov))
|
||||
- Fixed opening Changes with wrapped long lines freezing the desktop app ([#11113](https://github.com/getpaseo/paseo/pull/11113))
|
||||
- Fixed streaming code blocks growing and shrinking by a line while their closing fence arrives ([#7006](https://github.com/getpaseo/paseo/pull/7006) by [@luoph](https://github.com/luoph), [@RRD-dev](https://github.com/RRD-dev))
|
||||
- Fixed sending a steering message while an agent streams splitting the reply in half ([#5267](https://github.com/getpaseo/paseo/pull/5267))
|
||||
- Fixed the Schedules screen staying on a spinner when another saved host is offline or still connecting ([#11361](https://github.com/getpaseo/paseo/pull/11361) by [@agenore](https://github.com/agenore))
|
||||
- Fixed starting a new session on another host submitting an unavailable remembered model instead of selecting an available one ([#9052](https://github.com/getpaseo/paseo/pull/9052) by [@mcowger](https://github.com/mcowger))
|
||||
- Fixed the composer showing the wrong thinking level when an agent's level is absent from its model's option list ([#10937](https://github.com/getpaseo/paseo/pull/10937) by [@ortschun](https://github.com/ortschun))
|
||||
- Fixed unexpanded Windows environment-variable paths like `%TEMP%\file.md` rendering as broken links in chat ([#11228](https://github.com/getpaseo/paseo/pull/11228) by [@suniceman](https://github.com/suniceman))
|
||||
- Fixed Open in Antigravity on macOS launching the `agy` CLI instead of Antigravity IDE ([#10893](https://github.com/getpaseo/paseo/pull/10893) by [@wangfh5](https://github.com/wangfh5))
|
||||
- Fixed opening a built-in plugin's settings page showing a "not installed or listed" error ([#11308](https://github.com/getpaseo/paseo/pull/11308))
|
||||
- Fixed local host images inside plugin Markdown surfaces failing to render inline ([#11171](https://github.com/getpaseo/paseo/pull/11171))
|
||||
- Fixed agent metadata disappearing from plugin views after an app reload ([#11265](https://github.com/getpaseo/paseo/pull/11265))
|
||||
- Fixed Android terminal input doubling characters, dropping Backspace, breaking Korean/Pinyin/Gboard suggestions, and mishandling hardware Enter ([#11146](https://github.com/getpaseo/paseo/pull/11146), [#11318](https://github.com/getpaseo/paseo/pull/11318) by [@apple-ouyang](https://github.com/apple-ouyang), [@lennartschoch](https://github.com/lennartschoch), [@jasonmarkperez](https://github.com/jasonmarkperez))
|
||||
- Fixed Light-mode terminals reporting dark colors to terminal apps and added live light/dark theme change notifications ([#11163](https://github.com/getpaseo/paseo/pull/11163), [#11312](https://github.com/getpaseo/paseo/pull/11312) by [@gstamp](https://github.com/gstamp))
|
||||
- Fixed web and desktop terminals using the interface font instead of the configured Code font on the DOM renderer ([#11099](https://github.com/getpaseo/paseo/pull/11099) by [@sh0nuff](https://github.com/sh0nuff))
|
||||
- Fixed Windows terminals exiting immediately on busy machines when ConPTY startup takes more than five seconds ([#11238](https://github.com/getpaseo/paseo/pull/11238))
|
||||
- Fixed closing terminals or stopping the daemon on Windows leaving terminal programs running ([#11147](https://github.com/getpaseo/paseo/pull/11147))
|
||||
- Fixed Cursor usage showing HTTP 401 or missing cards across macOS Keychain, encrypted desktop stores, and Windows ([#11148](https://github.com/getpaseo/paseo/pull/11148) by [@jasonhnd](https://github.com/jasonhnd), [@KronixDev](https://github.com/KronixDev), [@kiawin](https://github.com/kiawin), [@ChicorSun](https://github.com/ChicorSun), [@kbitz](https://github.com/kbitz))
|
||||
- Fixed OpenCode v2 agents hiding plan usage windows in the chat meter and Codex usage reading stale OpenCode v1 logins ([#11153](https://github.com/getpaseo/paseo/pull/11153) by [@Wu-Jiayang](https://github.com/Wu-Jiayang))
|
||||
- Fixed Usage missing custom Claude and Codex providers configured with separate credential directories ([#11149](https://github.com/getpaseo/paseo/pull/11149) by [@QichangZheng](https://github.com/QichangZheng))
|
||||
- Fixed Claude and Codex wrapper commands or environment tokens showing a mismatched local account in Usage ([#11154](https://github.com/getpaseo/paseo/pull/11154))
|
||||
- Fixed Claude progress updates hiding inside collapsed Thinking rows and multi-block messages repeating their final block ([#11160](https://github.com/getpaseo/paseo/pull/11160) by [@ThePharmer](https://github.com/ThePharmer))
|
||||
- Fixed orphaned Claude CLI child processes leaking on concurrent resume or early cancel, and bounded headless metadata generation ([#11143](https://github.com/getpaseo/paseo/pull/11143) by [@desmond-rai](https://github.com/desmond-rai), [@nickmaglowsch](https://github.com/nickmaglowsch))
|
||||
- Fixed idle Claude agents being marked as failed when their process exits cleanly with code 0 ([#11273](https://github.com/getpaseo/paseo/pull/11273) by [@lucamzanon](https://github.com/lucamzanon))
|
||||
- Fixed Claude Advisor tool calls staying unsettled when rebuilding chat history ([#11202](https://github.com/getpaseo/paseo/pull/11202) by [@LucasValeQueiroz](https://github.com/LucasValeQueiroz), [@SirisZheng](https://github.com/SirisZheng))
|
||||
- Fixed updated plugin system prompt instructions not reaching resumed Claude sessions ([#10917](https://github.com/getpaseo/paseo/pull/10917) by [@Tomblarom](https://github.com/Tomblarom))
|
||||
- Fixed Codex alias `-c mcp_servers.*` overrides disappearing when Paseo injects MCP servers ([#11142](https://github.com/getpaseo/paseo/pull/11142))
|
||||
- Fixed OpenCode v2 models having no Default thinking option to return to base model behavior ([#11184](https://github.com/getpaseo/paseo/pull/11184) by [@3ae3ae](https://github.com/3ae3ae))
|
||||
- Fixed Pi and OMP live streaming splitting thinking and answer blocks out of order ([#11159](https://github.com/getpaseo/paseo/pull/11159))
|
||||
- Fixed Pi chat history opening empty when transcripts contain unlinked title or model-change metadata ([#11379](https://github.com/getpaseo/paseo/pull/11379))
|
||||
- Fixed sending a Pi extension slash command mid-turn aborting the active response ([#11341](https://github.com/getpaseo/paseo/pull/11341) by [@tridao](https://github.com/tridao))
|
||||
- Fixed a rejected Pi history or rewind extension prompt crashing the daemon worker ([#11329](https://github.com/getpaseo/paseo/pull/11329) by [@thomasvan](https://github.com/thomasvan))
|
||||
- Fixed completed Pi Tintinweb background subagents staying marked as Running ([#11168](https://github.com/getpaseo/paseo/pull/11168) by [@amcfague](https://github.com/amcfague))
|
||||
- Fixed background OMP catalog refreshes triggering cancelled startup model requests ([#11129](https://github.com/getpaseo/paseo/pull/11129) by [@mcowger](https://github.com/mcowger))
|
||||
- Fixed OMP turns timing out after ten minutes while actively streaming or waiting on a question card ([#11079](https://github.com/getpaseo/paseo/pull/11079) by [@LiebeLee](https://github.com/LiebeLee))
|
||||
- Fixed Antigravity deferred turns ending early after an interim reply when the final background tool completes ([#10924](https://github.com/getpaseo/paseo/pull/10924) by [@Juns-g](https://github.com/Juns-g))
|
||||
- Fixed stopping an unresponsive ACP agent leaving later prompts stuck behind an active foreground turn ([#11152](https://github.com/getpaseo/paseo/pull/11152))
|
||||
- Fixed resumed Muse sessions dropping daemon and plugin system instructions ([#10915](https://github.com/getpaseo/paseo/pull/10915) by [@Tomblarom](https://github.com/Tomblarom))
|
||||
- Fixed Unix-socket, named-pipe, non-loopback, and HTTP-proxy daemons dropping injected Paseo MCP tools and terminal activity reporting ([#11144](https://github.com/getpaseo/paseo/pull/11144))
|
||||
- Fixed repeated daemon restarts duplicating provider image attachments in temporary directories ([#7895](https://github.com/getpaseo/paseo/pull/7895) by [@cleiter](https://github.com/cleiter))
|
||||
- Fixed concurrent reloads of the same agent failing with "Unknown agent" ([#8369](https://github.com/getpaseo/paseo/pull/8369) by [@tieo](https://github.com/tieo))
|
||||
- Fixed `paseo agent logs --tail` timing out on very large chat histories ([#10723](https://github.com/getpaseo/paseo/pull/10723) by [@minamorl](https://github.com/minamorl))
|
||||
- Fixed `paseo agent logs` hanging instead of exiting after a daemon request timeout ([#11360](https://github.com/getpaseo/paseo/pull/11360))
|
||||
- Fixed `paseo permit ls` missing pending permissions from background agents and agents past the first 200 ([#10655](https://github.com/getpaseo/paseo/pull/10655) by [@NightMachinery](https://github.com/NightMachinery))
|
||||
- Fixed `paseo --host host:port` giving generic credential advice on HTTP 400 instead of suggesting `wss://` for TLS endpoints ([#11383](https://github.com/getpaseo/paseo/pull/11383))
|
||||
|
||||
### Plugins
|
||||
|
||||
- Added `update_workspace` and workspace `metadata` support to Paseo MCP and `PluginWorkspaceSnapshot` ([#11166](https://github.com/getpaseo/paseo/pull/11166))
|
||||
- Fixed server plugin compilation failing when a dependency's type declarations import Node ambient types ([#8618](https://github.com/getpaseo/paseo/pull/8618) by [@nkwib](https://github.com/nkwib))
|
||||
|
||||
## 0.18.1 - 2026-11-27
|
||||
|
||||
- **Host metadata instructions:** Set host-wide instructions once to guide language, tone, and formatting for generated workspace titles, branch names, commit messages, and pull requests. ([#11064](https://github.com/getpaseo/paseo/pull/11064))
|
||||
|
||||
@@ -1,5 +1,98 @@
|
||||
# Changelog
|
||||
|
||||
## 0.18.2 - 2026-11-30
|
||||
|
||||
- **重新设计的模型选择器**:桌面端采用支持跨 Provider 搜索的双栏视图,手机端合并为带思考强度滑块的单层抽屉,并支持在设置中按 Provider 筛选常用模型。([#11186](https://github.com/getpaseo/paseo/pull/11186), [#11280](https://github.com/getpaseo/paseo/pull/11280), [#11295](https://github.com/getpaseo/paseo/pull/11295), [#11371](https://github.com/getpaseo/paseo/pull/11371), [#11313](https://github.com/getpaseo/paseo/pull/11313))
|
||||
- **文件操作与筛选**:支持按名称筛选文件树,并直接从对话文件链接、文件标签页和侧边栏文件树中定位文件、使用默认应用打开、下载或复制路径。([#11073](https://github.com/getpaseo/paseo/pull/11073), [#11299](https://github.com/getpaseo/paseo/pull/11299), [#11320](https://github.com/getpaseo/paseo/pull/11320),贡献者:[@YASICJUNWOO](https://github.com/YASICJUNWOO), [@apple-ouyang](https://github.com/apple-ouyang), [@iqshen](https://github.com/iqshen), [@Ctrl-Creeper](https://github.com/Ctrl-Creeper), [@softyoda](https://github.com/softyoda))
|
||||
- **全新蝴蝶应用图标**:桌面端和移动端现已统一使用新版蝴蝶图标,并在 macOS 程序坞中具备正确的图标尺寸与系统光影。([#11091](https://github.com/getpaseo/paseo/pull/11091))
|
||||
- **实时用量更新**:Claude 和 Codex 的用量摘要现在会在轮次结束时实时更新,不再需要等待五分钟轮询。([#11170](https://github.com/getpaseo/paseo/pull/11170),贡献者:[@Zayooo00](https://github.com/Zayooo00))
|
||||
- **更快的 CLI 启动速度**:Paseo CLI 仅按需加载所执行的命令,启动速度提升 7 至 22 倍。([#11155](https://github.com/getpaseo/paseo/pull/11155), [#11193](https://github.com/getpaseo/paseo/pull/11193), [#11363](https://github.com/getpaseo/paseo/pull/11363))
|
||||
- **原生 ACP 提问卡片**:Antigravity 等插件 ACP Provider 遇到交互式表单提问时,现在会暂停并显示 Paseo 原生提问卡片,而不再输出编号列表。([#11135](https://github.com/getpaseo/paseo/pull/11135),贡献者:[@djbclark](https://github.com/djbclark), [@krazyjakee](https://github.com/krazyjakee))
|
||||
- **OMP 后台任务**:OMP Agent 现在会在 Composer 上方列出正在运行的后台任务,并支持直接停止而不中断 Agent。([#11270](https://github.com/getpaseo/paseo/pull/11270),贡献者:[@mcowger](https://github.com/mcowger))
|
||||
- **插件 HTTP 隧道**:插件现在可以通过隧道 Provider 将本地 HTTP 服务暴露为公网 HTTPS 地址,内置支持 `cloudflared` 和 Tailscale Funnel。([#11036](https://github.com/getpaseo/paseo/pull/11036))
|
||||
|
||||
### 新增
|
||||
|
||||
- 为 `paseo schedule ls` 新增 `--all` 选项以列出指向现有 Agent 的定时任务,并在表格输出中提示已隐藏的定时任务 ([#11243](https://github.com/getpaseo/paseo/pull/11243),贡献者:[@suniceman](https://github.com/suniceman))
|
||||
- 为非 Agent 发送方新增 `activeTurnBehavior: "queue"` 支持,使插件和界面操作可将提示词排队到当前运行轮次之后 ([#11169](https://github.com/getpaseo/paseo/pull/11169))
|
||||
|
||||
### 改进
|
||||
|
||||
- 移除了内存中重复保留的已缓存对话记录副本,降低了应用内存占用 ([#11322](https://github.com/getpaseo/paseo/pull/11322))
|
||||
- 延长原生启动画面直到恢复的工作区渲染到屏幕上,避免移动端冷启动时闪烁空白帧或加载指示器 ([#11348](https://github.com/getpaseo/paseo/pull/11348))
|
||||
- 为消息 Composer 新增中性色调的聚焦边框 ([#11097](https://github.com/getpaseo/paseo/pull/11097), [#11272](https://github.com/getpaseo/paseo/pull/11272),贡献者:[@Zayooo00](https://github.com/Zayooo00))
|
||||
- 改进协议解析,忽略未知的新字段并跳过无法识别的列表项,不再丢弃整条消息 ([#11284](https://github.com/getpaseo/paseo/pull/11284))
|
||||
- 在加载工作区配置前先进行过滤,提升包含大量工作区主机上的工作区查询速度 ([#11266](https://github.com/getpaseo/paseo/pull/11266))
|
||||
|
||||
### 变更
|
||||
|
||||
- 无人值守的 Hub Agent 及其子 Agent 遇到意外权限请求时,改为自动拒绝而不再阻塞直至超时 ([#11179](https://github.com/getpaseo/paseo/pull/11179))
|
||||
- 仍有待处理任务的委托 Agent 轮次结束通知,改为显示为紧凑的工具调用行,而不再显示为对等消息气泡 ([#11175](https://github.com/getpaseo/paseo/pull/11175))
|
||||
|
||||
### 修复
|
||||
|
||||
- 修复 iOS 软键盘弹出时 Composer 按钮忽略点击,以及在展开的宽屏设备上模型选择器被键盘遮挡的问题 ([#11276](https://github.com/getpaseo/paseo/pull/11276))
|
||||
- 修复在移动端 Composer 中点击全屏或退出全屏时收起键盘并闪烁错位帧的问题 ([#11326](https://github.com/getpaseo/paseo/pull/11326))
|
||||
- 修复手机照片和大量 Android 图片批次发送失败的问题,改为以分块文件上传图片并将 HEIC 照片降采样为 JPEG ([#11137](https://github.com/getpaseo/paseo/pull/11137), [#9328](https://github.com/getpaseo/paseo/pull/9328), [#11281](https://github.com/getpaseo/paseo/pull/11281),贡献者:[@Brandon168](https://github.com/Brandon168))
|
||||
- 修复 Android 系统开启粗体文字设置后应用内末尾字符和标签被截断的问题 ([#11162](https://github.com/getpaseo/paseo/pull/11162),贡献者:[@JustinJoshi](https://github.com/JustinJoshi))
|
||||
- 修复 Android 的 Provider 设置中已发现的模型列表无法滚动的问题 ([#11350](https://github.com/getpaseo/paseo/pull/11350),贡献者:[@ilteoood](https://github.com/ilteoood))
|
||||
- 修复移动端仍为当前正在查看的对话发送推送通知的问题,将原生触摸与输入计入在线活跃状态 ([#8070](https://github.com/getpaseo/paseo/pull/8070),贡献者:[@truelecter](https://github.com/truelecter))
|
||||
- 修复 iOS 和 Android 上打开 SVG 文件预览显示空白的问题 ([#9094](https://github.com/getpaseo/paseo/pull/9094))
|
||||
- 修复在包含大量工作区的主机上重连时导致移动端卡顿和 60 秒请求超时的问题 ([#11145](https://github.com/getpaseo/paseo/pull/11145),贡献者:[@TheUnlimited64](https://github.com/TheUnlimited64))
|
||||
- 修复由 Agent 控制的桌面端浏览器标签页抢占对话 Composer 键盘焦点的问题 ([#11158](https://github.com/getpaseo/paseo/pull/11158),贡献者:[@puchkoff](https://github.com/puchkoff))
|
||||
- 修复在网页端和桌面端切换到其他会话后图片灯箱仍卡在屏幕上的问题 ([#11358](https://github.com/getpaseo/paseo/pull/11358),贡献者:[@matchy233](https://github.com/matchy233))
|
||||
- 修复桌面端和网页端长对话在滚动重新测量时触发 React 错误 #185 崩溃的问题 ([#11138](https://github.com/getpaseo/paseo/pull/11138),贡献者:[@kogekiplay](https://github.com/kogekiplay))
|
||||
- 修复时间线插件跨消息复用输出 ID 时,滚动较早历史记录导致桌面端崩溃的问题 ([#8498](https://github.com/getpaseo/paseo/pull/8498),贡献者:[@kevinle128](https://github.com/kevinle128), [@ykurilov](https://github.com/ykurilov))
|
||||
- 修复在变更视图中开启长行换行时桌面端卡死的问题 ([#11113](https://github.com/getpaseo/paseo/pull/11113))
|
||||
- 修复流式输出代码块在闭合围栏尚未完整到达时高度增加一行又缩回的问题 ([#7006](https://github.com/getpaseo/paseo/pull/7006),贡献者:[@luoph](https://github.com/luoph), [@RRD-dev](https://github.com/RRD-dev))
|
||||
- 修复在 Agent 流式回复过程中发送引导消息将回复截成两半的问题 ([#5267](https://github.com/getpaseo/paseo/pull/5267))
|
||||
- 修复另一个已保存主机离线或仍在连接时,定时任务页面一直停留在加载状态的问题 ([#11361](https://github.com/getpaseo/paseo/pull/11361),贡献者:[@agenore](https://github.com/agenore))
|
||||
- 修复在另一台主机上启动新会话时提交上次记住但该主机不可用的模型,而未自动选择可用模型的问题 ([#9052](https://github.com/getpaseo/paseo/pull/9052),贡献者:[@mcowger](https://github.com/mcowger))
|
||||
- 修复 Agent 的思考强度不在其模型选项列表中时,Composer 显示错误思考强度的问题 ([#10937](https://github.com/getpaseo/paseo/pull/10937),贡献者:[@ortschun](https://github.com/ortschun))
|
||||
- 修复对话中未展开的 Windows 环境变量路径(如 `%TEMP%\file.md`)被渲染为失效链接的问题 ([#11228](https://github.com/getpaseo/paseo/pull/11228),贡献者:[@suniceman](https://github.com/suniceman))
|
||||
- 修复 macOS 上“在 Antigravity 中打开”启动 `agy` CLI 而不是 Antigravity IDE 的问题 ([#10893](https://github.com/getpaseo/paseo/pull/10893),贡献者:[@wangfh5](https://github.com/wangfh5))
|
||||
- 修复打开内置插件设置页面时显示“未安装或未列出”错误的问题 ([#11308](https://github.com/getpaseo/paseo/pull/11308))
|
||||
- 修复插件 Markdown 界面中的本地主机图片无法内联渲染的问题 ([#11171](https://github.com/getpaseo/paseo/pull/11171))
|
||||
- 修复重新加载应用后插件视图中 Agent 元数据消失的问题 ([#11265](https://github.com/getpaseo/paseo/pull/11265))
|
||||
- 修复 Android 终端输入重复字符、丢失退格键、破坏韩语/拼音/Gboard 候选词以及误处理实体回车键的问题 ([#11146](https://github.com/getpaseo/paseo/pull/11146), [#11318](https://github.com/getpaseo/paseo/pull/11318),贡献者:[@apple-ouyang](https://github.com/apple-ouyang), [@lennartschoch](https://github.com/lennartschoch), [@jasonmarkperez](https://github.com/jasonmarkperez))
|
||||
- 修复浅色模式终端向终端程序报告深色配色的问题,并新增实时浅色/深色主题切换通知 ([#11163](https://github.com/getpaseo/paseo/pull/11163), [#11312](https://github.com/getpaseo/paseo/pull/11312),贡献者:[@gstamp](https://github.com/gstamp))
|
||||
- 修复网页端和桌面端终端在 DOM 渲染器下使用界面字体而不是已配置代码字体的问题 ([#11099](https://github.com/getpaseo/paseo/pull/11099),贡献者:[@sh0nuff](https://github.com/sh0nuff))
|
||||
- 修复在负载较高的 Windows 机器上 ConPTY 启动超过五秒时终端立即退出的问题 ([#11238](https://github.com/getpaseo/paseo/pull/11238))
|
||||
- 修复在 Windows 上关闭终端或停止 daemon 时终端内程序仍在后台运行的问题 ([#11147](https://github.com/getpaseo/paseo/pull/11147))
|
||||
- 修复 Cursor 使用情况在 macOS 钥匙串、加密桌面存储和 Windows 上返回 HTTP 401 或缺失卡片的问题 ([#11148](https://github.com/getpaseo/paseo/pull/11148),贡献者:[@jasonhnd](https://github.com/jasonhnd), [@KronixDev](https://github.com/KronixDev), [@kiawin](https://github.com/kiawin), [@ChicorSun](https://github.com/ChicorSun), [@kbitz](https://github.com/kbitz))
|
||||
- 修复 OpenCode v2 Agent 在对话用量指示器中不显示套餐用量窗口,以及 Codex 使用情况读取过期 OpenCode v1 登录态的问题 ([#11153](https://github.com/getpaseo/paseo/pull/11153),贡献者:[@Wu-Jiayang](https://github.com/Wu-Jiayang))
|
||||
- 修复使用情况遗漏配置了独立凭据目录的自定义 Claude 和 Codex Provider 的问题 ([#11149](https://github.com/getpaseo/paseo/pull/11149),贡献者:[@QichangZheng](https://github.com/QichangZheng))
|
||||
- 修复使用包装命令或环境变量令牌的 Claude 和 Codex 在使用情况中显示不匹配的本地账号的问题 ([#11154](https://github.com/getpaseo/paseo/pull/11154))
|
||||
- 修复 Claude 进度更新被隐藏在折叠的思考行内,以及多块消息重复显示最后一块的问题 ([#11160](https://github.com/getpaseo/paseo/pull/11160),贡献者:[@ThePharmer](https://github.com/ThePharmer))
|
||||
- 修复并发恢复或提前取消时泄漏孤立 Claude CLI 子进程的问题,并限制无头元数据生成的并发 ([#11143](https://github.com/getpaseo/paseo/pull/11143),贡献者:[@desmond-rai](https://github.com/desmond-rai), [@nickmaglowsch](https://github.com/nickmaglowsch))
|
||||
- 修复空闲 Claude Agent 进程以退出码 0 正常退出时被标记为失败的问题 ([#11273](https://github.com/getpaseo/paseo/pull/11273),贡献者:[@lucamzanon](https://github.com/lucamzanon))
|
||||
- 修复重建对话历史时 Claude Advisor 工具调用一直停留在未完成状态的问题 ([#11202](https://github.com/getpaseo/paseo/pull/11202),贡献者:[@LucasValeQueiroz](https://github.com/LucasValeQueiroz), [@SirisZheng](https://github.com/SirisZheng))
|
||||
- 修复更新后的插件系统提示词指令未能送达已恢复的 Claude 会话的问题 ([#10917](https://github.com/getpaseo/paseo/pull/10917),贡献者:[@Tomblarom](https://github.com/Tomblarom))
|
||||
- 修复 Paseo 注入 MCP 服务器时 Codex 别名的 `-c mcp_servers.*` 覆盖配置丢失的问题 ([#11142](https://github.com/getpaseo/paseo/pull/11142))
|
||||
- 修复 OpenCode v2 模型缺少 Default 思考选项、无法恢复模型默认行为的问题 ([#11184](https://github.com/getpaseo/paseo/pull/11184),贡献者:[@3ae3ae](https://github.com/3ae3ae))
|
||||
- 修复 Pi 和 OMP 实时流式输出时思考块和回复块顺序错乱分割的问题 ([#11159](https://github.com/getpaseo/paseo/pull/11159))
|
||||
- 修复包含未关联标题或模型变更元数据的 Pi 对话历史打开为空的问题 ([#11379](https://github.com/getpaseo/paseo/pull/11379))
|
||||
- 修复在轮次进行中发送 Pi 扩展斜杠命令会中止当前回复的问题 ([#11341](https://github.com/getpaseo/paseo/pull/11341),贡献者:[@tridao](https://github.com/tridao))
|
||||
- 修复被拒绝的 Pi 历史读取或回退扩展提示导致 daemon 工作进程崩溃的问题 ([#11329](https://github.com/getpaseo/paseo/pull/11329),贡献者:[@thomasvan](https://github.com/thomasvan))
|
||||
- 修复已完成的 Pi Tintinweb 后台子 Agent 仍一直显示为运行中的问题 ([#11168](https://github.com/getpaseo/paseo/pull/11168),贡献者:[@amcfague](https://github.com/amcfague))
|
||||
- 修复后台 OMP 目录刷新触发被取消的启动模型请求的问题 ([#11129](https://github.com/getpaseo/paseo/pull/11129),贡献者:[@mcowger](https://github.com/mcowger))
|
||||
- 修复 OMP 轮次在持续流式输出或等待提问卡片超过十分钟后超时失败的问题 ([#11079](https://github.com/getpaseo/paseo/pull/11079),贡献者:[@LiebeLee](https://github.com/LiebeLee))
|
||||
- 修复 Antigravity 延迟轮次在发出中间回复后,最后一个后台工具完成时提前结束轮次的问题 ([#10924](https://github.com/getpaseo/paseo/pull/10924),贡献者:[@Juns-g](https://github.com/Juns-g))
|
||||
- 修复停止无响应的 ACP Agent 后,后续提示词一直卡在活跃前台轮次之后的问题 ([#11152](https://github.com/getpaseo/paseo/pull/11152))
|
||||
- 修复恢复的 Muse 会话丢失 daemon 和插件系统指令的问题 ([#10915](https://github.com/getpaseo/paseo/pull/10915),贡献者:[@Tomblarom](https://github.com/Tomblarom))
|
||||
- 修复监听 Unix 套接字、命名管道、非回环地址或处于 HTTP 代理后的 daemon 丢失内置 Paseo MCP 工具注入和终端活动上报的问题 ([#11144](https://github.com/getpaseo/paseo/pull/11144))
|
||||
- 修复重复重启 daemon 在临时目录中不断复制 Provider 图片附件的问题 ([#7895](https://github.com/getpaseo/paseo/pull/7895),贡献者:[@cleiter](https://github.com/cleiter))
|
||||
- 修复并发重载同一个 Agent 时返回“Unknown agent”错误的问题 ([#8369](https://github.com/getpaseo/paseo/pull/8369),贡献者:[@tieo](https://github.com/tieo))
|
||||
- 修复 `paseo agent logs --tail` 在超长对话历史上超时的问题 ([#10723](https://github.com/getpaseo/paseo/pull/10723),贡献者:[@minamorl](https://github.com/minamorl))
|
||||
- 修复 `paseo agent logs` 在 daemon 请求超时后挂起不退出的问题 ([#11360](https://github.com/getpaseo/paseo/pull/11360))
|
||||
- 修复 `paseo permit ls` 遗漏后台 Agent 以及前 200 个之后 Agent 的待处理权限的问题 ([#10655](https://github.com/getpaseo/paseo/pull/10655),贡献者:[@NightMachinery](https://github.com/NightMachinery))
|
||||
- 修复 `paseo --host host:port` 遇到 HTTP 400 时只提示检查凭据而未建议对 TLS 端点使用 `wss://` 的问题 ([#11383](https://github.com/getpaseo/paseo/pull/11383))
|
||||
|
||||
### 插件
|
||||
|
||||
- 为 Paseo MCP 和 `PluginWorkspaceSnapshot` 新增 `update_workspace` 和工作区 `metadata` 支持 ([#11166](https://github.com/getpaseo/paseo/pull/11166))
|
||||
- 修复依赖的类型声明导入 Node 环境类型时服务端插件编译失败的问题 ([#8618](https://github.com/getpaseo/paseo/pull/8618),贡献者:[@nkwib](https://github.com/nkwib))
|
||||
|
||||
## 0.18.1 - 2026-11-27
|
||||
|
||||
- **主机元数据指令**:设置一次主机级指令,即可统一控制自动生成的工作区标题、分支名、提交信息和 PR 的语言、语气与格式。([#11064](https://github.com/getpaseo/paseo/pull/11064))
|
||||
|
||||
@@ -55,6 +55,7 @@ At the start of non-trivial work, list `docs/` and skim anything relevant to the
|
||||
| [docs/permissions.md](docs/permissions.md) | Semantic daemon permissions, principals, credentials, pairing invitations, and Hub authority |
|
||||
| [docs/terminal-performance.md](docs/terminal-performance.md) | Terminal latency pipeline, coalescing/backpressure invariants, benchmark + perf spec usage |
|
||||
| [docs/terminal-rendering.md](docs/terminal-rendering.md) | Native terminal view: xterm owns the grid, cluster placement, emoji widths, mixed-direction limits, render regression |
|
||||
| [docs/timeline-sync.md](docs/timeline-sync.md) | Owned agent history, rewind retirements, live stream vs authoritative fetch, paged catch-up, client replica |
|
||||
| [docs/agent-stream-performance.md](docs/agent-stream-performance.md) | Assistant text pipeline — coalescing window, paced reveal, why arrival lumps are smoothed at render |
|
||||
| [docs/agent-stream-disclosure.md](docs/agent-stream-disclosure.md) | Expand/collapse in the chat timeline — hold contract, native anchor sequence, frame spacing, render-window cost |
|
||||
| [docs/markdown-renderer.md](docs/markdown-renderer.md) | Shared Markdown engine, the vendored library fork, native selection, links, images and library constraints |
|
||||
|
||||
@@ -39,8 +39,8 @@ An unarchived agent may be `closed` without being deleted or archived. Closing r
|
||||
processes and subscriptions while retaining its Paseo identity, persistence handle, timeline,
|
||||
workspace, labels, title, usage, attention, timestamps, and parent relationship. Opening or prompting
|
||||
the agent runs through `ensureAgentLoaded()`, which resumes the durable provider session under the
|
||||
same Paseo agent ID. Provider history is not appended again when the canonical timeline is already
|
||||
primed.
|
||||
same Paseo agent ID. Resume does not read provider history when the agent already has a timeline;
|
||||
see [owned history](timeline-sync.md#owned-history).
|
||||
|
||||
Reload releases the old runtime before resuming its durable session: an idle provider process can
|
||||
still own an exclusive writer. A close failure retains that runtime for cleanup and blocks the
|
||||
@@ -277,7 +277,8 @@ lifecycle is separate from public workspace visibility and is not a public creat
|
||||
Archive is a **soft delete**: the agent record stays on disk with `archivedAt` set, the runtime is closed, and the agent disappears from active lists. Archive is **global** — it lives on the server and propagates to every connected client.
|
||||
|
||||
Archive sets `archivedAt`, invokes the provider's native archive hook, and cascades to managed
|
||||
children.
|
||||
children. The timeline and the provider children stay, so an archived chat reads them without its
|
||||
provider; deleting the agent removes them.
|
||||
|
||||
`create_agent_request` can opt an agent into `autoArchive`. In that mode the daemon archives the agent after the first terminal turn event (`turn_completed`, `turn_failed`, or `turn_canceled`). When the agent owns an isolated workspace, auto-archive archives that workspace too; the managed worktree is removed when its final workspace reference is gone.
|
||||
|
||||
@@ -373,6 +374,8 @@ Workspace status is an aggregate activity signal computed **per `workspaceId`**.
|
||||
|
||||
Running provider-native subagents contribute `running` to the workspace owned by their parent agent. Their completed, failed, and canceled states stay in the parent's subagents track.
|
||||
|
||||
Only the parent's current runtime makes a provider child running. A child's stored status is the last report about it, and that report can come from provider history or from a runtime an earlier daemon ran, so a stored `running` child does not make the workspace running or keep the parent's runtime alive. It counts again once the live session reports it running. Closing a runtime cancels the children that runtime reported running; children it never reported keep their stored status.
|
||||
|
||||
A finished or failed workspace can be marked unread after it has been reviewed. The daemon restores
|
||||
attention on its newest eligible workspace-root agent, `error` for an agent whose lifecycle is
|
||||
`error` and `finished` otherwise, without sending a new notification. Opening a workspace restores
|
||||
|
||||
@@ -94,6 +94,7 @@ workspace for a directory clears it. The store lives in memory and resets on dae
|
||||
| `server/directory-sync/` | Daemon-global latest-state sequences for projects, workspaces, and agents |
|
||||
| `server/workspace-labels/` | Host-local label catalog, assignment mutations, and explicit subscriptions |
|
||||
| `server/agent/agent-manager.ts` | Agent lifecycle state machine, timeline tracking, subscriber management |
|
||||
| `server/agent/timeline/` | Owned agent history, provider children, rewind retirements, behind a backend |
|
||||
| `server/agent/agent-storage.ts` | File-backed JSON persistence at `$PASEO_HOME/agents/` |
|
||||
| `server/agent/tools/` | Transport-neutral catalog for workspaces, agents, permissions, and automation |
|
||||
| `server/agent/mcp-server.ts` | Thin MCP adapter that registers the Paseo tool catalog with the MCP SDK |
|
||||
@@ -402,7 +403,7 @@ initializing → idle ⇄ running
|
||||
client-side dedup; the default fetch page is 200 items.
|
||||
- Timeline row `timestamp` values are canonical daemon-owned timestamps. Providers may supply original replay timestamps, but clients must not guess timestamp trust or hide time UI based on local clock heuristics.
|
||||
- Events stream to connected clients in real time; correctness is backed by authoritative timeline fetches and paged-to-completion catch-up.
|
||||
- Agent state persists to `$PASEO_HOME/agents/{cwd-with-dashes}/{agent-id}.json`. Timeline rows are runtime memory; provider history is the durable transcript authority and resumed agents rebuild from it. That storage path is derived from `cwd`, not from workspace id.
|
||||
- Agent state persists to `$PASEO_HOME/agents/{cwd-with-dashes}/{agent-id}.json`. That storage path is derived from `cwd`, not from workspace id. Timeline rows persist in the daemon database, `$PASEO_HOME/paseo.db`. They are the transcript authority after the first import of provider history. See [owned history](timeline-sync.md#owned-history).
|
||||
|
||||
## Right-sidebar boundary: directory-backed vs workspace-owned
|
||||
|
||||
@@ -478,6 +479,7 @@ Providers that can accept native tool definitions should set `supportsNativePase
|
||||
```
|
||||
$PASEO_HOME/
|
||||
├── agents/{cwd-with-dashes}/{agent-id}.json # Agent record
|
||||
├── paseo.db # Daemon database (SQLite): agent timelines
|
||||
├── projects/projects.json # Project registry
|
||||
├── projects/workspaces.json # Workspace registry
|
||||
├── projects/icons/ # Custom project icon images
|
||||
|
||||
+41
-1
@@ -34,7 +34,7 @@ Workspace archive runs lifecycle teardown from the exact `cwd` but removes only
|
||||
`worktreeRoot` after its last active reference disappears. Worktree recovery recreates that backing
|
||||
checkout from `mainRepoRoot`, then restores the relative path from `worktreeRoot` to `cwd`.
|
||||
|
||||
Paseo uses **file-based JSON persistence** instead of a traditional database. All data is validated at runtime with Zod schemas. Most stores write atomically (write to temp file, then rename); a few still use plain `writeFile` — see each section. There is no schema-versioning/migration framework — schemas rely on optional fields with defaults for forward compatibility, with a small amount of inline normalization in `persisted-config.ts` for legacy provider/speech entries.
|
||||
Paseo persists most stores as JSON files, and agent timelines in the [daemon database](#daemon-database). JSON data is validated at runtime with Zod schemas. Most JSON stores write atomically (write to temp file, then rename); a few still use plain `writeFile` — see each section. JSON stores have no schema-versioning/migration framework — schemas rely on optional fields with defaults for forward compatibility, with a small amount of inline normalization in `persisted-config.ts` for legacy provider/speech entries.
|
||||
|
||||
All server-side stores live under `$PASEO_HOME` (defaults to `~/.paseo`).
|
||||
|
||||
@@ -53,6 +53,7 @@ $PASEO_HOME/
|
||||
├── daemon-keypair.json # E2EE keypair for relay (mode 0600)
|
||||
├── paseo.pid # Daemon PID lock file
|
||||
├── local-credential # Per-run local client credential (mode 0600)
|
||||
├── paseo.db # Daemon database (SQLite, with -wal and -shm files)
|
||||
├── daemon.log # Default log file (path configurable)
|
||||
├── agents/
|
||||
│ └── {sanitized-cwd}/
|
||||
@@ -181,6 +182,45 @@ Terminal activity contributes to the workspace status bucket **per `workspaceId`
|
||||
|
||||
---
|
||||
|
||||
## Daemon database
|
||||
|
||||
`$PASEO_HOME/paseo.db` is one SQLite file that the daemon opens at startup with `node:sqlite`
|
||||
(`packages/server/src/server/database/`). Agent timelines are its only store today. Each store is a
|
||||
`SchemaModule`: its own table-name prefix and an append-only list of migrations.
|
||||
|
||||
- **Migrations.** Startup runs every module's pending migrations in one transaction, so a failed
|
||||
migration leaves the file as it was. `schema_versions` records each module's version and
|
||||
`min_reader_version`. Mark a migration `breaking` when an older daemon cannot read the result,
|
||||
for example a dropped or renamed column. An older daemon then refuses to start with
|
||||
`DatabaseSchemaTooNewError`. Additive migrations leave older daemons working, and they ignore
|
||||
modules they do not know. This matters because the app and the daemon update separately, and a
|
||||
user can run an older daemon on the same `$PASEO_HOME`.
|
||||
- **Failure.** A file that SQLite cannot open stops the daemon with `DatabaseOpenError`, which
|
||||
names the path. The daemon does not delete or recreate the file.
|
||||
- **Access.** The file holds every prompt and reply, so the daemon sets it and its `-wal` and `-shm`
|
||||
files to mode `0600` on every open. SQLite gives the WAL files it creates the mode of the database
|
||||
file.
|
||||
- **Durability.** The database uses WAL with `synchronous = NORMAL`. A power loss can drop the
|
||||
last commits but does not corrupt the file.
|
||||
- **Checkpoints.** A checkpoint syncs the file to disk and takes up to 100 ms. SQLite's
|
||||
auto-checkpoint runs it on the committing thread, which stalled the event loop during streaming.
|
||||
The daemon turns it off and checkpoints from a worker thread with its own connection. If the
|
||||
worker exits, the daemon turns auto-checkpoint back on.
|
||||
- **Transactions.** `write` and `read` callbacks are synchronous, so a transaction never spans an
|
||||
`await` and transactions never interleave.
|
||||
- **Node.** `node:sqlite` needs Node 22.16 or later. Node 22 prints an experimental warning once,
|
||||
when the daemon opens the database.
|
||||
|
||||
### Agent timelines
|
||||
|
||||
`AgentTimeline` owns each agent's history, and its SQLite backend stores the projected rows, the
|
||||
source ranges, retirements, the open rewind, and provider children in `timeline_*` tables. The text
|
||||
of a streamed assistant or reasoning message is stored as one chunk per source event, beside its
|
||||
row, so a chunk never rewrites the message. An earlier file store rewrote the whole transcript on
|
||||
every update. See [owned history](timeline-sync.md#owned-history).
|
||||
|
||||
---
|
||||
|
||||
## 2. Daemon Configuration
|
||||
|
||||
**Path:** `$PASEO_HOME/config.json`
|
||||
|
||||
@@ -523,6 +523,8 @@ Measured bundle size for a standard Expo web export:
|
||||
- gzip: 2.55 MiB
|
||||
- brotli: 1.93 MiB
|
||||
|
||||
`npm run build:desktop` runs the same `scripts/precompress-assets.mjs` over `packages/app/dist` before electron-builder copies it to `app-dist`, so the desktop-served UI also gets `.br`/`.gz` siblings.
|
||||
|
||||
The desktop-managed daemon disables the bundled web UI by default (`PASEO_WEB_UI_ENABLED=false`) because the desktop app already ships the renderer as `app-dist`. Shipping the same assets again inside `@getpaseo/server` would duplicate the ~10.8 MiB install. Desktop packaging also excludes `node_modules/@getpaseo/server/dist/server/web-ui/**` from the packaged app.
|
||||
|
||||
## Built workspace packages
|
||||
|
||||
@@ -36,6 +36,10 @@ ordinary `WorkspaceTab` (`SheetTab` in the store) and is an `IsolatedBottomSheet
|
||||
other sheet in the app, so it sits on the one app-wide stack: a sheet opened from any sheet lands on
|
||||
top of it, and closing the top sheet (drag, Close, backdrop, or Android Back) uncovers the one below.
|
||||
|
||||
Because that stack is app-wide and hidden workspace screens stay mounted, a sheet is not presented
|
||||
until its workspace has been on screen. A target opened in a workspace before the user gets there
|
||||
waits in the store and appears on arrival.
|
||||
|
||||
A subagent chosen from the subagents list is the exception. It opens as a page of the list's own
|
||||
sheet and replaces the list in place: Back returns to the list, Close ends both, and Open parent
|
||||
closes the list, landing on the pane the list was opened from. The store's `selectSheetTab` describes
|
||||
|
||||
+11
-4
@@ -447,10 +447,17 @@ wide layouts keep local geometry. That export is
|
||||
what `patches/@gorhom+bottom-sheet+*.patch` adds.
|
||||
|
||||
A sheet whose owner may veto the close (unsaved work) passes `enableDismissOnClose={false}`. Every
|
||||
close path then parks the sheet at index -1 with its content mounted; the owner hears
|
||||
`onChange(-1)`, runs its guard, and either snaps back to 0 or drops its state, which unmounts the
|
||||
sheet and takes it off the stack. Calling `dismiss()` on such a sheet bypasses the guard and
|
||||
unmounts it, so its backdrop and Back press call `close()`.
|
||||
close path then parks the sheet at index -1 with its content mounted; the owner runs its guard and
|
||||
either snaps back to 0 or drops its state, which unmounts the sheet and takes it off the stack.
|
||||
Calling `dismiss()` on such a sheet bypasses the guard and unmounts it, so its backdrop and Back
|
||||
press call `close()`.
|
||||
|
||||
Run that guard from the wrapper's `onClosed`. Gorhom only calls `onChange` when a close ends at a
|
||||
different index than the one it already recorded, and an interrupted mount animation leaves that
|
||||
record at -1, so the close that follows is invisible: the sheet parks with its backdrop still over
|
||||
the app, and every tap in the covered area is lost. `onClosed` watches the close animation settle at
|
||||
the closed detent and reports it either way. Keeping `onChange` as well is harmless as long as the
|
||||
guard is idempotent.
|
||||
|
||||
The wrapper must give Gorhom an object ref. Gorhom accepts a callback ref at the React boundary
|
||||
but stores it in the modal queue and later reads `.current`; provider dismissal, replacement,
|
||||
|
||||
@@ -26,7 +26,7 @@ The package keeps the npm tarball's layout, including its build output:
|
||||
|
||||
- Metro, Vitest and TypeScript load `lib/`, not `src/`. A JavaScript change edits `src/` and the matching `lib/module` and `lib/typescript` files.
|
||||
- `android/generated` and `ios/generated` are checked-in codegen output (`includesGeneratedCode`). A change to a native component spec regenerates both; `scripts/postinstall-patches.test.mjs` compares them against the specs.
|
||||
- `src/web/wasm/md4c.js` and `lib/module/web/wasm/md4c.js` are an Emscripten build of `cpp/md4c`. A parser change rebuilds them with upstream's `packages/core/cpp/wasm/build.sh`.
|
||||
- `src/web/wasm/md4c.js` and `lib/module/web/wasm/md4c.js` are an Emscripten build of `cpp/md4c`, `cpp/parser` and `cpp/wasm`. A parser change rebuilds both, or web keeps the old behavior while iOS and Android change. Run `cpp/wasm/build.sh` with `OUT_DIR` set to `src/web/wasm`, in `emscripten/emsdk:4.0.10` with the `-s GROWABLE_ARRAYBUFFERS=0` line removed. That version reproduces the committed JavaScript glue and has no such setting. The `lib/module` copy is the Babel output of the new file.
|
||||
- Upstream's Gradle, CMake and CocoaPods scripts detect upstream's own monorepo by the paths `packages/core` and a root `vendor/`. Do not add either path to this repository.
|
||||
- `postinstall.mjs` downloads the tree-sitter grammars into the ignored `cpp/highlight/vendor/grammars` and `vendor/tree-sitter`. The `enriched-markdown` block in `packages/app/package.json` chooses the languages.
|
||||
|
||||
@@ -42,7 +42,7 @@ Some fork changes are backports. A sync past the upstream version drops them in
|
||||
|
||||
## Engine constraints
|
||||
|
||||
Math and video are disabled. Task lists and admonitions are enabled; task checkboxes are read-only. Source adaptation spaces adjacent empty GFM table delimiters before escaping prose spoiler delimiters and decodes entity text before the engine can discard it. Code spans and fences keep their literal source. Comment HTML is normalized to Markdown before parsing; details show their summary and body expanded.
|
||||
Math and video are disabled. Task lists and admonitions are enabled; task checkboxes are read-only. Source adaptation spaces adjacent empty GFM table delimiters before escaping prose spoiler delimiters and decodes entity text before the engine can discard it. Code spans and fences keep their literal source. Comment HTML is normalized to Markdown before parsing; details show their summary and body expanded. `<br>` becomes a Markdown hard break, except inside a table, where a newline would end the row. There it becomes U+2028, and `cpp/parser/MD4CParser.cpp` turns U+2028 back into a line break in table cell text, never in code.
|
||||
|
||||
Mermaid fences use the existing isolated diagram runtime and fullscreen viewer. Web dispatches them through the library’s code-block override. Native has no block-renderer hook, so the renderer extracts only Mermaid fences and places the existing WebView host between library-rendered segments. This is the only block exception; see [native selection limitations](native-text-selection.md) for diagram grouping and leading inline images. Streaming keeps the last valid diagram visible while the next revision renders.
|
||||
|
||||
|
||||
+6
-2
@@ -267,6 +267,10 @@ Plugin UI runs on desktop and mobile across multiple themes: color every `Text`
|
||||
`theme.colors.foreground` or `theme.colors.foregroundMuted`, and size layout from `layout.compact`.
|
||||
See `public-docs/plugins/reference.md`.
|
||||
|
||||
A plugin reads and arranges panes and tabs through `PluginWorkspaceLayout`. Its host,
|
||||
`packages/app/src/plugins/workspace-layout/`, is a facade over the layout store and `workspace-tabs`,
|
||||
so add behavior to those owners and keep layout mechanics out of the SDK types.
|
||||
|
||||
### SDK import boundaries
|
||||
|
||||
Classify every SDK export before adding it. All client entry points and implementations live under
|
||||
@@ -1018,8 +1022,8 @@ payload that cannot be rendered intact. The daemon advertises this RPC through
|
||||
|
||||
`addSlashCommand` registers an agent- or workspace-context command in the composer. The
|
||||
callback runs in the app, receives the trimmed text after the command name as `args`, and receives
|
||||
the same `paseo`, `rpc`, `openScreen`, workspace, agent, and `openPanel` capabilities as the matching
|
||||
Command Center callback.
|
||||
the same `paseo`, `rpc`, `openScreen`, workspace, agent, and `workspaceLayout` capabilities as the
|
||||
matching Command Center callback.
|
||||
|
||||
```ts
|
||||
client.addSlashCommand({
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
# Online client replacement: timeline recovery
|
||||
|
||||
Verified on macOS arm64 with Node 22.20.0, Chromium 145 (Playwright), and a real isolated daemon. Replies use the deterministic test provider; no external AI API is involved.
|
||||
|
||||
## Reproduction
|
||||
|
||||
1. Open two chats on one host and return to the first.
|
||||
2. Delay the active connection's real pong frames by 1 second, forwarding all real traffic, and wait for a measured liveness RTT.
|
||||
3. Add another direct endpoint for the same daemon.
|
||||
4. Advance the browser clock in 10-second steps. Each step waits for real delayed heartbeat replies and the public probe-cycle completion barrier, including replacement handshakes. The production selector and its timer constants are unchanged.
|
||||
5. Verify that every observed host snapshot stays online with a client, then confirm exactly one client-generation change to the faster endpoint.
|
||||
6. Require the Reconnecting alert to disappear within 3 seconds and verify a new message in the visible chat.
|
||||
7. Commit a message to the hidden second chat before reopening it. Verify that message is recovered, then verify another live message.
|
||||
|
||||
The two paths are localhost and 127.0.0.1 to the same daemon. The test does not force host state or replace a private client field. It controls browser time, not the daemon clock or real socket responses. Subscription assertions require the needed agents without requiring all other agents to be absent; exact matching remains the shared helper's default. The test has a 180-second timeout and a bounded clock-step budget allowing one candidate backoff. Observers, handles, timers, and scenario data are cleaned up even on failure.
|
||||
|
||||
## Before: exact final test source
|
||||
|
||||
Temporarily remove only the production `sync.setConnected(...)` seed, run the final regression, and restore the source in a `finally` block. The host remains online and changes to generation 2, but Reconnecting does not settle:
|
||||
|
||||
```text
|
||||
Error: expect(locator).toHaveCount(expected) failed
|
||||
Locator: getByRole('alert').filter({ hasText: 'Reconnecting' })
|
||||
Expected: 0
|
||||
Received: 1
|
||||
Timeout: 3000ms
|
||||
1 failed
|
||||
```
|
||||
|
||||
The frame below is extracted without modification from that final RED trace while the assertion was waiting, before fixture cleanup.
|
||||
|
||||

|
||||
|
||||
## After
|
||||
|
||||
Restore the production seed without changing the test files, then run:
|
||||
|
||||
```sh
|
||||
npm run test:e2e --workspace=@getpaseo/app -- \
|
||||
e2e/browser/viewed-agent-timelines.spec.ts \
|
||||
--grep 'online connection replacement|visible chat reports updating until reconnect' \
|
||||
--workers=1
|
||||
```
|
||||
|
||||
```text
|
||||
✓ an online connection replacement keeps every open chat synchronized (1.6m)
|
||||
✓ a visible chat reports updating until reconnect catch-up completes (35.9s)
|
||||
2 passed (2.3m)
|
||||
```
|
||||
|
||||
The online replacement case previously took 4.8 minutes with wall-clock probe waits. The final controlled-clock run takes 1.6 minutes. [Recorded hashes](red-green.json) confirm both test files are identical between final RED and GREEN and the production source was restored exactly.
|
||||
|
||||

|
||||
|
||||
## Other checks
|
||||
|
||||
```sh
|
||||
npm run typecheck
|
||||
npm run lint -- packages/app/e2e/browser/viewed-agent-timelines.spec.ts packages/app/e2e/support/helpers/timeline-delivery.ts
|
||||
npm run format
|
||||
```
|
||||
|
||||
Whole-workspace typecheck exited 0. Changed-file lint reported `Found 0 warnings and 0 errors.` Formatting passed.
|
||||
|
||||
The original runtime fix is unchanged by this test follow-up. Its previous native validation remains: both unmodified and fixed renderers exported with `PASEO_WEB_PLATFORM=electron npm exec -- expo export --platform web`; server dependencies and desktop main built through repository scripts; both packaged locally with `electron-builder --config electron-builder.yml --publish never --mac --arm64 --dir -c.mac.notarize=false`, with certificate discovery disabled.
|
||||
|
||||
The existing `packages/desktop/e2e/packaged-app-smoke.js --app <built-app>` passed for both packages with fresh temporary user data/daemon homes and loopback ports:
|
||||
|
||||
```text
|
||||
Packaged desktop smoke: real app renderer and preload bridge loaded
|
||||
Packaged desktop smoke: renderer-started desktop daemon reported running
|
||||
Packaged desktop smoke: every built-in plugin started
|
||||
Packaged desktop smoke: running bundled CLI shim daemon status
|
||||
Packaged desktop smoke: creating terminal through bundled CLI shim
|
||||
Packaged desktop smoke: terminal hook command completed
|
||||
Packaged desktop smoke passed: real renderer and preload loaded; renderer-started desktop daemon;
|
||||
CLI shim daemon status and terminal smoke succeeded
|
||||
```
|
||||
|
||||
The final summary omits ephemeral PID/listen values. The native smoke establishes packaged startup and terminal functionality, not native reconnect coverage.
|
||||
|
||||
## Coverage limits
|
||||
|
||||
- Web: real browser/daemon regression, with controlled browser scheduling, before and after.
|
||||
- macOS desktop: prior arm64 packaging and native startup/CLI/terminal smoke of the unchanged runtime fix.
|
||||
- iOS, Android, Windows desktop, Linux desktop: not tested.
|
||||
- External relay transport and a real provider turn: not tested by this regression.
|
||||
- The test requires eventual history recovery; it does not change the product's hidden-chat subscription policy or prohibit every transient toast frame.
|
||||
- These are local results. No full-suite or GitHub CI pass is claimed.
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 128 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 57 KiB |
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"production_source_restored": true,
|
||||
"test_sha256": {
|
||||
"packages/app/e2e/browser/viewed-agent-timelines.spec.ts": "1857d0ca187648d8377557cd82428a64546530795cf884c7474e921a1118c003",
|
||||
"packages/app/e2e/support/helpers/timeline-delivery.ts": "23d0adb9f92daac6d0841d584abb7aa272a2981861d7d211c8213e98a9af90da"
|
||||
},
|
||||
"red": {
|
||||
"result": "expected failure",
|
||||
"assertion": "Reconnecting alert expected 0, received 1",
|
||||
"timeout_ms": 3000
|
||||
},
|
||||
"green": {
|
||||
"passed": 2,
|
||||
"online_replacement_duration": "1.6m",
|
||||
"ordinary_reconnect_duration": "35.9s",
|
||||
"total_duration": "2.3m"
|
||||
}
|
||||
}
|
||||
+68
-11
@@ -5,15 +5,9 @@ Agent chat delivery has two paths:
|
||||
1. **Live stream** — `agent_stream` WebSocket messages for immediacy. These may be delta-shaped lifecycle updates.
|
||||
2. **Authoritative history** — `fetch_agent_timeline_request` for correctness. This always returns full projected timeline items, never lifecycle deltas.
|
||||
|
||||
The daemon retains projected items in memory. Each source event advances the stream sequence,
|
||||
then replaces the previous tool state or merges into the current text item. Intermediate payloads
|
||||
are never retained for history or catch-up. Provider history is the durable transcript authority
|
||||
and rebuilds the projection when an agent resumes.
|
||||
|
||||
Pagination bounds each read, not total resident history. Active and idle agents retain their
|
||||
projected transcript; archive releases it and later history reads rebuild it from the provider.
|
||||
Streaming overhead must remain proportional to the retained transcript. Cumulative text snapshots
|
||||
must be released after their deltas have been consumed.
|
||||
Pagination bounds each read, not total resident history. Streaming overhead must remain
|
||||
proportional to the retained transcript. Cumulative text snapshots must be released after their
|
||||
deltas have been consumed.
|
||||
|
||||
The invariants are:
|
||||
|
||||
@@ -32,6 +26,50 @@ bounded item is used for runtime timeline rows and live stream events. Provider
|
||||
applies the same rule so reopening an agent cannot restore an oversized payload. Fetches apply it
|
||||
again to assistant and reasoning rows the projection merges from many chunks.
|
||||
|
||||
## Owned history
|
||||
|
||||
The daemon owns each agent's history in `AgentTimeline`
|
||||
(`packages/server/src/server/agent/timeline/`): one ordered history per agent, with each provider
|
||||
child's descriptor and history in a child scope of the same agent. Each source event advances the
|
||||
stream sequence, then replaces the previous tool state or merges into the current text item.
|
||||
Intermediate payloads are never retained for history or catch-up.
|
||||
|
||||
History is append-only: rewind, import, reload and archive never delete or rewrite a row. Only
|
||||
deleting the agent, or a provider removing one of its own children, deletes history.
|
||||
|
||||
- **Rewind** retires a range of rows. They leave the conversation and stay stored, in the same
|
||||
epoch. See [Rewind retires rows](#rewind-retires-rows).
|
||||
- **Provider history** is imported only into an agent that has no history. After that, resume
|
||||
does not read it. Reload agent and Unarchive require the provider history to start with the
|
||||
same prompt IDs and text in order. They then append whole new turns, starting at the next
|
||||
prompt. Existing replies, including partial replies, stay as recorded. If the prompts differ,
|
||||
for example because the provider stored expanded attachment text, the chat stays unchanged and
|
||||
Paseo reports a mismatch. A provider child Paseo already holds, listed or retired, is never imported again.
|
||||
- **Archive and reload** keep the history and the provider children. An archived chat reads them
|
||||
without its provider. Opening a stored agent that has no provider session to resume starts its
|
||||
first session on the same history.
|
||||
- **Delete** removes the agent's history and every child's, retired ones included, before the
|
||||
agent record. If the history cannot be removed, the request fails and the agent stays listed. The
|
||||
user can keep using it and delete it again.
|
||||
|
||||
`epoch` is the stored history's identity, minted once when the history is created.
|
||||
|
||||
`AgentTimeline` serializes every operation of one agent, child scopes included, and keeps its
|
||||
state in an `AgentTimelineBackend`: the sequence, the rows and retirements, prompt identities, the
|
||||
open rewind, and the children. The backend contract suite is `agent-timeline.test.ts`, run over
|
||||
`TIMELINE_CONTRACT_BACKENDS` in `timeline/testing.ts`. The daemon uses the SQLite backend in the
|
||||
[daemon database](data-model.md#daemon-database). History, retirements, the open rewind, and
|
||||
provider children survive a daemon restart in the same epoch, so clients keep their cursors. A
|
||||
closed or archived agent holds no history in memory. Each fetch reads the page from the database
|
||||
and starts no provider. An internal agent, such as the one that writes a commit message, keeps its
|
||||
history in a memory backend instead, so it leaves nothing on disk. The memory backend also serves
|
||||
tests.
|
||||
|
||||
An open rewind is stored with the history. Resuming an agent whose history holds one settles it
|
||||
before the agent takes prompts: a recorded provider cut is committed, and an unknown outcome is
|
||||
judged from the resumed provider history. When that history proves nothing, the rewind stays open
|
||||
and the agent refuses prompts with the unknown-outcome error.
|
||||
|
||||
## Presence is not delivery
|
||||
|
||||
Client heartbeat reports presence:
|
||||
@@ -173,7 +211,7 @@ or retry backoff. This cannot keep a mobile socket alive after the operating sys
|
||||
bookkeeping without replacing timeline arrays, preserving an upward-scrolled viewport.
|
||||
- When the page overlaps or is adjacent to the local end cursor, only projected items newer than
|
||||
that cursor are applied. Already-covered rows are not replayed.
|
||||
- A true middle gap, epoch change, or rewind atomically replaces stale canonical history with the
|
||||
- A true middle gap or epoch change atomically replaces stale canonical history with the
|
||||
latest tail. The replacement reconciles positioned live rows beyond its coverage and unresolved
|
||||
local submissions; it never retains two discontiguous canonical ranges.
|
||||
|
||||
@@ -186,6 +224,24 @@ history replay. The pending approval UI can hide that tool from presentation, bu
|
||||
must retain its position. Creating a new history card on rejection places it after the prompt that
|
||||
rejected it; changing steer-event ordering would also put new assistant output before that prompt.
|
||||
|
||||
## Rewind retires rows
|
||||
|
||||
A conversation rewind commits a retirement `{ seq, retireFromSeq }`: active rows anchored in
|
||||
`[retireFromSeq, seq)` leave the conversation, and `seq` is the retirement's own position in the
|
||||
sequence. The provider children spawned by retired tool calls, and their descendants, are retired
|
||||
in the same commit. They leave the listing, keep their history, and drop late provider events.
|
||||
|
||||
Clients learn of a retirement live through `agent.timeline.rewind`, and on pages through
|
||||
`retirements`, which lists the retirements whose `seq` lies inside the page's span. The client
|
||||
drops the rows it holds in that range; rows without a timeline position are unechoed local sends
|
||||
and stay. Retired ranges and the retirement's `seq` count as covered, so forward cursors advance
|
||||
through them. Tail, before and prompt-jump pages are served from active rows, so one served before
|
||||
a retirement the client already applied is stale and is refetched (`viewed-timeline-sync.ts`).
|
||||
|
||||
Clients without `timeline_rewind_operations` cannot drop retired rows. For them the session derives
|
||||
a wire epoch that changes with each retirement, so they take the destructive replacement they
|
||||
always took on rewind. The shim is tagged `COMPAT(timelineRewindOperations)`.
|
||||
|
||||
## Provider child history
|
||||
|
||||
Child transcripts use the same projected-page reconciliation as the main conversation. The client
|
||||
@@ -379,7 +435,7 @@ the draft-create handoff is the one boundary that also permits the legacy canoni
|
||||
arrived first. Generic reducers and consumers do not reimplement message identity matching.
|
||||
|
||||
Ordinary bootstrap, same-epoch reset, and catch-up replacement preserve unmatched locally submitted
|
||||
rows because a provider may never echo them. A known epoch change or rewind replaces history and
|
||||
rows because a provider may never echo them. A known epoch change replaces history and
|
||||
drops acknowledged local rows omitted by the new canonical epoch; every transaction not yet
|
||||
acknowledged by the provider, and no other local row, crosses that destructive boundary. A cold
|
||||
reset without an existing epoch is destructive because the client has no continuity anchor.
|
||||
@@ -395,6 +451,7 @@ canonical assistant prefix, it stays in the head lane. No row may be returned in
|
||||
|
||||
## Relevant code
|
||||
|
||||
- Server owned history: `packages/server/src/server/agent/timeline/`
|
||||
- Server live stream forwarding: `packages/server/src/server/session.ts`
|
||||
- App sync planning: `packages/app/src/timeline/timeline-sync-plan.ts`
|
||||
- App viewed-agent synchronization: `packages/app/src/timeline/viewed-timeline-sync.ts`
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
- Redesigned model picker: Pick models from a two-pane desktop view with cross-provider search, an in-place phone drawer with a thinking slider, and per-provider model lists in settings.
|
||||
- File actions and filter: Filter the Files tree by name, and reveal, open in your default app, download, or copy paths from chat file links, file tabs, and sidebar trees.
|
||||
|
||||
Full notes: https://paseo.sh/changelog
|
||||
@@ -0,0 +1,4 @@
|
||||
- Redesigned model picker: Pick models from a two-pane desktop view with cross-provider search, an in-place phone drawer with a thinking slider, and per-provider model lists in settings.
|
||||
- File actions and filter: Filter the Files tree by name, and reveal, open in your default app, download, or copy paths from chat file links, file tabs, and sidebar trees.
|
||||
|
||||
Full notes: https://paseo.sh/changelog
|
||||
@@ -0,0 +1,4 @@
|
||||
- Redesigned model picker: Pick models from a two-pane desktop view with cross-provider search, an in-place phone drawer with a thinking slider, and per-provider model lists in settings.
|
||||
- File actions and filter: Filter the Files tree by name, and reveal, open in your default app, download, or copy paths from chat file links, file tabs, and sidebar trees.
|
||||
|
||||
Full notes: https://paseo.sh/changelog
|
||||
@@ -0,0 +1,4 @@
|
||||
- Redesigned model picker: Pick models from a two-pane desktop view with cross-provider search, an in-place phone drawer with a thinking slider, and per-provider model lists in settings.
|
||||
- File actions and filter: Filter the Files tree by name, and reveal, open in your default app, download, or copy paths from chat file links, file tabs, and sidebar trees.
|
||||
|
||||
Full notes: https://paseo.sh/changelog
|
||||
+1
-1
@@ -1 +1 @@
|
||||
sha256-34bUBmRmjekbUSp93597GLTmSWKt23TCHaK3ViXG+iU=
|
||||
sha256-ZVIrRfb7oyTwx7kz6F51hs/ctT45qUdZM4v0QRLW9zA=
|
||||
|
||||
Generated
+49
-30
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "paseo",
|
||||
"version": "0.18.1",
|
||||
"version": "0.18.2",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "paseo",
|
||||
"version": "0.18.1",
|
||||
"version": "0.18.2",
|
||||
"hasInstallScript": true,
|
||||
"license": "Apache-2.0",
|
||||
"workspaces": [
|
||||
@@ -46,6 +46,9 @@
|
||||
"react-dom": "19.2.3",
|
||||
"typescript": "^5.9.3",
|
||||
"ws": "^8.20.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22.16.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@0no-co/graphql.web": {
|
||||
@@ -37543,7 +37546,7 @@
|
||||
},
|
||||
"packages/app": {
|
||||
"name": "@getpaseo/app",
|
||||
"version": "0.18.1",
|
||||
"version": "0.18.2",
|
||||
"dependencies": {
|
||||
"@codemirror/commands": "6.10.4",
|
||||
"@codemirror/language": "6.12.4",
|
||||
@@ -39696,13 +39699,13 @@
|
||||
},
|
||||
"packages/cli": {
|
||||
"name": "@getpaseo/cli",
|
||||
"version": "0.18.1",
|
||||
"version": "0.18.2",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@clack/prompts": "^1.0.0",
|
||||
"@getpaseo/client": "0.18.1",
|
||||
"@getpaseo/protocol": "0.18.1",
|
||||
"@getpaseo/server": "0.18.1",
|
||||
"@getpaseo/client": "0.18.2",
|
||||
"@getpaseo/protocol": "0.18.2",
|
||||
"@getpaseo/server": "0.18.2",
|
||||
"chalk": "^5.3.0",
|
||||
"commander": "^12.0.0",
|
||||
"mime-types": "^2.1.35",
|
||||
@@ -39721,6 +39724,9 @@
|
||||
"typescript": "^5.2.2",
|
||||
"vitest": "^4.1.6",
|
||||
"zx": "^8.8.5"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22.16.0"
|
||||
}
|
||||
},
|
||||
"packages/cli/node_modules/@vitest/expect": {
|
||||
@@ -39949,11 +39955,11 @@
|
||||
},
|
||||
"packages/client": {
|
||||
"name": "@getpaseo/client",
|
||||
"version": "0.18.1",
|
||||
"version": "0.18.2",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@getpaseo/protocol": "0.18.1",
|
||||
"@getpaseo/relay": "0.18.1",
|
||||
"@getpaseo/protocol": "0.18.2",
|
||||
"@getpaseo/relay": "0.18.2",
|
||||
"ws": "^8.20.0",
|
||||
"zod": "^4.4.3"
|
||||
},
|
||||
@@ -39965,7 +39971,7 @@
|
||||
},
|
||||
"packages/desktop": {
|
||||
"name": "@getpaseo/desktop",
|
||||
"version": "0.18.1",
|
||||
"version": "0.18.2",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@getpaseo/cli": "*",
|
||||
@@ -40208,7 +40214,7 @@
|
||||
},
|
||||
"packages/expo-two-way-audio": {
|
||||
"name": "@getpaseo/expo-two-way-audio",
|
||||
"version": "0.18.1",
|
||||
"version": "0.18.2",
|
||||
"license": "MIT",
|
||||
"devDependencies": {
|
||||
"@types/jest": "^29.5.14",
|
||||
@@ -40254,7 +40260,7 @@
|
||||
},
|
||||
"packages/highlight": {
|
||||
"name": "@getpaseo/highlight",
|
||||
"version": "0.18.1",
|
||||
"version": "0.18.2",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@codemirror/language": "6.12.4",
|
||||
@@ -40284,7 +40290,7 @@
|
||||
},
|
||||
"packages/plugin": {
|
||||
"name": "@getpaseo/plugin",
|
||||
"version": "0.18.1",
|
||||
"version": "0.18.2",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@agentclientprotocol/sdk": "^1.4.0",
|
||||
@@ -40292,8 +40298,8 @@
|
||||
"use-sync-external-store": "^1.6.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@getpaseo/client": "0.18.1",
|
||||
"@getpaseo/protocol": "0.18.1",
|
||||
"@getpaseo/client": "0.18.2",
|
||||
"@getpaseo/protocol": "0.18.2",
|
||||
"@types/node": "^20.9.0",
|
||||
"@types/react": "~19.2.0",
|
||||
"react": "19.2.3",
|
||||
@@ -40303,8 +40309,8 @@
|
||||
"zod": "^4.4.3"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@getpaseo/client": "0.18.1",
|
||||
"@getpaseo/protocol": "0.18.1",
|
||||
"@getpaseo/client": "0.18.2",
|
||||
"@getpaseo/protocol": "0.18.2",
|
||||
"react": ">=19.1.0 <20",
|
||||
"react-native": ">=0.81.5",
|
||||
"zod": "^4.4.3"
|
||||
@@ -40326,7 +40332,7 @@
|
||||
},
|
||||
"packages/protocol": {
|
||||
"name": "@getpaseo/protocol",
|
||||
"version": "0.18.1",
|
||||
"version": "0.18.2",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"semver": "^7.8.5",
|
||||
@@ -40353,7 +40359,7 @@
|
||||
}
|
||||
},
|
||||
"packages/react-native-enriched-markdown": {
|
||||
"version": "0.18.1",
|
||||
"version": "0.18.2",
|
||||
"hasInstallScript": true,
|
||||
"license": "MIT",
|
||||
"peerDependencies": {
|
||||
@@ -40369,7 +40375,7 @@
|
||||
},
|
||||
"packages/relay": {
|
||||
"name": "@getpaseo/relay",
|
||||
"version": "0.18.1",
|
||||
"version": "0.18.2",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@noble/ciphers": "^2.4.0",
|
||||
@@ -40591,17 +40597,17 @@
|
||||
},
|
||||
"packages/server": {
|
||||
"name": "@getpaseo/server",
|
||||
"version": "0.18.1",
|
||||
"version": "0.18.2",
|
||||
"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.18.1",
|
||||
"@getpaseo/highlight": "0.18.1",
|
||||
"@getpaseo/plugin": "0.18.1",
|
||||
"@getpaseo/protocol": "0.18.1",
|
||||
"@getpaseo/relay": "0.18.1",
|
||||
"@getpaseo/client": "0.18.2",
|
||||
"@getpaseo/highlight": "0.18.2",
|
||||
"@getpaseo/plugin": "0.18.2",
|
||||
"@getpaseo/protocol": "0.18.2",
|
||||
"@getpaseo/relay": "0.18.2",
|
||||
"@isaacs/ttlcache": "^2.1.4",
|
||||
"@modelcontextprotocol/node": "2.1.2",
|
||||
"@modelcontextprotocol/sdk": "1.29.0",
|
||||
@@ -40649,7 +40655,7 @@
|
||||
"@playwright/test": "^1.56.1",
|
||||
"@types/express": "^4.17.20",
|
||||
"@types/markdown-it": "^14.2.0",
|
||||
"@types/node": "^20.9.0",
|
||||
"@types/node": "^22.16.0",
|
||||
"@types/qrcode": "^1.5.6",
|
||||
"@types/uuid": "^9.0.7",
|
||||
"@types/ws": "^8.5.8",
|
||||
@@ -40657,6 +40663,9 @@
|
||||
"cross-env": "^10.1.0",
|
||||
"tsx": "^4.6.0",
|
||||
"vitest": "^4.1.6"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22.16.0"
|
||||
}
|
||||
},
|
||||
"packages/server/node_modules/@esbuild/aix-ppc64": {
|
||||
@@ -41104,6 +41113,16 @@
|
||||
"@types/mdurl": "^2"
|
||||
}
|
||||
},
|
||||
"packages/server/node_modules/@types/node": {
|
||||
"version": "22.20.5",
|
||||
"resolved": "https://registry.npmjs.org/@types/node/-/node-22.20.5.tgz",
|
||||
"integrity": "sha512-U2+DNr+wSjpsTS/wZGYHq7GcwfuSmKiKvoPvK22zwTlRhU91yOniN4qRR5KhIjvif7ysw/dz/hKmfDH0Ris4aA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"undici-types": "~6.21.0"
|
||||
}
|
||||
},
|
||||
"packages/server/node_modules/@vitest/expect": {
|
||||
"version": "4.1.6",
|
||||
"resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-4.1.6.tgz",
|
||||
@@ -41552,7 +41571,7 @@
|
||||
},
|
||||
"packages/website": {
|
||||
"name": "@getpaseo/website",
|
||||
"version": "0.18.1",
|
||||
"version": "0.18.2",
|
||||
"dependencies": {
|
||||
"@cloudflare/vite-plugin": "^1.29.1",
|
||||
"@cloudflare/workers-types": "^4.20260317.1",
|
||||
@@ -43178,7 +43197,7 @@
|
||||
},
|
||||
"plugins": {
|
||||
"name": "@getpaseo/builtin-plugins",
|
||||
"version": "0.18.1",
|
||||
"version": "0.18.2",
|
||||
"dependencies": {
|
||||
"@getpaseo/plugin": "*",
|
||||
"zod": "^4.4.3"
|
||||
|
||||
+5
-2
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "paseo",
|
||||
"version": "0.18.1",
|
||||
"version": "0.18.2",
|
||||
"private": true,
|
||||
"description": "Paseo: voice-controlled development environment for local AI coding agents",
|
||||
"keywords": [
|
||||
@@ -99,7 +99,7 @@
|
||||
"web": "npm run web --workspace=@getpaseo/app",
|
||||
"dev:desktop": "cross-env PASEO_LISTEN=127.0.0.1:6768 npm run dev --workspace=@getpaseo/desktop",
|
||||
"dev:win:desktop": "npm run dev:win --workspace=@getpaseo/desktop",
|
||||
"build:desktop": "npm run build:app-deps:clean && cd packages/app && cross-env PASEO_WEB_PLATFORM=electron npx expo export --platform web && cd ../.. && npm run build --workspace=@getpaseo/desktop --",
|
||||
"build:desktop": "npm run build:app-deps:clean && cd packages/app && cross-env PASEO_WEB_PLATFORM=electron npx expo export --platform web && cd ../.. && node scripts/precompress-assets.mjs packages/app/dist && npm run build --workspace=@getpaseo/desktop --",
|
||||
"db:query": "npm run db:query --workspace=@getpaseo/server --",
|
||||
"cli": "./scripts/dev-home.sh npx tsx packages/cli/src/index.js",
|
||||
"version": "npm run version:sync-internal && npm run fdroid:changelogs && npm run release:prepare && git add -A",
|
||||
@@ -172,5 +172,8 @@
|
||||
"tiny-async-pool": {
|
||||
"semver@^5": "5.7.2"
|
||||
}
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22.16.0"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,6 +13,13 @@ import {
|
||||
import { expectNearBottom, scrollChatAwayFromBottom } from "../support/helpers/agent-bottom-anchor";
|
||||
import { holdRewindCompletion } from "../support/helpers/agent-timeline-gate";
|
||||
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
|
||||
import { userScrollsTimelineToHistoryStart } from "../support/helpers/timeline-pagination";
|
||||
import {
|
||||
closeWorkspaceAgentTab,
|
||||
fetchAgentArchivedAt,
|
||||
primeAdditionalPage,
|
||||
resetSeededPageState,
|
||||
} from "../support/helpers/archive-tab";
|
||||
|
||||
async function completeSubmittedTurn(
|
||||
page: Page,
|
||||
@@ -48,26 +55,98 @@ async function expectTurnCompletesNormally(
|
||||
await expectAgentIdle(page);
|
||||
}
|
||||
|
||||
async function openAgentOnAnotherClient(
|
||||
page: Page,
|
||||
agent: Awaited<ReturnType<typeof seedMockAgentWorkspace>>,
|
||||
): Promise<void> {
|
||||
await primeAdditionalPage(page);
|
||||
await resetSeededPageState(page);
|
||||
await openAgentRoute(page, agent);
|
||||
await expectComposerVisible(page);
|
||||
}
|
||||
|
||||
/** The prompts the chat shows, in order, each exactly once. */
|
||||
async function expectPrompts(page: Page, prompts: string[]): Promise<void> {
|
||||
const messages = page.getByTestId("user-message");
|
||||
await expect(messages).toHaveCount(prompts.length);
|
||||
await expect(messages).toContainText(prompts);
|
||||
}
|
||||
|
||||
async function reloadAgentFromTabMenu(page: Page, agentId: string): Promise<void> {
|
||||
const tabId = `workspace-tab-agent_${agentId}`;
|
||||
await page.getByTestId(tabId).filter({ visible: true }).first().click({ button: "right" });
|
||||
await page.getByTestId(`workspace-tab-context-agent_${agentId}-reload-agent`).click();
|
||||
}
|
||||
|
||||
async function archiveAgentByClosingTab(
|
||||
page: Page,
|
||||
agent: Awaited<ReturnType<typeof seedMockAgentWorkspace>>,
|
||||
): Promise<void> {
|
||||
await closeWorkspaceAgentTab(page, agent.agentId);
|
||||
await expect.poll(() => fetchAgentArchivedAt(agent.client, agent.agentId)).not.toBeNull();
|
||||
}
|
||||
|
||||
async function unarchiveAgent(page: Page): Promise<void> {
|
||||
await page.getByRole("button", { name: "Unarchive", exact: true }).click();
|
||||
await expect(page.getByText("This agent is archived", { exact: true })).toHaveCount(0, {
|
||||
timeout: 30_000,
|
||||
});
|
||||
}
|
||||
|
||||
async function expectToast(page: Page, message: string): Promise<void> {
|
||||
await expect(page.getByTestId("app-toast-message")).toHaveText(message, { timeout: 30_000 });
|
||||
}
|
||||
|
||||
/** The prompts of the whole conversation, after scrolling up through its older pages. */
|
||||
async function expectConversationPrompts(page: Page, prompts: string[]): Promise<void> {
|
||||
const messages = page.getByTestId("user-message");
|
||||
await expect
|
||||
.poll(async () => {
|
||||
await userScrollsTimelineToHistoryStart(page);
|
||||
return await messages.count();
|
||||
})
|
||||
.toBe(prompts.length);
|
||||
await expect(messages).toContainText(prompts);
|
||||
}
|
||||
|
||||
// A row React remounts loses this attribute; one that stays mounted keeps it.
|
||||
async function markMounted(row: Locator): Promise<void> {
|
||||
await row.evaluate((element) => element.setAttribute("data-e2e-mounted", "before-rewind"));
|
||||
}
|
||||
|
||||
async function expectStillMounted(row: Locator): Promise<void> {
|
||||
await expect(row).toHaveAttribute("data-e2e-mounted", "before-rewind");
|
||||
}
|
||||
|
||||
test.describe("Agent message rewind", () => {
|
||||
test("rewinds a submitted prompt without replaying history and preserves a human draft", async ({
|
||||
test("rewinds a prompt in place on every open client and keeps a human draft", async ({
|
||||
page,
|
||||
}) => {
|
||||
test.setTimeout(90_000);
|
||||
test.setTimeout(150_000);
|
||||
const retainedPrompt = "Keep this completed turn after rewind.";
|
||||
const rewoundPrompt = "Remove this completed turn after rewind.";
|
||||
const nextPrompt = "Continue after the rewind.";
|
||||
const preservedDraft = "Keep this human draft after rewind.";
|
||||
const agent = await seedMockAgentWorkspace({
|
||||
repoPrefix: "message-rewind-roundtrip-",
|
||||
title: "Message rewind roundtrip",
|
||||
model: "ten-second-stream",
|
||||
});
|
||||
const otherClient = await page.context().newPage();
|
||||
|
||||
try {
|
||||
const rewindCompletion = await holdRewindCompletion(page, agent.agentId);
|
||||
await openAgentRoute(page, agent);
|
||||
await expectComposerVisible(page);
|
||||
await completeSubmittedTurn(page, agent, retainedPrompt);
|
||||
const retainedMessage = await completeSubmittedTurn(page, agent, retainedPrompt);
|
||||
const userMessage = await completeSubmittedTurn(page, agent, rewoundPrompt);
|
||||
|
||||
await test.step("a second client opens the same chat", async () => {
|
||||
await openAgentOnAnotherClient(otherClient, agent);
|
||||
await expectPrompts(otherClient, [retainedPrompt, rewoundPrompt]);
|
||||
});
|
||||
|
||||
await markMounted(retainedMessage);
|
||||
await scrollChatAwayFromBottom(page, {
|
||||
deltaY: -900,
|
||||
minDistanceFromBottom: 300,
|
||||
@@ -76,19 +155,91 @@ test.describe("Agent message rewind", () => {
|
||||
await blurComposerInput(page);
|
||||
rewindCompletion.clearTimelineStreamCount();
|
||||
|
||||
const rewind = rewindConversation(page, userMessage, rewoundPrompt);
|
||||
await rewindCompletion.waitForDelayedResponse();
|
||||
await expect(page.getByTestId("rewind-menu-conversation")).toBeDisabled();
|
||||
expect(rewindCompletion.timelineStreamCount()).toBe(0);
|
||||
rewindCompletion.release();
|
||||
await rewind;
|
||||
await test.step("the rewind stays pending until the daemon answers", async () => {
|
||||
const rewind = rewindConversation(page, userMessage, rewoundPrompt);
|
||||
await rewindCompletion.waitForDelayedResponse();
|
||||
await expect(page.getByTestId("rewind-menu-conversation")).toBeDisabled();
|
||||
expect(rewindCompletion.timelineStreamCount()).toBe(0);
|
||||
rewindCompletion.release();
|
||||
await rewind;
|
||||
});
|
||||
|
||||
await expect(page.getByTestId("user-message").filter({ hasText: rewoundPrompt })).toHaveCount(
|
||||
0,
|
||||
);
|
||||
await expectComposerDraft(page, preservedDraft);
|
||||
await expectComposerNotFocused(page);
|
||||
await expectNearBottom(page);
|
||||
await test.step("the rewound turn leaves without reloading the chat", async () => {
|
||||
await expectPrompts(page, [retainedPrompt]);
|
||||
await expectStillMounted(retainedMessage);
|
||||
expect(rewindCompletion.timelineFetchCount()).toBe(0);
|
||||
await expectComposerDraft(page, preservedDraft);
|
||||
await expectComposerNotFocused(page);
|
||||
await expectNearBottom(page);
|
||||
await expectPrompts(otherClient, [retainedPrompt]);
|
||||
});
|
||||
|
||||
await test.step("the next prompt appears once on both clients", async () => {
|
||||
await completeSubmittedTurn(otherClient, agent, nextPrompt);
|
||||
await expectPrompts(otherClient, [retainedPrompt, nextPrompt]);
|
||||
await expectPrompts(page, [retainedPrompt, nextPrompt]);
|
||||
});
|
||||
|
||||
await test.step("a reconnecting client loads the rewound conversation", async () => {
|
||||
await otherClient.reload();
|
||||
await expectPrompts(otherClient, [retainedPrompt, nextPrompt]);
|
||||
});
|
||||
} finally {
|
||||
await otherClient.close();
|
||||
await agent.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("keeps the rewound conversation through Reload agent, archive and unarchive", async ({
|
||||
page,
|
||||
}) => {
|
||||
test.setTimeout(150_000);
|
||||
const keptPrompt = "Keep this turn through reload and archive.";
|
||||
const rewoundPrompt = "Rewind this turn before reloading.";
|
||||
const nextPrompt = "Continue after the rewind, then reload.";
|
||||
const agent = await seedMockAgentWorkspace({
|
||||
repoPrefix: "message-rewind-reload-archive-",
|
||||
title: "Message rewind reload archive",
|
||||
model: "ten-second-stream",
|
||||
});
|
||||
|
||||
try {
|
||||
await openAgentRoute(page, agent);
|
||||
await expectComposerVisible(page);
|
||||
await completeSubmittedTurn(page, agent, keptPrompt);
|
||||
const rewound = await completeSubmittedTurn(page, agent, rewoundPrompt);
|
||||
await rewindConversation(page, rewound, rewoundPrompt);
|
||||
await expectPrompts(page, [keptPrompt]);
|
||||
await completeSubmittedTurn(page, agent, nextPrompt);
|
||||
await expectPrompts(page, [keptPrompt, nextPrompt]);
|
||||
|
||||
await test.step("Reload agent keeps the rewound conversation", async () => {
|
||||
await reloadAgentFromTabMenu(page, agent.agentId);
|
||||
await expectToast(page, "Reloaded agent");
|
||||
await expectPrompts(page, [keptPrompt, nextPrompt]);
|
||||
await expectComposerVisible(page);
|
||||
});
|
||||
|
||||
await test.step("the archived chat shows the rewound conversation", async () => {
|
||||
await archiveAgentByClosingTab(page, agent);
|
||||
await openAgentRoute(page, agent);
|
||||
await expect(page.getByText("This agent is archived", { exact: true })).toBeVisible({
|
||||
timeout: 30_000,
|
||||
});
|
||||
await expectConversationPrompts(page, [keptPrompt, nextPrompt]);
|
||||
});
|
||||
|
||||
await test.step("unarchiving keeps the rewound conversation", async () => {
|
||||
await unarchiveAgent(page);
|
||||
await expectComposerVisible(page);
|
||||
await expectConversationPrompts(page, [keptPrompt, nextPrompt]);
|
||||
});
|
||||
|
||||
await test.step("a reconnecting client loads the same conversation", async () => {
|
||||
await page.reload();
|
||||
await expectComposerVisible(page);
|
||||
await expectConversationPrompts(page, [keptPrompt, nextPrompt]);
|
||||
});
|
||||
} finally {
|
||||
await agent.cleanup();
|
||||
}
|
||||
|
||||
@@ -44,6 +44,26 @@ const PROFILE = {
|
||||
|
||||
const PROFILE_SUMMARY = "Mock Load Test · One minute stream · Approval test";
|
||||
|
||||
// Isolate this suite to the sole mock provider so it tests single-provider picker
|
||||
// behavior deterministically regardless of which CLIs are installed on the host.
|
||||
test.use({
|
||||
e2eDaemonConfig: {
|
||||
version: 1,
|
||||
agents: {
|
||||
providers: {
|
||||
claude: { enabled: false },
|
||||
codex: { enabled: false },
|
||||
copilot: { enabled: false },
|
||||
opencode: { enabled: false },
|
||||
pi: { enabled: false },
|
||||
omp: { enabled: false },
|
||||
antigravity: { enabled: false },
|
||||
hoplite: { enabled: false },
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
test.describe("Agent profiles in the model picker", () => {
|
||||
test("an empty host still exposes agent profile settings from the picker", async ({ page }) => {
|
||||
const seed = await seedAgentProfiles([]);
|
||||
@@ -68,8 +88,8 @@ test.describe("Agent profiles in the model picker", () => {
|
||||
page,
|
||||
}) => {
|
||||
const seed = await seedAgentProfiles([PROFILE]);
|
||||
// A live agent is one provider's process, so the profile has to name that
|
||||
// same provider or the picker will not offer it at all.
|
||||
// With only the mock provider enabled on this host, the picker opens
|
||||
// directly into its models and shows its pinned profile.
|
||||
const workspace = await seedMockAgentWorkspace({
|
||||
repoPrefix: "agent-profiles-picker-",
|
||||
title: "Agent profiles picker",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { readFile, writeFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { expect, test } from "../support/fixtures";
|
||||
import { expect, test, type Page } from "../support/fixtures";
|
||||
import { expectComposerVisible } from "../support/helpers/composer";
|
||||
import { installDaemonWebSocketGate } from "../support/helpers/daemon-websocket-gate";
|
||||
import { installLocalDesktopHost } from "../support/helpers/local-desktop-host";
|
||||
@@ -282,3 +282,63 @@ test("compact opens files and subagents in a sheet, leaving the tabs for agents"
|
||||
await workspace.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
async function openFileAndDismissDuringAnimation(page: Page) {
|
||||
const fileLink = page.getByText(FILE_LINK, { exact: true });
|
||||
await expect(fileLink).toBeVisible({ timeout: 15_000 });
|
||||
|
||||
// Check and press in the same browser frame so automation cannot outlast the opening animation.
|
||||
await fileLink.evaluate((link) => {
|
||||
if (!(link instanceof HTMLElement)) throw new Error("Expected an HTML file link");
|
||||
return new Promise<void>((resolve, reject) => {
|
||||
const timeout = window.setTimeout(() => {
|
||||
cancelAnimationFrame(frame);
|
||||
reject(new Error("The file sheet did not pass through the opening position"));
|
||||
}, 5_000);
|
||||
const dismissDuringOpening = () => {
|
||||
const header = document.querySelector('[data-testid="sheet-tab-header"]');
|
||||
const top = header?.getBoundingClientRect().top ?? window.innerHeight;
|
||||
const pressTarget = document.elementFromPoint(10, 10);
|
||||
if (
|
||||
top > window.innerHeight / 2 &&
|
||||
top < window.innerHeight &&
|
||||
pressTarget instanceof HTMLElement &&
|
||||
pressTarget.getAttribute("aria-label") === "Bottom sheet backdrop"
|
||||
) {
|
||||
window.clearTimeout(timeout);
|
||||
pressTarget.click();
|
||||
resolve();
|
||||
return;
|
||||
}
|
||||
frame = requestAnimationFrame(dismissDuringOpening);
|
||||
};
|
||||
let frame = requestAnimationFrame(dismissDuringOpening);
|
||||
link.click();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
test("a sheet dismissed while it is still opening closes its tab", async ({ page }) => {
|
||||
await page.setViewportSize({ width: 390, height: 844 });
|
||||
const workspace = await seedMockAgentWorkspace({
|
||||
repoPrefix: "compact-sheet-opening-dismiss-",
|
||||
title: "Sheet parent",
|
||||
initialPrompt: promptMentioning(FILE_LINK),
|
||||
});
|
||||
try {
|
||||
await writeFile(path.join(workspace.cwd, "linked.ts"), "one\ntwo\nthree\n", "utf8");
|
||||
await openAgentRoute(page, { workspaceId: workspace.workspaceId, agentId: workspace.agentId });
|
||||
|
||||
await openFileAndDismissDuringAnimation(page);
|
||||
|
||||
await expectNoSheetOpen(page);
|
||||
await expectOpenTabCount(page, 1);
|
||||
await page
|
||||
.getByRole("button", { name: /Switch tabs/ })
|
||||
.filter({ visible: true })
|
||||
.click();
|
||||
await expect(page.getByText("Workspace tabs", { exact: true })).toBeVisible();
|
||||
} finally {
|
||||
await workspace.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
@@ -0,0 +1,324 @@
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import type { Locator } from "@playwright/test";
|
||||
import { expect, test, type Page } from "../support/fixtures";
|
||||
import { openCommandCenter } from "../support/helpers/command-center";
|
||||
import { runWorkspaceActionFromCommandCenter } from "../support/helpers/command-center-workspace-actions";
|
||||
import { submitMessageWithButton } from "../support/helpers/composer";
|
||||
import { openFileExplorer, openFileFromExplorer } from "../support/helpers/file-explorer";
|
||||
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
|
||||
import { connectNewWorkspaceDaemonClient } from "../support/helpers/new-workspace";
|
||||
import { copyPluginExample } from "../support/helpers/plugin-fixture";
|
||||
import { runCommand } from "../support/helpers/plugin-sidebar-items";
|
||||
import {
|
||||
closeSheet,
|
||||
expectNoSheetOpen,
|
||||
expectOneSheetOpen,
|
||||
promptMentioning,
|
||||
sheet,
|
||||
} from "../support/helpers/sheet";
|
||||
import {
|
||||
closeMobileExplorer,
|
||||
expectMobileExplorerHidden,
|
||||
expectMobileExplorerVisible,
|
||||
openMobileAgentSidebar,
|
||||
selectWorkspaceInSidebar,
|
||||
} from "../support/helpers/sidebar";
|
||||
import { getServerId } from "../support/helpers/server-id";
|
||||
|
||||
const WIDE = { width: 1600, height: 900 };
|
||||
const COMPACT = { width: 390, height: 844 };
|
||||
const AGENT_TITLE = "Layout agent";
|
||||
const FILE_LINK = "README.md:1";
|
||||
const NO_FILE = "Focus a file to see its outline";
|
||||
|
||||
const REPO_FILES = [
|
||||
{ path: "README.md", content: "# Guide\n\n## Install\n" },
|
||||
{ path: "notes.md", content: "# Notes\n\n## Open questions\n" },
|
||||
{ path: "src/app.ts", content: "// TODO: handle errors\nexport const ready = true;\n" },
|
||||
];
|
||||
|
||||
const REVIEW_TAB = "workspace-tab-plugin_agent_16_workspace-layout_6_review_";
|
||||
const FINDINGS_TAB = "workspace-tab-plugin_workspace_16_workspace-layout_8_findings";
|
||||
const OUTLINE_TAB = "workspace-tab-plugin_workspace_16_workspace-layout_7_outline";
|
||||
|
||||
async function withLayoutExample(
|
||||
initialPrompt: string | undefined,
|
||||
run: (agent: { agentId: string; workspaceId: string }) => Promise<void>,
|
||||
): Promise<void> {
|
||||
const example = await copyPluginExample("workspace-layout");
|
||||
const workspace = await seedMockAgentWorkspace({
|
||||
repoPrefix: "plugin-workspace-layout-",
|
||||
title: AGENT_TITLE,
|
||||
repo: { files: REPO_FILES },
|
||||
initialPrompt,
|
||||
});
|
||||
try {
|
||||
await withPluginInstalled(example.directory, () => run(workspace));
|
||||
} finally {
|
||||
await workspace.cleanup();
|
||||
await example.cleanup();
|
||||
}
|
||||
}
|
||||
|
||||
async function withPluginInstalled(directory: string, run: () => Promise<void>): Promise<void> {
|
||||
const client = await connectNewWorkspaceDaemonClient({ ownProjects: false });
|
||||
const previous = await client.getDaemonConfig();
|
||||
try {
|
||||
await client.patchDaemonConfig({ pluginsEnabled: true });
|
||||
await client.installDirectoryPlugin(directory);
|
||||
await run();
|
||||
} finally {
|
||||
await client.removePlugin("workspace-layout").catch(() => undefined);
|
||||
await client.patchDaemonConfig({ pluginsEnabled: previous.config.pluginsEnabled ?? false });
|
||||
await client.close();
|
||||
}
|
||||
}
|
||||
|
||||
/** `/open-elsewhere <id>` opens a file in that workspace, then one where the command ran. */
|
||||
const OPEN_ELSEWHERE_ENTRY = `import type { PluginClientContext } from "@getpaseo/plugin/client";
|
||||
|
||||
export default function contribute(client: PluginClientContext) {
|
||||
client.addSlashCommand({
|
||||
name: "open-elsewhere",
|
||||
description: "Open a file there, then one here",
|
||||
argumentHint: "<workspaceId>",
|
||||
context: "agent",
|
||||
onSubmit({ args, workspaceLayout }) {
|
||||
const there = client.workspaceLayout(args.trim());
|
||||
there.open({ panelId: "paseo/file", params: { path: "README.md" } });
|
||||
workspaceLayout.open({ panelId: "paseo/file", params: { path: "notes.md" } });
|
||||
},
|
||||
});
|
||||
return () => {};
|
||||
}
|
||||
`;
|
||||
|
||||
async function withTwoWorkspaces(
|
||||
run: (workspaces: {
|
||||
first: { agentId: string; workspaceId: string };
|
||||
second: { agentId: string; workspaceId: string };
|
||||
}) => Promise<void>,
|
||||
): Promise<void> {
|
||||
const example = await copyPluginExample("workspace-layout");
|
||||
await writeFile(path.join(example.directory, "index.client.tsx"), OPEN_ELSEWHERE_ENTRY);
|
||||
const seed = (title: string) =>
|
||||
seedMockAgentWorkspace({
|
||||
repoPrefix: "plugin-workspace-layout-",
|
||||
title,
|
||||
repo: { files: REPO_FILES },
|
||||
});
|
||||
const first = await seed("First agent");
|
||||
const second = await seed("Second agent");
|
||||
try {
|
||||
await withPluginInstalled(example.directory, () => run({ first, second }));
|
||||
} finally {
|
||||
await second.cleanup();
|
||||
await first.cleanup();
|
||||
await example.cleanup();
|
||||
}
|
||||
}
|
||||
|
||||
/** Picks a workspace in a phone's agent list. */
|
||||
async function switchToWorkspace(page: Page, workspaceId: string): Promise<void> {
|
||||
await openMobileAgentSidebar(page);
|
||||
await selectWorkspaceInSidebar(page, workspaceId);
|
||||
await expect(
|
||||
page.getByTestId(`workspace-deck-entry-${getServerId()}:${workspaceId}`),
|
||||
).toBeVisible();
|
||||
await expect(composerIn(page.locator("body"))).toBeEditable({ timeout: 30_000 });
|
||||
}
|
||||
|
||||
function mainPanes(page: Page): Locator {
|
||||
return page.locator('[data-testid^="workspace-pane-"]').filter({ visible: true });
|
||||
}
|
||||
|
||||
function explorer(page: Page): Locator {
|
||||
return page.getByTestId("workspace-explorer-sidebar");
|
||||
}
|
||||
|
||||
function agentTabs(scope: Locator): Locator {
|
||||
return scope.locator('[data-testid^="workspace-tab-agent_"]');
|
||||
}
|
||||
|
||||
function composerIn(scope: Locator): Locator {
|
||||
return scope.getByRole("textbox", { name: "Message agent..." }).filter({ visible: true });
|
||||
}
|
||||
|
||||
async function sendToMainChat(page: Page, text: string): Promise<void> {
|
||||
const composer = composerIn(mainPanes(page).first());
|
||||
await expect(composer).toBeEditable({ timeout: 30_000 });
|
||||
await composer.fill(text);
|
||||
await composer.press("Enter");
|
||||
}
|
||||
|
||||
async function expectAsideChat(page: Page, input: { message: string; tabs: number }) {
|
||||
const chats = agentTabs(explorer(page));
|
||||
await expect(chats).toHaveCount(input.tabs, { timeout: 30_000 });
|
||||
await expect(chats.last()).toHaveAttribute("aria-selected", "true");
|
||||
await expect(
|
||||
explorer(page).getByTestId("user-message").getByText(input.message, { exact: true }),
|
||||
).toBeVisible();
|
||||
await expect(composerIn(explorer(page))).toBeEditable();
|
||||
}
|
||||
|
||||
/** Every visible tab chip, pane by pane, to compare the arrangement before and after. */
|
||||
async function tabsByPane(page: Page): Promise<string[][]> {
|
||||
const scopes = [...(await mainPanes(page).all()), explorer(page)];
|
||||
return Promise.all(
|
||||
scopes.map((scope) =>
|
||||
scope
|
||||
.getByTestId("workspace-tabs-row")
|
||||
.locator('[data-testid^="workspace-tab-"]:not([data-testid^="workspace-tab-tooltip"])')
|
||||
.evaluateAll((chips) => chips.map((chip) => chip.getAttribute("data-testid") ?? "")),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
async function expectReviewLayout(page: Page, agentId: string): Promise<void> {
|
||||
await expect(mainPanes(page)).toHaveCount(2);
|
||||
const left = mainPanes(page).first();
|
||||
const right = mainPanes(page).last();
|
||||
await expect(left.getByTestId(`workspace-tab-agent_${agentId}`)).toBeVisible();
|
||||
|
||||
const review = right.getByTestId(`${REVIEW_TAB}${agentId.length}_${agentId}`);
|
||||
await expect(review).toHaveAttribute("aria-selected", "true");
|
||||
await expect(right.getByText(`Reviewing ${AGENT_TITLE}`, { exact: true })).toBeVisible();
|
||||
await expect(right.getByTestId("workspace-tab-working_diff")).toHaveAttribute(
|
||||
"aria-selected",
|
||||
"false",
|
||||
);
|
||||
await expect(explorer(page).getByTestId(FINDINGS_TAB)).toBeVisible();
|
||||
|
||||
const [leftBox, rightBox] = [await left.boundingBox(), await right.boundingBox()];
|
||||
if (!leftBox || !rightBox) throw new Error("Review layout panes have no bounds");
|
||||
expect(rightBox.x).toBeGreaterThan(leftBox.x);
|
||||
expect(rightBox.width / (leftBox.width + rightBox.width)).toBeCloseTo(0.4, 1);
|
||||
}
|
||||
|
||||
async function openFileInFocusedPane(page: Page, name: string): Promise<void> {
|
||||
await openFileExplorer(page);
|
||||
await openFileFromExplorer(page, name);
|
||||
await expect(mainPanes(page).getByTestId(`workspace-tab-file_${name}`)).toBeVisible();
|
||||
}
|
||||
|
||||
async function expectOutline(page: Page, lines: string[]): Promise<void> {
|
||||
const outline = page.getByTestId("workspace-layout-outline");
|
||||
for (const line of lines) {
|
||||
await expect(outline.getByText(line, { exact: true })).toHaveCount(1);
|
||||
}
|
||||
}
|
||||
|
||||
test("the workspace layout example arranges a wide workspace", async ({ page }) => {
|
||||
test.setTimeout(180_000);
|
||||
await withLayoutExample(undefined, async ({ agentId, workspaceId }) => {
|
||||
await page.setViewportSize(WIDE);
|
||||
await openAgentRoute(page, { workspaceId, agentId });
|
||||
|
||||
await test.step("/aside opens the child agent's chat in the Explorer", async () => {
|
||||
await sendToMainChat(page, "/aside hey");
|
||||
await expectAsideChat(page, { message: "hey", tabs: 1 });
|
||||
await expect(agentTabs(mainPanes(page))).toHaveCount(1);
|
||||
});
|
||||
|
||||
await test.step("a second /aside adds a second tab", async () => {
|
||||
await sendToMainChat(page, "/aside again");
|
||||
await expectAsideChat(page, { message: "again", tabs: 2 });
|
||||
await expect(agentTabs(mainPanes(page))).toHaveCount(1);
|
||||
});
|
||||
|
||||
await test.step("Review layout splits the workspace, and running it again changes nothing", async () => {
|
||||
await runCommand(page, "Review layout");
|
||||
await expectReviewLayout(page, agentId);
|
||||
const arranged = await tabsByPane(page);
|
||||
|
||||
await mainPanes(page).first().getByTestId(`workspace-tab-agent_${agentId}`).click();
|
||||
await runCommand(page, "Review layout");
|
||||
await expectReviewLayout(page, agentId);
|
||||
expect(await tabsByPane(page)).toEqual(arranged);
|
||||
});
|
||||
|
||||
await test.step("the outline follows the focused file across split panes", async () => {
|
||||
await mainPanes(page).first().getByTestId(`workspace-tab-agent_${agentId}`).click();
|
||||
await runCommand(page, "Show outline");
|
||||
await expectOutline(page, [NO_FILE]);
|
||||
|
||||
await openFileInFocusedPane(page, "README.md");
|
||||
await explorer(page).getByTestId(OUTLINE_TAB).click();
|
||||
await expectOutline(page, ["README.md", "Guide", "Install"]);
|
||||
|
||||
await runWorkspaceActionFromCommandCenter(page, "Split pane right");
|
||||
await expect(mainPanes(page)).toHaveCount(3);
|
||||
await openFileInFocusedPane(page, "notes.md");
|
||||
await explorer(page).getByTestId(OUTLINE_TAB).click();
|
||||
await expectOutline(page, ["notes.md", "Notes", "Open questions"]);
|
||||
|
||||
await mainPanes(page).getByTestId("workspace-tab-file_README.md").click();
|
||||
await expectOutline(page, ["README.md", "Guide", "Install"]);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
test("the workspace layout example opens over a phone's chat", async ({ page }) => {
|
||||
test.setTimeout(180_000);
|
||||
await withLayoutExample(promptMentioning(FILE_LINK), async ({ agentId, workspaceId }) => {
|
||||
await page.setViewportSize(COMPACT);
|
||||
await openAgentRoute(page, { workspaceId, agentId });
|
||||
|
||||
await test.step("/aside opens the Explorer over the chat", async () => {
|
||||
await submitMessageWithButton(page, "/aside hey");
|
||||
await expectMobileExplorerVisible(page);
|
||||
await expectAsideChat(page, { message: "hey", tabs: 1 });
|
||||
await closeMobileExplorer(page);
|
||||
await expectMobileExplorerHidden(page);
|
||||
await expect(
|
||||
page.getByRole("button", { name: "Switch tabs (1 open)" }).filter({ visible: true }),
|
||||
).toBeVisible();
|
||||
});
|
||||
|
||||
await test.step("a file sheet updates the outline, and closing it restores it", async () => {
|
||||
await openMobileAgentSidebar(page);
|
||||
const commandCenter = await openCommandCenter(page);
|
||||
await commandCenter.getByTestId("command-center-input").fill("Show outline");
|
||||
await commandCenter.getByRole("button", { name: "Show outline", exact: true }).click();
|
||||
await expectMobileExplorerVisible(page);
|
||||
await expectOutline(page, [NO_FILE]);
|
||||
await closeMobileExplorer(page);
|
||||
await expectMobileExplorerHidden(page);
|
||||
|
||||
await page.getByText(FILE_LINK, { exact: true }).first().click();
|
||||
await expect(sheet(page, "README.md")).toBeVisible();
|
||||
// The sheet covers the Explorer, so the outline can only be read, not seen.
|
||||
await expectOutline(page, ["README.md", "Guide", "Install"]);
|
||||
await closeSheet(page, "README.md");
|
||||
await expectOutline(page, [NO_FILE]);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
test("a file a plugin opens in another workspace waits there on a phone", async ({ page }) => {
|
||||
test.setTimeout(180_000);
|
||||
await withTwoWorkspaces(async ({ first, second }) => {
|
||||
await page.setViewportSize(COMPACT);
|
||||
// Visiting the first workspace leaves its screen mounted behind the second.
|
||||
await openAgentRoute(page, first);
|
||||
await expect(composerIn(page.locator("body"))).toBeEditable({ timeout: 30_000 });
|
||||
await switchToWorkspace(page, second.workspaceId);
|
||||
|
||||
await test.step("only the sheet of the workspace on screen is shown", async () => {
|
||||
await submitMessageWithButton(page, `/open-elsewhere ${first.workspaceId}`);
|
||||
await expect(sheet(page, "notes.md")).toBeVisible();
|
||||
await expectOneSheetOpen(page);
|
||||
await closeSheet(page, "notes.md");
|
||||
await expectNoSheetOpen(page);
|
||||
});
|
||||
|
||||
await test.step("the other sheet is there when the user goes to its workspace", async () => {
|
||||
await switchToWorkspace(page, first.workspaceId);
|
||||
await expect(sheet(page, "README.md")).toBeVisible();
|
||||
await expectOneSheetOpen(page);
|
||||
await closeSheet(page, "README.md");
|
||||
await expectNoSheetOpen(page);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,555 @@
|
||||
import { mkdir } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import type { Locator } from "@playwright/test";
|
||||
import { expect, test, type Page } from "../support/fixtures";
|
||||
import { expectAgentIdle, expectAgentReadyToInterrupt } from "../support/helpers/agent-stream";
|
||||
import {
|
||||
drillIntoProvider,
|
||||
expectComposerMode,
|
||||
expectComposerModel,
|
||||
openModelPicker,
|
||||
selectModelRow,
|
||||
} from "../support/helpers/agent-profiles";
|
||||
import { expectWorkspaceAgentConfiguration } from "../support/helpers/command-center-agent-controls";
|
||||
import {
|
||||
expectComposerVisible,
|
||||
expectQueuedMessageButton,
|
||||
submitMessage,
|
||||
submitMessageWithButton,
|
||||
} from "../support/helpers/composer";
|
||||
import { connectDaemonClient } from "../support/helpers/daemon-client-loader";
|
||||
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
|
||||
import { copyPluginExample } from "../support/helpers/plugin-fixture";
|
||||
import { userScrollsTimelineToHistoryStart } from "../support/helpers/timeline-pagination";
|
||||
|
||||
const DIRECT_PROVIDER = {
|
||||
id: "direct-example",
|
||||
label: "Direct provider example",
|
||||
pluginId: "provider-direct-example",
|
||||
modelId: "example-1",
|
||||
modelLabel: "Example 1",
|
||||
modeLabel: "Build",
|
||||
} as const;
|
||||
|
||||
// Disable external CLIs so the E2E host deterministically exposes only Mock +
|
||||
// the installed Direct provider plugin on both developer machines and CI.
|
||||
test.use({
|
||||
e2eDaemonConfig: {
|
||||
version: 1,
|
||||
agents: {
|
||||
providers: {
|
||||
claude: { enabled: false },
|
||||
codex: { enabled: false },
|
||||
copilot: { enabled: false },
|
||||
opencode: { enabled: false },
|
||||
pi: { enabled: false },
|
||||
omp: { enabled: false },
|
||||
antigravity: { enabled: false },
|
||||
hoplite: { enabled: false },
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
interface PluginInstallDaemonClient {
|
||||
connect(): Promise<void>;
|
||||
close(): Promise<void>;
|
||||
getDaemonConfig(): Promise<{ config: { pluginsEnabled?: boolean } }>;
|
||||
patchDaemonConfig(config: { pluginsEnabled?: boolean }): Promise<unknown>;
|
||||
installDirectoryPlugin(directory: string): Promise<unknown>;
|
||||
removePlugin(pluginId: string): Promise<void>;
|
||||
getProvidersSnapshot(): Promise<{
|
||||
entries: Array<{ provider: string; available?: boolean }>;
|
||||
}>;
|
||||
}
|
||||
|
||||
async function hasDirectProvider(client: PluginInstallDaemonClient): Promise<boolean> {
|
||||
const snapshot = await client.getProvidersSnapshot();
|
||||
return snapshot.entries.some((entry) => entry.provider === DIRECT_PROVIDER.id);
|
||||
}
|
||||
|
||||
async function expectSwitchMarkerCountAfterScroll(page: Page, expected: number): Promise<void> {
|
||||
await expect
|
||||
.poll(
|
||||
async () => {
|
||||
await userScrollsTimelineToHistoryStart(page);
|
||||
return await page.getByTestId("provider-switch-marker").count();
|
||||
},
|
||||
{ timeout: 30_000 },
|
||||
)
|
||||
.toBe(expected);
|
||||
}
|
||||
|
||||
async function captureQaScreenshot(page: Page, fileName: string): Promise<void> {
|
||||
const dir = process.env.PASEO_QA_SCREENSHOT_DIR?.trim();
|
||||
if (!dir) return;
|
||||
await mkdir(dir, { recursive: true });
|
||||
await page.screenshot({ path: path.join(dir, fileName), fullPage: false });
|
||||
}
|
||||
|
||||
async function expectNoHorizontalOverflow(page: Page): Promise<void> {
|
||||
const overflow = await page.evaluate(() => {
|
||||
const doc = document.documentElement;
|
||||
return Math.ceil(doc.scrollWidth - doc.clientWidth);
|
||||
});
|
||||
expect(overflow).toBeLessThanOrEqual(1);
|
||||
}
|
||||
|
||||
async function startSwitchOrderGuard(page: Page): Promise<void> {
|
||||
await page.evaluate(() => {
|
||||
const violations: string[] = [];
|
||||
let stopped = false;
|
||||
const step = () => {
|
||||
const msgs = Array.from(document.querySelectorAll('[data-testid="user-message"]'));
|
||||
const markers = Array.from(
|
||||
document.querySelectorAll('[data-testid="provider-switch-marker"]'),
|
||||
);
|
||||
const banner = document.querySelector('[data-testid="staged-provider-switch-banner"]');
|
||||
if (msgs.length >= 2) {
|
||||
const secondMsg = msgs[msgs.length - 1];
|
||||
const lastMarker = markers[markers.length - 1];
|
||||
if (!lastMarker) {
|
||||
violations.push("user-message painted without switch marker");
|
||||
} else {
|
||||
const msgRect = secondMsg.getBoundingClientRect();
|
||||
const markerRect = lastMarker.getBoundingClientRect();
|
||||
if (markerRect.top > msgRect.top) {
|
||||
violations.push(
|
||||
`switch marker painted below user-message (${Math.round(markerRect.top)} > ${Math.round(msgRect.top)})`,
|
||||
);
|
||||
}
|
||||
}
|
||||
if (banner && banner.getBoundingClientRect().height > 0) {
|
||||
violations.push("staged-provider-switch-banner stayed visible after submit");
|
||||
}
|
||||
}
|
||||
if (!stopped) requestAnimationFrame(step);
|
||||
};
|
||||
requestAnimationFrame(step);
|
||||
(window as unknown as { __stopSwitchOrderGuard?: () => string[] }).__stopSwitchOrderGuard =
|
||||
() => {
|
||||
stopped = true;
|
||||
return violations;
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
async function stopSwitchOrderGuard(page: Page): Promise<string[]> {
|
||||
return await page.evaluate(
|
||||
() =>
|
||||
(
|
||||
window as unknown as { __stopSwitchOrderGuard?: () => string[] }
|
||||
).__stopSwitchOrderGuard?.() ?? [],
|
||||
);
|
||||
}
|
||||
|
||||
async function completeMockTurn(
|
||||
page: Page,
|
||||
agent: Awaited<ReturnType<typeof seedMockAgentWorkspace>>,
|
||||
prompt: string,
|
||||
): Promise<Locator> {
|
||||
await submitMessage(page, prompt);
|
||||
const userMessage = page.getByTestId("user-message").filter({ hasText: prompt });
|
||||
await expect(userMessage).toBeVisible({ timeout: 30_000 });
|
||||
const finish = await agent.client.waitForFinish(agent.agentId, 30_000);
|
||||
expect(finish.status).toBe("idle");
|
||||
await expectAgentIdle(page);
|
||||
await expect(userMessage).toHaveAttribute("aria-busy", "false");
|
||||
return userMessage;
|
||||
}
|
||||
|
||||
async function completeDirectTurn(
|
||||
page: Page,
|
||||
agent: Awaited<ReturnType<typeof seedMockAgentWorkspace>>,
|
||||
prompt: string,
|
||||
options?: { useSendButton?: boolean },
|
||||
): Promise<Locator> {
|
||||
if (options?.useSendButton) {
|
||||
await submitMessageWithButton(page, prompt);
|
||||
} else {
|
||||
await submitMessage(page, prompt);
|
||||
}
|
||||
const userMessage = page.getByTestId("user-message").filter({ hasText: prompt });
|
||||
await expect(userMessage).toBeVisible({ timeout: 30_000 });
|
||||
const finish = await agent.client.waitForFinish(agent.agentId, 30_000);
|
||||
expect(finish.status).toBe("idle");
|
||||
await expectAgentIdle(page);
|
||||
await expect(userMessage).toHaveAttribute("aria-busy", "false");
|
||||
return userMessage;
|
||||
}
|
||||
|
||||
async function stageProviderDesktop(
|
||||
page: Page,
|
||||
providerId: string,
|
||||
modelId: string,
|
||||
): Promise<void> {
|
||||
await openModelPicker(page);
|
||||
const picker = page.getByTestId("combobox-desktop-container");
|
||||
const backButton = picker.getByTestId("sheet-header-back");
|
||||
if (await backButton.isVisible()) {
|
||||
await backButton.click();
|
||||
}
|
||||
await drillIntoProvider(page, providerId);
|
||||
await selectModelRow(page, { provider: providerId, modelId });
|
||||
await expect(page.getByTestId("staged-provider-switch-banner")).toBeVisible({ timeout: 30_000 });
|
||||
}
|
||||
|
||||
async function stageDirectProviderDesktop(page: Page): Promise<void> {
|
||||
await stageProviderDesktop(page, DIRECT_PROVIDER.id, DIRECT_PROVIDER.modelId);
|
||||
}
|
||||
|
||||
async function stageDirectProviderCompact(page: Page): Promise<void> {
|
||||
await page.getByTestId("combined-model-selector").filter({ visible: true }).first().click();
|
||||
await expect(page.getByTestId("agent-controls-model")).toBeVisible({ timeout: 30_000 });
|
||||
await page.getByTestId("agent-controls-model").click();
|
||||
const modelPage = page.getByTestId("mobile-model-page");
|
||||
await expect(modelPage).toBeVisible({ timeout: 30_000 });
|
||||
const collapsedProvider = modelPage.getByTestId(`model-provider-${DIRECT_PROVIDER.id}`);
|
||||
if (await collapsedProvider.isVisible()) {
|
||||
await collapsedProvider.click();
|
||||
}
|
||||
await modelPage.getByTestId(`model-row-${DIRECT_PROVIDER.id}-${DIRECT_PROVIDER.modelId}`).click();
|
||||
await expect(page.getByTestId("agent-controls-settings-list")).toBeVisible({ timeout: 30_000 });
|
||||
// Dismiss the agent-controls sheet so the composer and banner are ready to submit.
|
||||
await page.getByRole("button", { name: "Close", exact: true }).last().click();
|
||||
await expect(page.getByTestId("agent-controls-model")).toHaveCount(0, { timeout: 30_000 });
|
||||
await expect(page.getByTestId("staged-provider-switch-banner")).toBeVisible({ timeout: 30_000 });
|
||||
}
|
||||
|
||||
async function rewindConversation(page: Page, userMessage: Locator, prompt: string): Promise<void> {
|
||||
await userMessage.getByText(prompt, { exact: true }).hover();
|
||||
await userMessage.getByRole("button", { name: "Rewind to this message", exact: true }).click();
|
||||
await page.getByRole("menuitem", { name: "Rewind conversation", exact: true }).click();
|
||||
}
|
||||
|
||||
test.describe.serial("Provider switching in chat", () => {
|
||||
let pluginClient: PluginInstallDaemonClient;
|
||||
let pluginFixture: Awaited<ReturnType<typeof copyPluginExample>>;
|
||||
let previousPluginsEnabled: boolean | undefined;
|
||||
|
||||
test.beforeAll(async () => {
|
||||
pluginClient = await connectDaemonClient<PluginInstallDaemonClient>({
|
||||
clientIdPrefix: "provider-switching-e2e",
|
||||
});
|
||||
pluginFixture = await copyPluginExample("provider-direct");
|
||||
previousPluginsEnabled = (await pluginClient.getDaemonConfig()).config.pluginsEnabled;
|
||||
await pluginClient.patchDaemonConfig({ pluginsEnabled: true });
|
||||
await pluginClient.installDirectoryPlugin(pluginFixture.directory);
|
||||
await expect.poll(() => hasDirectProvider(pluginClient), { timeout: 30_000 }).toBe(true);
|
||||
});
|
||||
|
||||
test.afterAll(async () => {
|
||||
await pluginClient?.removePlugin(DIRECT_PROVIDER.pluginId).catch(() => undefined);
|
||||
await pluginClient
|
||||
?.patchDaemonConfig({ pluginsEnabled: previousPluginsEnabled })
|
||||
.catch(() => undefined);
|
||||
await pluginClient?.close().catch(() => undefined);
|
||||
await pluginFixture?.cleanup().catch(() => undefined);
|
||||
});
|
||||
|
||||
test("stages, cancels, switches providers, inspects marker, scopes rewind, and survives reload", async ({
|
||||
page,
|
||||
}) => {
|
||||
test.setTimeout(150_000);
|
||||
await page.setViewportSize({ width: 1280, height: 800 });
|
||||
|
||||
const preSwitchPrompt = "First prompt on Mock before switching.";
|
||||
const postSwitchPrompt = "Follow up on Direct provider after switching.";
|
||||
const postRewindPrompt = "Continue on Direct provider after rewinding.";
|
||||
|
||||
const workspace = await seedMockAgentWorkspace({
|
||||
repoPrefix: "provider-switch-desktop-",
|
||||
title: "Provider switch desktop",
|
||||
model: "e2e-fast-stream",
|
||||
modeId: "load-test",
|
||||
});
|
||||
|
||||
try {
|
||||
await openAgentRoute(page, workspace);
|
||||
await expectComposerVisible(page);
|
||||
await expectComposerMode(page, "Load test");
|
||||
|
||||
const initialUrl = page.url();
|
||||
await completeMockTurn(page, workspace, preSwitchPrompt);
|
||||
|
||||
await test.step("staging updates only draft state and Cancel restores the live provider", async () => {
|
||||
await stageDirectProviderDesktop(page);
|
||||
await expectComposerModel(page, DIRECT_PROVIDER.modelLabel);
|
||||
await expectComposerMode(page, DIRECT_PROVIDER.modeLabel);
|
||||
await expect(page.getByTestId("staged-provider-switch-banner")).toContainText(
|
||||
DIRECT_PROVIDER.label,
|
||||
);
|
||||
await expectWorkspaceAgentConfiguration(workspace, {
|
||||
id: workspace.agentId,
|
||||
provider: "mock",
|
||||
model: "e2e-fast-stream",
|
||||
modeId: "load-test",
|
||||
});
|
||||
// Editing a staged provider option must keep all staged option controls visible.
|
||||
const conciseToggle = page.getByRole("button", { name: /Concise responses/i }).first();
|
||||
const voiceSelect = page.getByRole("button", { name: /Voice/i }).first();
|
||||
await expect(conciseToggle).toBeVisible();
|
||||
await expect(voiceSelect).toBeVisible();
|
||||
await conciseToggle.click();
|
||||
await expect(conciseToggle).toBeVisible();
|
||||
await expect(voiceSelect).toBeVisible();
|
||||
await expectNoHorizontalOverflow(page);
|
||||
await captureQaScreenshot(page, "desktop-staged-switch.png");
|
||||
|
||||
await page.getByTestId("cancel-staged-provider-switch").click();
|
||||
await expect(page.getByTestId("staged-provider-switch-banner")).toHaveCount(0);
|
||||
await expectComposerMode(page, "Load test");
|
||||
|
||||
// Returning to the live provider by choosing a different model clears the staged switch
|
||||
// and applies the newly chosen model directly to the live provider.
|
||||
await stageDirectProviderDesktop(page);
|
||||
await openModelPicker(page);
|
||||
const picker = page.getByTestId("combobox-desktop-container");
|
||||
const backButton = picker.getByTestId("sheet-header-back");
|
||||
if (await backButton.isVisible()) {
|
||||
await backButton.click();
|
||||
}
|
||||
await drillIntoProvider(page, "mock");
|
||||
await selectModelRow(page, { provider: "mock", modelId: "one-minute-stream" });
|
||||
await expect(page.getByTestId("staged-provider-switch-banner")).toHaveCount(0);
|
||||
await expectComposerModel(page, "One minute stream");
|
||||
await expectWorkspaceAgentConfiguration(workspace, {
|
||||
id: workspace.agentId,
|
||||
provider: "mock",
|
||||
model: "one-minute-stream",
|
||||
modeId: "load-test",
|
||||
});
|
||||
});
|
||||
|
||||
await test.step("submitting commits the switch in place with clean user display text and inspectable marker", async () => {
|
||||
await stageDirectProviderDesktop(page);
|
||||
await startSwitchOrderGuard(page);
|
||||
const switchedMessage = await completeDirectTurn(page, workspace, postSwitchPrompt);
|
||||
expect(await stopSwitchOrderGuard(page)).toEqual([]);
|
||||
|
||||
expect(page.url()).toBe(initialUrl);
|
||||
await expect(page.getByTestId("staged-provider-switch-banner")).toHaveCount(0);
|
||||
await expectWorkspaceAgentConfiguration(workspace, {
|
||||
id: workspace.agentId,
|
||||
provider: DIRECT_PROVIDER.id,
|
||||
model: DIRECT_PROVIDER.modelId,
|
||||
modeId: "build",
|
||||
});
|
||||
|
||||
// Clean display text: handoff summary must never leak into the visible user bubble.
|
||||
await expect(switchedMessage).toContainText(postSwitchPrompt);
|
||||
await expect(switchedMessage).not.toContainText("<chat-history-summary>");
|
||||
|
||||
// Direct provider echoes its prompt, proving bounded pre-switch context was attached.
|
||||
const directReply = page
|
||||
.getByTestId("assistant-message")
|
||||
.filter({ hasText: "Echo:" })
|
||||
.last();
|
||||
await expect(directReply).toContainText(preSwitchPrompt);
|
||||
await expect(directReply).toContainText(postSwitchPrompt);
|
||||
|
||||
// Switch marker is visible and expands to show context handoff details.
|
||||
const marker = page.getByTestId("provider-switch-marker");
|
||||
await expect(marker).toBeVisible({ timeout: 30_000 });
|
||||
await marker.scrollIntoViewIfNeeded();
|
||||
await marker.getByTestId("provider-switch-marker-toggle").click();
|
||||
const details = marker.getByTestId("provider-switch-marker-details");
|
||||
await expect(details).toBeVisible();
|
||||
await expect(details).toContainText("Mock");
|
||||
await expect(details).toContainText(DIRECT_PROVIDER.label);
|
||||
await marker.scrollIntoViewIfNeeded();
|
||||
await expectNoHorizontalOverflow(page);
|
||||
await captureQaScreenshot(page, "desktop-switched-expanded.png");
|
||||
await marker.getByTestId("provider-switch-marker-toggle").click();
|
||||
await expect(details).toHaveCount(0);
|
||||
});
|
||||
|
||||
await test.step("switching back to Mock enforces segment-scoped rewind and preserves pre-switch turns", async () => {
|
||||
const backToMockPrompt = "Switch back to Mock for segment-scoped rewind.";
|
||||
await stageProviderDesktop(page, "mock", "ten-second-stream");
|
||||
await expect(page.getByTestId("staged-provider-switch-banner")).toContainText("Mock");
|
||||
|
||||
const backToMockMessage = await completeMockTurn(page, workspace, backToMockPrompt);
|
||||
await expect(backToMockMessage).not.toContainText("<chat-history-summary>");
|
||||
await expect(page.getByTestId("provider-switch-marker")).toHaveCount(2, {
|
||||
timeout: 30_000,
|
||||
});
|
||||
await expectWorkspaceAgentConfiguration(workspace, {
|
||||
id: workspace.agentId,
|
||||
provider: "mock",
|
||||
model: "ten-second-stream",
|
||||
modeId: "load-test",
|
||||
});
|
||||
|
||||
// Pre-switch prompts from earlier segments must not expose rewind even though Mock supports it.
|
||||
const preSwitchMessage = page
|
||||
.getByTestId("user-message")
|
||||
.filter({ hasText: preSwitchPrompt });
|
||||
await preSwitchMessage.scrollIntoViewIfNeeded();
|
||||
await preSwitchMessage.getByText(preSwitchPrompt, { exact: true }).hover();
|
||||
await expect(
|
||||
preSwitchMessage.getByRole("button", { name: "Rewind to this message", exact: true }),
|
||||
).toHaveCount(0);
|
||||
|
||||
const directMessage = page
|
||||
.getByTestId("user-message")
|
||||
.filter({ hasText: postSwitchPrompt });
|
||||
await directMessage.scrollIntoViewIfNeeded();
|
||||
await directMessage.getByText(postSwitchPrompt, { exact: true }).hover();
|
||||
await expect(
|
||||
directMessage.getByRole("button", { name: "Rewind to this message", exact: true }),
|
||||
).toHaveCount(0);
|
||||
|
||||
// Post-switch prompt on Mock CAN rewind without retiring earlier segments or markers.
|
||||
await backToMockMessage.scrollIntoViewIfNeeded();
|
||||
await rewindConversation(page, backToMockMessage, backToMockPrompt);
|
||||
await expect(
|
||||
page.getByTestId("user-message").filter({ hasText: backToMockPrompt }),
|
||||
).toHaveCount(0, { timeout: 30_000 });
|
||||
await expect(
|
||||
page.getByTestId("user-message").filter({ hasText: preSwitchPrompt }),
|
||||
).toBeVisible();
|
||||
await expect(
|
||||
page.getByTestId("user-message").filter({ hasText: postSwitchPrompt }),
|
||||
).toBeVisible();
|
||||
await expect(page.getByTestId("provider-switch-marker")).toHaveCount(2);
|
||||
|
||||
// Continuing in the now-empty active segment completes cleanly.
|
||||
const retriedMessage = await completeMockTurn(page, workspace, postRewindPrompt);
|
||||
await expect(retriedMessage).not.toContainText("<chat-history-summary>");
|
||||
});
|
||||
|
||||
await test.step("reload preserves the switched provider, markers, and rewind boundary", async () => {
|
||||
await page.reload();
|
||||
await expectComposerVisible(page);
|
||||
await expectComposerModel(page, "Ten second stream");
|
||||
await expectSwitchMarkerCountAfterScroll(page, 2);
|
||||
const reloadedDirect = page
|
||||
.getByTestId("user-message")
|
||||
.filter({ hasText: postSwitchPrompt });
|
||||
await expect(reloadedDirect).toBeVisible();
|
||||
await expect(
|
||||
page.getByTestId("user-message").filter({ hasText: postRewindPrompt }),
|
||||
).toBeVisible();
|
||||
|
||||
await reloadedDirect.scrollIntoViewIfNeeded();
|
||||
await reloadedDirect.getByText(postSwitchPrompt, { exact: true }).hover();
|
||||
await expect(
|
||||
reloadedDirect.getByRole("button", { name: "Rewind to this message", exact: true }),
|
||||
).toHaveCount(0);
|
||||
});
|
||||
} finally {
|
||||
await workspace.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("stages a switch mid-turn, queues the prompt, and switches cleanly between turns", async ({
|
||||
page,
|
||||
}) => {
|
||||
test.setTimeout(150_000);
|
||||
await page.setViewportSize({ width: 1280, height: 800 });
|
||||
|
||||
const runningPrompt = "Run a ten-second mock turn first.";
|
||||
const queuedPrompt = "Queued handoff prompt for Direct provider.";
|
||||
|
||||
const workspace = await seedMockAgentWorkspace({
|
||||
repoPrefix: "provider-switch-midturn-",
|
||||
title: "Provider switch midturn",
|
||||
model: "ten-second-stream",
|
||||
modeId: "load-test",
|
||||
});
|
||||
|
||||
try {
|
||||
await openAgentRoute(page, workspace);
|
||||
await expectComposerVisible(page);
|
||||
|
||||
await submitMessage(page, runningPrompt);
|
||||
await expectAgentReadyToInterrupt(page);
|
||||
|
||||
// Stage Direct provider while Mock is actively streaming.
|
||||
await stageDirectProviderDesktop(page);
|
||||
await expectWorkspaceAgentConfiguration(workspace, {
|
||||
id: workspace.agentId,
|
||||
provider: "mock",
|
||||
model: "ten-second-stream",
|
||||
modeId: "load-test",
|
||||
});
|
||||
|
||||
// Submitting queues the prompt instead of racing the live turn.
|
||||
await submitMessage(page, queuedPrompt);
|
||||
await expectQueuedMessageButton(page);
|
||||
|
||||
// Once the mock turn completes, the queue drains and commits the switch.
|
||||
await expect(page.getByTestId("provider-switch-marker")).toBeVisible({ timeout: 45_000 });
|
||||
await expect(page.getByTestId("staged-provider-switch-banner")).toHaveCount(0, {
|
||||
timeout: 30_000,
|
||||
});
|
||||
await expect(
|
||||
page.getByTestId("assistant-message").filter({ hasText: queuedPrompt }).last(),
|
||||
).toBeVisible({ timeout: 30_000 });
|
||||
await expectAgentIdle(page);
|
||||
await expectWorkspaceAgentConfiguration(workspace, {
|
||||
id: workspace.agentId,
|
||||
provider: DIRECT_PROVIDER.id,
|
||||
model: DIRECT_PROVIDER.modelId,
|
||||
modeId: "build",
|
||||
});
|
||||
} finally {
|
||||
await workspace.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("switches providers cleanly on a compact viewport with zero horizontal overflow", async ({
|
||||
page,
|
||||
}) => {
|
||||
test.setTimeout(150_000);
|
||||
await page.setViewportSize({ width: 390, height: 844 });
|
||||
|
||||
const preSwitchPrompt = "Compact turn on Mock.";
|
||||
const postSwitchPrompt = "Compact handoff on Direct.";
|
||||
|
||||
const workspace = await seedMockAgentWorkspace({
|
||||
repoPrefix: "provider-switch-compact-",
|
||||
title: "Provider switch compact",
|
||||
model: "e2e-fast-stream",
|
||||
modeId: "load-test",
|
||||
});
|
||||
|
||||
try {
|
||||
await openAgentRoute(page, workspace);
|
||||
await expectComposerVisible(page);
|
||||
|
||||
await submitMessageWithButton(page, preSwitchPrompt);
|
||||
await expect(
|
||||
page.getByTestId("user-message").filter({ hasText: preSwitchPrompt }),
|
||||
).toBeVisible({ timeout: 30_000 });
|
||||
const firstFinish = await workspace.client.waitForFinish(workspace.agentId, 30_000);
|
||||
expect(firstFinish.status).toBe("idle");
|
||||
await expectAgentIdle(page);
|
||||
|
||||
await stageDirectProviderCompact(page);
|
||||
await expectNoHorizontalOverflow(page);
|
||||
await captureQaScreenshot(page, "compact-staged-switch.png");
|
||||
|
||||
const switchedMessage = await completeDirectTurn(page, workspace, postSwitchPrompt, {
|
||||
useSendButton: true,
|
||||
});
|
||||
await expect(switchedMessage).not.toContainText("<chat-history-summary>");
|
||||
|
||||
const marker = page.getByTestId("provider-switch-marker");
|
||||
await expect(marker).toBeVisible({ timeout: 30_000 });
|
||||
await marker.scrollIntoViewIfNeeded();
|
||||
const toggle = marker.getByTestId("provider-switch-marker-toggle");
|
||||
const toggleBox = await toggle.boundingBox();
|
||||
expect(toggleBox).not.toBeNull();
|
||||
expect((toggleBox?.x ?? 0) + (toggleBox?.width ?? 0)).toBeLessThanOrEqual(390);
|
||||
await toggle.click();
|
||||
await expect(marker.getByTestId("provider-switch-marker-details")).toBeVisible();
|
||||
await marker.scrollIntoViewIfNeeded();
|
||||
await expectNoHorizontalOverflow(page);
|
||||
await captureQaScreenshot(page, "compact-switched-expanded.png");
|
||||
} finally {
|
||||
await workspace.cleanup();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -235,7 +235,7 @@ test.describe("Rewind sheet", () => {
|
||||
await expect(page.getByTestId("rewind-menu-content")).toHaveCount(0);
|
||||
await expect(userMessage(page, secondPrompt)).toHaveCount(0);
|
||||
await expect(page.getByText("Cycle 1", { exact: true })).toHaveCount(0);
|
||||
await expectUserMessageCount(page, 1);
|
||||
await expectUserMessageCount(page, 0);
|
||||
await expectComposerDraft(page, firstPrompt);
|
||||
await expectComposerFocused(page);
|
||||
|
||||
@@ -243,7 +243,7 @@ test.describe("Rewind sheet", () => {
|
||||
await expectUserMessageVisible(page, replacementPrompt);
|
||||
await expect(userMessage(page, secondPrompt)).toHaveCount(0);
|
||||
await expect(page.getByText("Cycle 1", { exact: true })).toHaveCount(0);
|
||||
await expectUserMessageCount(page, 2);
|
||||
await expectUserMessageCount(page, 1);
|
||||
|
||||
await fillComposerDraft(page, "");
|
||||
await composerLocator(page).evaluate((element) => element.blur());
|
||||
@@ -254,7 +254,19 @@ test.describe("Rewind sheet", () => {
|
||||
await expect(page.getByTestId("rewind-menu-content")).toHaveCount(0);
|
||||
await expectComposerDraft(page, "");
|
||||
await expectComposerNotFocused(page);
|
||||
await expectUserMessageCount(page, 2);
|
||||
await expectUserMessageCount(page, 1);
|
||||
|
||||
const preservedDraft = "Keep this human draft after rewind.";
|
||||
await fillComposerDraft(page, preservedDraft);
|
||||
await composerLocator(page).evaluate((element) => element.blur());
|
||||
await userMessage(page, replacementPrompt).hover();
|
||||
await page.getByTestId("rewind-menu-trigger").last().click();
|
||||
await expect(page.getByTestId("rewind-menu-content")).toBeVisible();
|
||||
await selectRewindOption(page, "Rewind files");
|
||||
await expect(page.getByTestId("rewind-menu-content")).toHaveCount(0);
|
||||
await expectComposerDraft(page, preservedDraft);
|
||||
await expectComposerNotFocused(page);
|
||||
await expectUserMessageCount(page, 1);
|
||||
|
||||
await fillComposerDraft(page, "");
|
||||
await composerLocator(page).evaluate((element) => element.blur());
|
||||
@@ -265,7 +277,7 @@ test.describe("Rewind sheet", () => {
|
||||
await expect(page.getByTestId("rewind-menu-content")).toHaveCount(0);
|
||||
await expectComposerDraft(page, replacementPrompt);
|
||||
await expectComposerFocused(page);
|
||||
await expectUserMessageCount(page, 1);
|
||||
await expectUserMessageCount(page, 0);
|
||||
} finally {
|
||||
await session.cleanup();
|
||||
}
|
||||
|
||||
@@ -35,7 +35,13 @@ import {
|
||||
expectSettingsHeader,
|
||||
openAddHostFlow,
|
||||
selectHostConnectionType,
|
||||
toggleHostAdvanced,
|
||||
selectDirectConnectionMode,
|
||||
expectDirectConnectionMode,
|
||||
expectDirectFormModeDisabled,
|
||||
connectDirectHost,
|
||||
connectDirectHostExpectingPassword,
|
||||
pasteIntoDirectHost,
|
||||
fillDirectHostPromptPassword,
|
||||
openCompactSettings,
|
||||
expectCompactSettingsList,
|
||||
expectSettingsSidebarVisible,
|
||||
@@ -50,11 +56,11 @@ import {
|
||||
fillDirectHostUri,
|
||||
expectDirectHostFormValues,
|
||||
expectDirectHostSslEnabled,
|
||||
expectDirectHostSslDisabled,
|
||||
fillDirectHostAddress,
|
||||
toggleDirectHostSsl,
|
||||
expectDirectHostUriValue,
|
||||
expectDirectHostUriHidden,
|
||||
expectDirectFormFullyVisible,
|
||||
expectDiagnosticsContent,
|
||||
expectAboutContent,
|
||||
expectGeneralContent,
|
||||
@@ -71,6 +77,7 @@ import {
|
||||
bindCommandCenterToEnter,
|
||||
} from "../support/helpers/settings";
|
||||
import { getServerId } from "../support/helpers/server-id";
|
||||
import { startIsolatedHostDaemon } from "../support/helpers/isolated-host-daemon";
|
||||
import { expectAppRoute } from "../support/helpers/route-assertions";
|
||||
import { clickNewChat, gotoWorkspace } from "../support/helpers/launcher";
|
||||
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
|
||||
@@ -327,44 +334,105 @@ test.describe("Settings sidebar navigation", () => {
|
||||
await verifyLegacyHostSettingsRedirect(page);
|
||||
});
|
||||
|
||||
test("direct connection advanced URI round-trips SSL and password into the form", async ({
|
||||
page,
|
||||
}) => {
|
||||
test("direct connection converts between Form and URI modes", async ({ page }) => {
|
||||
await gotoAppShell(page);
|
||||
await openSettings(page);
|
||||
await openAddHostFlow(page);
|
||||
await expectAddHostMethodOptions(page);
|
||||
await selectHostConnectionType(page, "direct");
|
||||
await expectDirectConnectionMode(page, "Form");
|
||||
|
||||
await fillDirectHostAddress(page, "example.paseo.test", "7443");
|
||||
await expectDirectHostSslDisabled(page);
|
||||
await toggleDirectHostSsl(page);
|
||||
await expectDirectHostSslEnabled(page);
|
||||
await toggleHostAdvanced(page);
|
||||
await expectDirectHostUriValue(page, "tcp://example.paseo.test:7443?ssl=true");
|
||||
await toggleHostAdvanced(page);
|
||||
await toggleDirectHostSsl(page);
|
||||
await expectDirectHostSslDisabled(page);
|
||||
|
||||
await toggleHostAdvanced(page);
|
||||
await fillDirectHostUri(page, "tcp://example.paseo.test:7443?ssl=true&password=shared-secret");
|
||||
await toggleHostAdvanced(page);
|
||||
|
||||
await expectDirectHostFormValues(page, {
|
||||
host: "example.paseo.test",
|
||||
port: "7443",
|
||||
password: "shared-secret",
|
||||
await test.step("Form fields become a URI", async () => {
|
||||
await fillDirectHostAddress(page, "example.paseo.test", "7443");
|
||||
await toggleDirectHostSsl(page);
|
||||
await selectDirectConnectionMode(page, "URI");
|
||||
await expectDirectHostUriValue(page, "tcp://example.paseo.test:7443?ssl=true");
|
||||
});
|
||||
await expectDirectHostSslEnabled(page);
|
||||
await expectDirectHostUriHidden(page);
|
||||
|
||||
await toggleHostAdvanced(page);
|
||||
await expectDirectHostUriValue(
|
||||
page,
|
||||
"tcp://example.paseo.test:7443?ssl=true&password=shared-secret",
|
||||
);
|
||||
await toggleHostAdvanced(page);
|
||||
await expectDirectHostUriHidden(page);
|
||||
await test.step("a URI becomes Form fields", async () => {
|
||||
await fillDirectHostUri(
|
||||
page,
|
||||
"tcp://example.paseo.test:7443?ssl=true&password=shared-secret",
|
||||
);
|
||||
await selectDirectConnectionMode(page, "Form");
|
||||
await expectDirectHostFormValues(page, {
|
||||
host: "example.paseo.test",
|
||||
port: "7443",
|
||||
password: "shared-secret",
|
||||
});
|
||||
await expectDirectHostSslEnabled(page);
|
||||
await expectDirectHostUriHidden(page);
|
||||
});
|
||||
|
||||
await test.step("a pairing link pasted into Host stays a URI", async () => {
|
||||
const link = "relay://relay.paseo.test:443/srv_e2e_pairing?key=daemon-key&ssl=true";
|
||||
await pasteIntoDirectHost(page, link);
|
||||
await expectDirectConnectionMode(page, "URI");
|
||||
await expectDirectHostUriValue(page, link);
|
||||
await expectDirectFormModeDisabled(page);
|
||||
});
|
||||
});
|
||||
|
||||
test("direct connection connects to a URI with Host blank", async ({ page }) => {
|
||||
await gotoAppShell(page);
|
||||
await openSettings(page);
|
||||
await openAddHostFlow(page);
|
||||
await selectHostConnectionType(page, "direct");
|
||||
|
||||
await selectDirectConnectionMode(page, "URI");
|
||||
await fillDirectHostUri(page, `tcp://127.0.0.1:${getE2EDaemonPort()}`);
|
||||
|
||||
await connectDirectHost(page);
|
||||
});
|
||||
|
||||
test("direct connection connects to an edited URI instead of the form", async ({ page }) => {
|
||||
await gotoAppShell(page);
|
||||
await openSettings(page);
|
||||
await openAddHostFlow(page);
|
||||
await selectHostConnectionType(page, "direct");
|
||||
|
||||
await fillDirectHostAddress(page, "127.0.0.1", "9");
|
||||
await selectDirectConnectionMode(page, "URI");
|
||||
await expectDirectHostUriValue(page, "tcp://127.0.0.1:9");
|
||||
await fillDirectHostUri(page, `tcp://127.0.0.1:${getE2EDaemonPort()}`);
|
||||
|
||||
await connectDirectHost(page);
|
||||
});
|
||||
|
||||
test("direct connection sends the password in a URI and asks again when it is wrong", async ({
|
||||
page,
|
||||
}) => {
|
||||
const password = "e2e uri password";
|
||||
const daemon = await startIsolatedHostDaemon("srv_e2e_uri_password_host", {
|
||||
environment: { ...process.env, PASEO_PASSWORD: password },
|
||||
});
|
||||
try {
|
||||
await gotoAppShell(page);
|
||||
await openSettings(page);
|
||||
|
||||
await test.step("a URI with the password connects with one tap", async () => {
|
||||
await openAddHostFlow(page);
|
||||
await selectHostConnectionType(page, "direct");
|
||||
await selectDirectConnectionMode(page, "URI");
|
||||
await fillDirectHostUri(
|
||||
page,
|
||||
`tcp://127.0.0.1:${daemon.port}?password=${encodeURIComponent(password)}`,
|
||||
);
|
||||
await connectDirectHost(page);
|
||||
});
|
||||
|
||||
await test.step("a wrong password asks for the host's password inline", async () => {
|
||||
await openAddHostFlow(page);
|
||||
await selectHostConnectionType(page, "direct");
|
||||
await selectDirectConnectionMode(page, "URI");
|
||||
await fillDirectHostUri(page, `tcp://127.0.0.1:${daemon.port}?password=wrong`);
|
||||
await connectDirectHostExpectingPassword(page, `127.0.0.1:${daemon.port}`);
|
||||
await fillDirectHostPromptPassword(page, password);
|
||||
await connectDirectHost(page);
|
||||
});
|
||||
} finally {
|
||||
await daemon.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("Escape lets settings dropdowns and modals close before leaving settings", async ({
|
||||
@@ -697,3 +765,16 @@ test("docked navigation keeps its density and Settings preserves reading width",
|
||||
await expectSettingsSidebarHidden(page);
|
||||
await expectAppearanceContent(page);
|
||||
});
|
||||
|
||||
test.describe("Settings — small phone", () => {
|
||||
test.use({ viewport: { width: 360, height: 640 } });
|
||||
|
||||
test("direct connection shows the whole form above Cancel and Connect", async ({ page }) => {
|
||||
await gotoAppShell(page);
|
||||
await openCompactSidebar(page);
|
||||
await openSettingsFromCompactSidebar(page);
|
||||
await openAddHostFlow(page);
|
||||
await selectHostConnectionType(page, "direct");
|
||||
await expectDirectFormFullyVisible(page);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -3,6 +3,7 @@ import { buildHostAgentDetailRoute } from "@/utils/host-routes";
|
||||
import { test } from "../support/fixtures";
|
||||
import { seedWorkspace, type SeedDaemonClient } from "../support/helpers/seed-client";
|
||||
import { getServerId } from "../support/helpers/server-id";
|
||||
import { getE2EDaemonPort } from "../support/helpers/daemon-port";
|
||||
import { observeTimelineSubscriptions } from "../support/helpers/timeline-delivery";
|
||||
import { waitForWorkspaceTabsVisible } from "../support/helpers/workspace-tabs";
|
||||
import { selectWorkspaceInSidebar } from "../support/helpers/sidebar";
|
||||
@@ -254,7 +255,226 @@ async function expectCurrentChatWithoutCatchUp(page: Page, message: string) {
|
||||
await expect(page.getByRole("alert").filter({ hasText: "Updating messages" })).toHaveCount(0);
|
||||
}
|
||||
|
||||
async function delayActiveDaemonPongs(page: Page, port: string) {
|
||||
let deliveredPongs = 0;
|
||||
let inFlightPings = 0;
|
||||
const delayedPongs = new Set<ReturnType<typeof setTimeout>>();
|
||||
await page.routeWebSocket(
|
||||
(url) => url.hostname === "localhost" && url.port === port,
|
||||
(socket) => {
|
||||
const server = socket.connectToServer();
|
||||
socket.onMessage((message) => {
|
||||
if (typeof message === "string" && JSON.parse(message).type === "ping") inFlightPings += 1;
|
||||
server.send(message);
|
||||
});
|
||||
server.onMessage((message) => {
|
||||
if (typeof message === "string" && JSON.parse(message).type === "pong") {
|
||||
const timer = setTimeout(() => {
|
||||
delayedPongs.delete(timer);
|
||||
socket.send(message);
|
||||
deliveredPongs += 1;
|
||||
inFlightPings -= 1;
|
||||
}, 1_000);
|
||||
delayedPongs.add(timer);
|
||||
} else {
|
||||
socket.send(message);
|
||||
}
|
||||
});
|
||||
},
|
||||
);
|
||||
return {
|
||||
delivered: () => deliveredPongs,
|
||||
settled: () => inFlightPings === 0 && delayedPongs.size === 0,
|
||||
dispose: () => {
|
||||
for (const timer of delayedPongs) clearTimeout(timer);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function readActiveLivenessRtt(page: Page): Promise<number> {
|
||||
return page.evaluate((serverId) => {
|
||||
const runtime = Reflect.get(globalThis, "__paseoHostRuntimeStore") as {
|
||||
getClient(id: string): { getLastLivenessRttMs(): number | null } | null;
|
||||
};
|
||||
return runtime.getClient(serverId)?.getLastLivenessRttMs() ?? 0;
|
||||
}, getServerId());
|
||||
}
|
||||
|
||||
async function readHostConnection(page: Page) {
|
||||
return page.evaluate((serverId) => {
|
||||
const runtime = Reflect.get(globalThis, "__paseoHostRuntimeStore") as {
|
||||
getSnapshot(id: string): {
|
||||
clientGeneration: number;
|
||||
connectionStatus: string;
|
||||
activeConnectionId: string;
|
||||
};
|
||||
};
|
||||
const snapshot = runtime.getSnapshot(serverId);
|
||||
return {
|
||||
generation: snapshot.clientGeneration,
|
||||
status: snapshot.connectionStatus,
|
||||
connection: snapshot.activeConnectionId,
|
||||
};
|
||||
}, getServerId());
|
||||
}
|
||||
|
||||
async function settleHostProbeCycle(page: Page): Promise<void> {
|
||||
await page.evaluate(async (serverId) => {
|
||||
const runtime = Reflect.get(globalThis, "__paseoHostRuntimeStore") as {
|
||||
runProbeCycleNow(id: string): Promise<void>;
|
||||
};
|
||||
// Joins any in-flight cycle through its final replacement handshake.
|
||||
await runtime.runProbeCycleNow(serverId);
|
||||
}, getServerId());
|
||||
}
|
||||
|
||||
async function observeContinuousHostConnection(page: Page) {
|
||||
const observation = await page.evaluateHandle((serverId) => {
|
||||
const runtime = Reflect.get(globalThis, "__paseoHostRuntimeStore") as {
|
||||
getSnapshot(id: string): { connectionStatus: string; client: unknown } | null;
|
||||
subscribe(id: string, listener: () => void): () => void;
|
||||
};
|
||||
const connected: boolean[] = [];
|
||||
const record = () => {
|
||||
const snapshot = runtime.getSnapshot(serverId);
|
||||
connected.push(snapshot?.connectionStatus === "online" && snapshot.client !== null);
|
||||
};
|
||||
record();
|
||||
const unsubscribe = runtime.subscribe(serverId, record);
|
||||
return {
|
||||
stop() {
|
||||
unsubscribe();
|
||||
return connected;
|
||||
},
|
||||
};
|
||||
}, getServerId());
|
||||
let stopped: Promise<boolean[]> | null = null;
|
||||
return {
|
||||
stop() {
|
||||
stopped ??= observation
|
||||
.evaluate((recorder) => recorder.stop())
|
||||
.finally(() => observation.dispose());
|
||||
return stopped;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function advanceToOnlineReplacement(
|
||||
page: Page,
|
||||
delayedPongs: Awaited<ReturnType<typeof delayActiveDaemonPongs>>,
|
||||
beforeGeneration: number,
|
||||
) {
|
||||
// Advance scheduling, not the sockets: settle real heartbeat and probe replies
|
||||
// between hops, including the replacement handshake, without altering production timers.
|
||||
for (let step = 0; step < 60; step += 1) {
|
||||
if ((await readHostConnection(page)).generation !== beforeGeneration) break;
|
||||
await expect.poll(delayedPongs.settled, { timeout: 10_000 }).toBe(true);
|
||||
await settleHostProbeCycle(page);
|
||||
const pongsBefore = delayedPongs.delivered();
|
||||
await page.clock.fastForward(10_000);
|
||||
await expect
|
||||
.poll(
|
||||
async () =>
|
||||
(await readHostConnection(page)).generation !== beforeGeneration ||
|
||||
delayedPongs.delivered() > pongsBefore,
|
||||
{ timeout: 10_000 },
|
||||
)
|
||||
.toBe(true);
|
||||
await settleHostProbeCycle(page);
|
||||
}
|
||||
}
|
||||
|
||||
test.describe("Viewed agent timelines", () => {
|
||||
test("an online connection replacement keeps every open chat synchronized", async ({
|
||||
page,
|
||||
}, testInfo) => {
|
||||
test.setTimeout(180_000);
|
||||
await page.clock.install();
|
||||
const port = getE2EDaemonPort();
|
||||
const delayedEndpoint = `localhost:${port}`;
|
||||
const fasterEndpoint = `127.0.0.1:${port}`;
|
||||
const delayedPongs = await delayActiveDaemonPongs(page, port);
|
||||
const subscriptions = observeTimelineSubscriptions(page);
|
||||
const scenario = await seedViewedTimelineScenario();
|
||||
let connectionObservation:
|
||||
| Awaited<ReturnType<typeof observeContinuousHostConnection>>
|
||||
| undefined;
|
||||
try {
|
||||
await commitMessage(scenario, scenario.firstAgentId, "BEFORE_CONNECTION_REPLACEMENT");
|
||||
await openAgent(page, scenario, scenario.firstAgentId);
|
||||
await selectAgent(page, "Second viewed chat");
|
||||
await selectAgent(page, "First viewed chat");
|
||||
await subscriptions.waitForSubscribedAgents([scenario.firstAgentId, scenario.secondAgentId]);
|
||||
await expectReconnectingToastGone(page);
|
||||
// The adaptive selector needs an RTT from the active socket, not only its startup probe.
|
||||
await expect.poll(delayedPongs.delivered, { timeout: 30_000 }).toBeGreaterThan(1);
|
||||
await expect
|
||||
.poll(() => readActiveLivenessRtt(page), { timeout: 30_000 })
|
||||
.toBeGreaterThanOrEqual(800);
|
||||
|
||||
// Add another real route to the same daemon. Delaying only the active route's real
|
||||
// pong frames gives the ordinary adaptive selector three consistently faster probes.
|
||||
// No host state is forced offline and no client or timeline owner is replaced by the test.
|
||||
connectionObservation = await observeContinuousHostConnection(page);
|
||||
const beforeGeneration = await page.evaluate(
|
||||
async ({ serverId, endpoint, activeEndpoint }) => {
|
||||
const runtime = Reflect.get(globalThis, "__paseoHostRuntimeStore") as {
|
||||
getSnapshot(id: string): {
|
||||
clientGeneration: number;
|
||||
connectionStatus: string;
|
||||
activeConnectionId: string;
|
||||
};
|
||||
upsertDirectConnection(input: { serverId: string; endpoint: string }): Promise<unknown>;
|
||||
};
|
||||
const before = runtime.getSnapshot(serverId);
|
||||
if (
|
||||
before.connectionStatus !== "online" ||
|
||||
before.activeConnectionId !== `direct:${activeEndpoint}`
|
||||
) {
|
||||
throw new Error("Expected the initial real connection to be online");
|
||||
}
|
||||
await runtime.upsertDirectConnection({ serverId, endpoint });
|
||||
return before.clientGeneration;
|
||||
},
|
||||
{ serverId: getServerId(), endpoint: fasterEndpoint, activeEndpoint: delayedEndpoint },
|
||||
);
|
||||
subscriptions.reset();
|
||||
await advanceToOnlineReplacement(page, delayedPongs, beforeGeneration);
|
||||
await expect
|
||||
.poll(() => readHostConnection(page), { timeout: 3_000 })
|
||||
.toEqual({
|
||||
generation: beforeGeneration + 1,
|
||||
status: "online",
|
||||
connection: `direct:${fasterEndpoint}`,
|
||||
});
|
||||
expect(await connectionObservation.stop()).not.toContain(false);
|
||||
await expectReconnectingToastGone(page, { timeout: 3_000 });
|
||||
await page.screenshot({
|
||||
path: testInfo.outputPath("after-online-connection-replacement.png"),
|
||||
});
|
||||
await subscriptions.waitForSubscribedAgents([scenario.firstAgentId], { match: "includes" });
|
||||
await commitMessage(scenario, scenario.firstAgentId, "FIRST_CHAT_AFTER_REPLACEMENT");
|
||||
await expect(page.getByText("FIRST_CHAT_AFTER_REPLACEMENT", { exact: true })).toBeVisible();
|
||||
await commitMessage(scenario, scenario.secondAgentId, "SECOND_CHAT_WHILE_HIDDEN");
|
||||
await selectAgent(page, "Second viewed chat");
|
||||
await expectReconnectingToastGone(page, { timeout: 3_000 });
|
||||
await expect(page.getByText("SECOND_CHAT_WHILE_HIDDEN", { exact: true })).toBeVisible();
|
||||
await subscriptions.waitForSubscribedAgents([scenario.firstAgentId, scenario.secondAgentId], {
|
||||
match: "includes",
|
||||
});
|
||||
await commitMessage(scenario, scenario.secondAgentId, "SECOND_CHAT_AFTER_REPLACEMENT");
|
||||
await expect(page.getByText("SECOND_CHAT_AFTER_REPLACEMENT", { exact: true })).toBeVisible();
|
||||
await page.screenshot({ path: testInfo.outputPath("both-chats-synchronized.png") });
|
||||
} finally {
|
||||
try {
|
||||
await connectionObservation?.stop();
|
||||
} finally {
|
||||
delayedPongs.dispose();
|
||||
await scenario.cleanup();
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test("a reloaded layout subscribes only the chat it restores into", async ({ page }) => {
|
||||
test.setTimeout(120_000);
|
||||
const subscriptions = observeTimelineSubscriptions(page);
|
||||
|
||||
@@ -111,7 +111,7 @@ Keep generated screenshots, recordings, and run logs outside the repository.
|
||||
confirmation. It first types without tapping the input to verify autofocus, then cancels the
|
||||
confirmation, closes and reopens the underlying sheet, confirms again,
|
||||
and completes the password retry. `stacked-settings.ad` checks the same return and retry through
|
||||
Settings → add host → Direct connection → Advanced. Run both on phones and tablets so both the
|
||||
Settings → add host → Direct connection → URI. Run both on phones and tablets so both the
|
||||
bottom sheet and centered dialog are exercised.
|
||||
|
||||
These integration journeys require the host-confirmation flow in the test app. Include both the
|
||||
@@ -146,7 +146,7 @@ Android uses the same journeys: copy each script outside the repository, change
|
||||
artifacts, and sessions separate from other runs. These host-dependent journeys remain outside the
|
||||
default mobile suite, alongside the existing modal-sheet scripts.
|
||||
|
||||
On iPhone, bulk replacement or bulk keyboard entry of the advanced URI field triggers a
|
||||
On iPhone, bulk replacement or bulk keyboard entry of the Connection URI field triggers a
|
||||
repeated-update error with both the parent and stacked-sheet implementations. Entering the complete
|
||||
URI one character at a time passed with both implementations; faster typing remains unverified.
|
||||
On iPad, replacing the field a second time appends text. For this Settings journey, use the
|
||||
|
||||
@@ -10,7 +10,7 @@ wait "id=\"add-host-method-direct\"" 10000
|
||||
screenshot "${OUT}/10-add-host-methods.png"
|
||||
press "id=\"add-host-method-direct\""
|
||||
wait stable
|
||||
press "id=\"direct-host-advanced-toggle\""
|
||||
press "id=\"direct-mode-uri\""
|
||||
wait stable
|
||||
fill "id=\"direct-host-uri-input\"" "${PAIRING_LINK}"
|
||||
wait stable
|
||||
@@ -32,9 +32,9 @@ wait "id=\"host-confirmation-connect\"" 10000
|
||||
screenshot "${OUT}/14-add-host-confirmation-reopens.png"
|
||||
press "id=\"host-confirmation-connect\""
|
||||
wait stable
|
||||
wait "id=\"direct-password-input\"" 20000
|
||||
wait "id=\"direct-uri-password-input\"" 20000
|
||||
screenshot "${OUT}/15-add-host-password.png"
|
||||
fill "id=\"direct-password-input\"" "${PASSWORD}"
|
||||
fill "id=\"direct-uri-password-input\"" "${PASSWORD}"
|
||||
wait stable
|
||||
press "id=\"direct-host-submit\""
|
||||
wait stable
|
||||
|
||||
@@ -31,6 +31,8 @@ export interface RewindCompletionGate {
|
||||
clearTimelineStreamCount(): void;
|
||||
release(): void;
|
||||
timelineStreamCount(): number;
|
||||
/** Timeline reads this page sent since the last clear. */
|
||||
timelineFetchCount(): number;
|
||||
waitForDelayedResponse(): Promise<void>;
|
||||
}
|
||||
|
||||
@@ -186,12 +188,20 @@ export async function holdDaemonHydration(page: Page): Promise<DaemonHydrationGa
|
||||
};
|
||||
}
|
||||
|
||||
// The rewind response and the timeline change it causes; the change removes the rewound row too.
|
||||
const REWIND_COMPLETION_MESSAGES = new Set([
|
||||
"agent.rewind.response",
|
||||
"agent.timeline.rewind",
|
||||
"agent.timeline.replacement",
|
||||
]);
|
||||
|
||||
export async function holdRewindCompletion(
|
||||
page: Page,
|
||||
agentId: string,
|
||||
): Promise<RewindCompletionGate> {
|
||||
let released = false;
|
||||
let timelineStreamCount = 0;
|
||||
let timelineFetchCount = 0;
|
||||
const delayedForwards: Array<() => void> = [];
|
||||
let resolveDelayedResponse: (() => void) | null = null;
|
||||
const delayedResponse = new Promise<void>((resolve) => {
|
||||
@@ -200,7 +210,16 @@ export async function holdRewindCompletion(
|
||||
|
||||
await page.routeWebSocket(daemonWsRoutePattern(), (ws) => {
|
||||
const server = ws.connectToServer();
|
||||
ws.onMessage((message) => server.send(message));
|
||||
ws.onMessage((message) => {
|
||||
const sessionMessage = getSessionMessage(message);
|
||||
if (
|
||||
sessionMessage?.type === "fetch_agent_timeline_request" &&
|
||||
sessionMessage.agentId === agentId
|
||||
) {
|
||||
timelineFetchCount += 1;
|
||||
}
|
||||
server.send(message);
|
||||
});
|
||||
server.onMessage((message) => {
|
||||
const sessionMessage = getSessionMessage(message);
|
||||
const payload = sessionMessage ? getPayload(sessionMessage) : null;
|
||||
@@ -216,11 +235,11 @@ export async function holdRewindCompletion(
|
||||
}
|
||||
if (
|
||||
!released &&
|
||||
(sessionMessage?.type === "agent.rewind.response" ||
|
||||
sessionMessage?.type === "agent.timeline.replacement") &&
|
||||
sessionMessage &&
|
||||
REWIND_COMPLETION_MESSAGES.has(String(sessionMessage.type)) &&
|
||||
payload?.agentId === agentId
|
||||
) {
|
||||
// The replacement also signals completion and removes the rewound row/menu.
|
||||
// The rewind also signals completion and removes the rewound row/menu.
|
||||
// Hold it with the response so the pending-state assertion observes a pending rewind.
|
||||
delayedForwards.push(() => ws.send(message));
|
||||
if (sessionMessage.type === "agent.rewind.response") resolveDelayedResponse?.();
|
||||
@@ -233,6 +252,7 @@ export async function holdRewindCompletion(
|
||||
return {
|
||||
clearTimelineStreamCount() {
|
||||
timelineStreamCount = 0;
|
||||
timelineFetchCount = 0;
|
||||
},
|
||||
release() {
|
||||
released = true;
|
||||
@@ -241,6 +261,7 @@ export async function holdRewindCompletion(
|
||||
}
|
||||
},
|
||||
timelineStreamCount: () => timelineStreamCount,
|
||||
timelineFetchCount: () => timelineFetchCount,
|
||||
waitForDelayedResponse: () => delayedResponse,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -258,8 +258,37 @@ export async function expectAddHostFieldDrawnAsInput(page: Page, testId: string)
|
||||
await expect(field).not.toHaveCSS("background-color", "rgba(0, 0, 0, 0)");
|
||||
}
|
||||
|
||||
export async function toggleHostAdvanced(page: Page): Promise<void> {
|
||||
await page.getByTestId("direct-host-advanced-toggle").click();
|
||||
function directConnectionModeSegment(page: Page, mode: "Form" | "URI") {
|
||||
return page.getByTestId("direct-mode").getByRole("button", { name: mode, exact: true });
|
||||
}
|
||||
|
||||
export async function selectDirectConnectionMode(page: Page, mode: "Form" | "URI"): Promise<void> {
|
||||
await directConnectionModeSegment(page, mode).click();
|
||||
await expectDirectConnectionMode(page, mode);
|
||||
}
|
||||
|
||||
export async function expectDirectConnectionMode(page: Page, mode: "Form" | "URI"): Promise<void> {
|
||||
await expect(directConnectionModeSegment(page, mode)).toHaveAttribute("aria-selected", "true");
|
||||
}
|
||||
|
||||
export async function expectDirectFormModeDisabled(page: Page): Promise<void> {
|
||||
await expect(directConnectionModeSegment(page, "Form")).toBeDisabled();
|
||||
}
|
||||
|
||||
export async function connectDirectHost(page: Page): Promise<void> {
|
||||
await page.getByTestId("direct-host-submit").click();
|
||||
await expect(page.getByTestId("add-host-modal")).toHaveCount(0, { timeout: 30_000 });
|
||||
}
|
||||
|
||||
export async function connectDirectHostExpectingPassword(page: Page, host: string): Promise<void> {
|
||||
await page.getByTestId("direct-host-submit").click();
|
||||
await expect(page.getByText(`Password for ${host}`, { exact: true })).toBeVisible({
|
||||
timeout: 30_000,
|
||||
});
|
||||
}
|
||||
|
||||
export async function fillDirectHostPromptPassword(page: Page, password: string): Promise<void> {
|
||||
await page.getByRole("textbox", { name: "Host password", exact: true }).fill(password);
|
||||
}
|
||||
|
||||
export async function openCompactSettings(page: Page, expectedStartRoute: string): Promise<void> {
|
||||
@@ -422,6 +451,10 @@ export async function fillDirectHostAddress(page: Page, host: string, port: stri
|
||||
await page.getByRole("textbox", { name: "Port", exact: true }).fill(port);
|
||||
}
|
||||
|
||||
export async function pasteIntoDirectHost(page: Page, text: string): Promise<void> {
|
||||
await page.getByRole("textbox", { name: "Host", exact: true }).fill(text);
|
||||
}
|
||||
|
||||
export async function toggleDirectHostSsl(page: Page): Promise<void> {
|
||||
await page.getByRole("checkbox", { name: "Use SSL", exact: true }).click();
|
||||
}
|
||||
@@ -439,6 +472,12 @@ export async function expectDirectHostUriHidden(page: Page): Promise<void> {
|
||||
await expect(page.getByTestId("direct-host-uri-input")).toHaveCount(0);
|
||||
}
|
||||
|
||||
/** The whole form shows above Cancel and Connect, with nothing cut off by the footer. */
|
||||
export async function expectDirectFormFullyVisible(page: Page): Promise<void> {
|
||||
await expect(page.getByTestId("direct-password-input")).toBeInViewport({ ratio: 1 });
|
||||
await expect(page.getByTestId("direct-password-visibility-toggle")).toBeInViewport({ ratio: 1 });
|
||||
}
|
||||
|
||||
export async function expectDiagnosticsContent(page: Page): Promise<void> {
|
||||
await expect(page.getByRole("button", { name: "Run" })).toBeVisible();
|
||||
await expect(page.getByRole("button", { name: "Play test" })).toBeVisible();
|
||||
|
||||
@@ -9,6 +9,7 @@ interface SessionMessage {
|
||||
|
||||
interface TimelineSubscriptionWaitOptions {
|
||||
timeout?: number;
|
||||
match?: "exact" | "includes";
|
||||
}
|
||||
|
||||
function readSessionMessage(message: WebSocketMessage): SessionMessage | null {
|
||||
@@ -56,7 +57,7 @@ export function observeTimelineSubscriptions(page: Page) {
|
||||
.poll(() => acknowledgedAgentIds?.slice().sort() ?? null, {
|
||||
timeout: options.timeout ?? 15_000,
|
||||
})
|
||||
.toEqual(expected);
|
||||
.toEqual(options.match === "includes" ? expect.arrayContaining(expected) : expected);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -63,6 +63,8 @@ using namespace facebook::react;
|
||||
- (instancetype)initWithFrame:(CGRect)frame
|
||||
{
|
||||
if (self = [super initWithFrame:frame]) {
|
||||
// The iOS status-bar tap region can overlap app header buttons (#11027).
|
||||
self.scrollView.scrollsToTop = NO;
|
||||
#if defined(__IPHONE_26_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_26_0
|
||||
if (@available(iOS 26.0, *)) {
|
||||
UIScrollView *scrollView = self.scrollView;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@getpaseo/app",
|
||||
"version": "0.18.1",
|
||||
"version": "0.18.2",
|
||||
"private": true,
|
||||
"main": "index.ts",
|
||||
"scripts": {
|
||||
|
||||
@@ -3,9 +3,12 @@ import { useTranslation } from "react-i18next";
|
||||
import { i18n } from "@/i18n/i18next";
|
||||
import { useProviderIcon } from "@/components/provider-icons";
|
||||
import type { PanelDescriptor } from "@/panels/panel-registry";
|
||||
import { resolveAgentLabel } from "@/panels/tab-labels";
|
||||
import { useSessionStore, selectAgentTurnPresentation, type Agent } from "@/stores/session-store";
|
||||
import { deriveSidebarStateBucket } from "@/utils/sidebar-agent-state";
|
||||
|
||||
export { resolveAgentLabel };
|
||||
|
||||
function formatProviderLabel(provider: Agent["provider"]): string {
|
||||
if (!provider) {
|
||||
return "Agent";
|
||||
@@ -17,20 +20,6 @@ function formatProviderLabel(provider: Agent["provider"]): string {
|
||||
.join(" ");
|
||||
}
|
||||
|
||||
export function resolveAgentLabel(title: string | null | undefined): string | null {
|
||||
if (typeof title !== "string") {
|
||||
return null;
|
||||
}
|
||||
const normalized = title.trim();
|
||||
if (!normalized) {
|
||||
return null;
|
||||
}
|
||||
if (normalized.toLowerCase() === "new agent") {
|
||||
return null;
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
|
||||
export function useAgentDescriptor(
|
||||
target: { kind: "agent"; agentId: string },
|
||||
context: { serverId: string },
|
||||
|
||||
@@ -23,7 +23,15 @@ export interface DraftAgentProfileControls {
|
||||
}
|
||||
|
||||
export type AgentProfileApplyTarget =
|
||||
| { kind: "agent"; agentId: string; availableModeIds: readonly string[] | null }
|
||||
| {
|
||||
kind: "agent";
|
||||
agentId: string;
|
||||
availableModeIds: readonly string[] | null;
|
||||
currentProvider?: string | null;
|
||||
isSwitchInFlight?: () => boolean;
|
||||
onApplySameProvider?: () => void;
|
||||
onStageProviderSwitch?: (profile: MaterializedAgentProfile) => void;
|
||||
}
|
||||
| { kind: "draft"; controls: DraftAgentProfileControls };
|
||||
|
||||
/** Everything the model picker renders for one profile. It never sees the profile itself. */
|
||||
@@ -148,6 +156,16 @@ export function useAgentProfilePicker(
|
||||
return;
|
||||
}
|
||||
|
||||
if (
|
||||
target.onStageProviderSwitch &&
|
||||
(target.isSwitchInFlight?.() ||
|
||||
(target.currentProvider && resolved.provider !== target.currentProvider))
|
||||
) {
|
||||
target.onStageProviderSwitch(resolved);
|
||||
return;
|
||||
}
|
||||
|
||||
target.onApplySameProvider?.();
|
||||
const reconciled = reconcileMaterializedProfileMode(resolved, target.availableModeIds);
|
||||
if (!reconciled) {
|
||||
return;
|
||||
@@ -157,7 +175,11 @@ export function useAgentProfilePicker(
|
||||
return;
|
||||
}
|
||||
void client
|
||||
.applyAgentConfig(target.agentId, toAgentConfigApply(reconciled))
|
||||
.applyAgentConfig(
|
||||
target.agentId,
|
||||
toAgentConfigApply(reconciled),
|
||||
target.currentProvider ? { expectedProvider: target.currentProvider } : undefined,
|
||||
)
|
||||
.then((notice) => showProviderNoticeToast(toast, notice))
|
||||
.catch((error) => {
|
||||
console.warn("[useAgentProfilePicker] applyAgentConfig failed", error);
|
||||
|
||||
@@ -56,6 +56,7 @@ export function ChatFind({
|
||||
agentId,
|
||||
serverId,
|
||||
epoch,
|
||||
rewindSeq,
|
||||
items,
|
||||
viewportRef,
|
||||
revealLoadedMessage,
|
||||
@@ -95,8 +96,8 @@ export function ChatFind({
|
||||
);
|
||||
const state = useSyncExternalStore(model.subscribe, model.getSnapshot, model.getSnapshot);
|
||||
useEffect(() => {
|
||||
model.updateHistory(epoch, items);
|
||||
}, [model, epoch, items]);
|
||||
model.updateHistory(epoch, items, rewindSeq);
|
||||
}, [model, epoch, items, rewindSeq]);
|
||||
useEffect(() => () => model.close(), [model]);
|
||||
useEffect(() => {
|
||||
if (!active) model.close();
|
||||
|
||||
@@ -18,7 +18,7 @@ function message(seq: number, text = "target"): StreamItem {
|
||||
kind: "assistant_message",
|
||||
text,
|
||||
timestamp: new Date(0),
|
||||
timelineCursor: { epoch: "epoch", seq },
|
||||
timelineCursor: { epoch: "epoch", seq, anchorSeq: seq },
|
||||
};
|
||||
}
|
||||
|
||||
@@ -39,7 +39,7 @@ it("loads an older location and searches a response merged across suppressed tas
|
||||
source.map((item, index) => ({
|
||||
event: { type: "timeline" as const, provider: "claude" as const, item },
|
||||
timestamp: new Date(0),
|
||||
timelineCursor: { epoch: "epoch", seq: index + 1 },
|
||||
timelineCursor: { epoch: "epoch", seq: index + 1, anchorSeq: index + 1 },
|
||||
})),
|
||||
{ source: "canonical" },
|
||||
);
|
||||
@@ -55,7 +55,7 @@ it("loads an older location and searches a response merged across suppressed tas
|
||||
},
|
||||
async load(_epoch, seq) {
|
||||
loaded.push(seq);
|
||||
model.updateHistory("epoch", history);
|
||||
model.updateHistory("epoch", history, null);
|
||||
},
|
||||
async reveal(_id, _query, occurrence) {
|
||||
revealed.push(occurrence);
|
||||
@@ -64,7 +64,7 @@ it("loads an older location and searches a response merged across suppressed tas
|
||||
clear() {},
|
||||
});
|
||||
try {
|
||||
model.updateHistory("epoch", []);
|
||||
model.updateHistory("epoch", [], null);
|
||||
model.open();
|
||||
model.setQuery("target");
|
||||
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
|
||||
@@ -99,7 +99,7 @@ it("skips a source-only candidate and highlights a displayed match", async () =>
|
||||
clear() {},
|
||||
});
|
||||
try {
|
||||
model.updateHistory("epoch", [message(1), message(2)]);
|
||||
model.updateHistory("epoch", [message(1), message(2)], null);
|
||||
model.open();
|
||||
model.setQuery("target");
|
||||
await expect.poll(() => model.getSnapshot().selectedItemId).toBe("row-2");
|
||||
@@ -129,7 +129,7 @@ it("ignores replies after closing and does not navigate", async () => {
|
||||
},
|
||||
clear() {},
|
||||
});
|
||||
model.updateHistory("epoch", [message(1)]);
|
||||
model.updateHistory("epoch", [message(1)], null);
|
||||
model.open();
|
||||
model.setQuery("target");
|
||||
await expect.poll(() => calls).toEqual(["search"]);
|
||||
@@ -155,7 +155,7 @@ it("retains a failed search for retry and distinguishes failure from zero matche
|
||||
};
|
||||
const model = new ChatFindModel(operations);
|
||||
try {
|
||||
model.updateHistory("epoch", []);
|
||||
model.updateHistory("epoch", [], null);
|
||||
model.open();
|
||||
model.setQuery("target");
|
||||
await expect.poll(() => model.getSnapshot().phase).toBe("error");
|
||||
@@ -185,7 +185,7 @@ it("reports a failed timeline load as a connection failure", async () => {
|
||||
clear() {},
|
||||
});
|
||||
try {
|
||||
model.updateHistory("epoch", []);
|
||||
model.updateHistory("epoch", [], null);
|
||||
model.open();
|
||||
model.setQuery("target");
|
||||
await expect.poll(() => model.getSnapshot().phase).toBe("error");
|
||||
@@ -207,24 +207,160 @@ it("reports a search result that outlived its epoch as a changed history", async
|
||||
clear() {},
|
||||
});
|
||||
try {
|
||||
model.updateHistory("epoch", [message(1)]);
|
||||
model.updateHistory("epoch", [message(1)], null);
|
||||
model.open();
|
||||
model.setQuery("target");
|
||||
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
|
||||
model.updateHistory("epoch-2", [message(1)]);
|
||||
model.updateHistory("epoch-2", [message(1)], null);
|
||||
expect(model.getSnapshot()).toMatchObject({ phase: "error", failure: "historyChanged" });
|
||||
} finally {
|
||||
model.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("reports results that a rewind took messages from as a changed history", async () => {
|
||||
const model = new ChatFindModel({
|
||||
async search() {
|
||||
return response([{ seq: 2, role: "assistant" }]);
|
||||
},
|
||||
async load() {},
|
||||
async reveal() {
|
||||
return { count: 1, occurrence: 0 };
|
||||
},
|
||||
clear() {},
|
||||
});
|
||||
try {
|
||||
model.updateHistory("epoch", [message(1), message(2)], null);
|
||||
model.open();
|
||||
model.setQuery("target");
|
||||
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
|
||||
expect(model.getSnapshot()).toMatchObject({ selectedItemId: "row-2", count: 1 });
|
||||
// Another client rewinds the turn holding the match; the epoch stays.
|
||||
model.updateHistory("epoch", [message(1)], 3);
|
||||
expect(model.getSnapshot()).toMatchObject({
|
||||
phase: "error",
|
||||
failure: "historyChanged",
|
||||
selectedItemId: null,
|
||||
});
|
||||
} finally {
|
||||
model.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("stops a search still receiving pages when a rewind lands between them", async () => {
|
||||
let pages = 0;
|
||||
let releaseSecondPage!: () => void;
|
||||
const secondPage = new Promise<void>((resolve) => {
|
||||
releaseSecondPage = resolve;
|
||||
});
|
||||
const model = new ChatFindModel({
|
||||
async search(_query, cursor) {
|
||||
pages += 1;
|
||||
if (cursor === undefined)
|
||||
return { ...response([{ seq: 2, role: "assistant" }]), nextCursor: 2 };
|
||||
await secondPage;
|
||||
return response([{ seq: 1, role: "assistant" }]);
|
||||
},
|
||||
async load() {},
|
||||
async reveal() {
|
||||
return { count: 1, occurrence: 0 };
|
||||
},
|
||||
clear() {},
|
||||
});
|
||||
try {
|
||||
model.updateHistory("epoch", [message(1), message(2)], null);
|
||||
model.open();
|
||||
model.setQuery("target");
|
||||
await expect.poll(() => pages).toBe(2);
|
||||
model.updateHistory("epoch", [message(1)], 3);
|
||||
releaseSecondPage();
|
||||
await expect.poll(() => model.getSnapshot().failure).toBe("historyChanged");
|
||||
expect(model.getSnapshot()).toMatchObject({ phase: "error", selectedItemId: null });
|
||||
} finally {
|
||||
model.close();
|
||||
}
|
||||
});
|
||||
|
||||
it.each([
|
||||
["Next", "next"],
|
||||
["Previous", "previous"],
|
||||
] as const)("reports a rewind after %s as a changed history", async (_label, step) => {
|
||||
const model = new ChatFindModel({
|
||||
async search() {
|
||||
return response([
|
||||
{ seq: 1, role: "assistant" },
|
||||
{ seq: 2, role: "assistant" },
|
||||
]);
|
||||
},
|
||||
async load() {},
|
||||
async reveal() {
|
||||
return { count: 1, occurrence: 0 };
|
||||
},
|
||||
clear() {},
|
||||
});
|
||||
try {
|
||||
model.updateHistory("epoch", [message(1), message(2)], null);
|
||||
model.open();
|
||||
model.setQuery("target");
|
||||
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
|
||||
model[step]();
|
||||
await expect.poll(() => model.getSnapshot().selectedItemId).toBe("row-2");
|
||||
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
|
||||
model.updateHistory("epoch", [message(1)], 3);
|
||||
expect(model.getSnapshot()).toMatchObject({
|
||||
phase: "error",
|
||||
failure: "historyChanged",
|
||||
selectedItemId: null,
|
||||
});
|
||||
} finally {
|
||||
model.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("stops a pending Next when a rewind lands before it reveals", async () => {
|
||||
let reveals = 0;
|
||||
let revealSecond!: () => void;
|
||||
const secondReveal = new Promise<void>((resolve) => {
|
||||
revealSecond = resolve;
|
||||
});
|
||||
const model = new ChatFindModel({
|
||||
async search() {
|
||||
return response([
|
||||
{ seq: 1, role: "assistant" },
|
||||
{ seq: 2, role: "assistant" },
|
||||
]);
|
||||
},
|
||||
async load() {},
|
||||
async reveal() {
|
||||
reveals += 1;
|
||||
if (reveals > 1) await secondReveal;
|
||||
return { count: 1, occurrence: 0 };
|
||||
},
|
||||
clear() {},
|
||||
});
|
||||
try {
|
||||
model.updateHistory("epoch", [message(1), message(2)], null);
|
||||
model.open();
|
||||
model.setQuery("target");
|
||||
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
|
||||
model.next();
|
||||
await expect.poll(() => reveals).toBe(2);
|
||||
model.updateHistory("epoch", [message(1)], 3);
|
||||
revealSecond();
|
||||
await expect.poll(() => model.getSnapshot().failure).toBe("historyChanged");
|
||||
expect(model.getSnapshot()).toMatchObject({ phase: "error", selectedItemId: null });
|
||||
} finally {
|
||||
model.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("can load a search location before the initial chat history has arrived", async () => {
|
||||
const model = new ChatFindModel({
|
||||
async search() {
|
||||
return response([{ seq: 1, role: "assistant" }]);
|
||||
},
|
||||
async load() {
|
||||
model.updateHistory("epoch", [message(1)]);
|
||||
model.updateHistory("epoch", [message(1)], null);
|
||||
},
|
||||
async reveal() {
|
||||
return { count: 1, occurrence: 0 };
|
||||
@@ -232,7 +368,7 @@ it("can load a search location before the initial chat history has arrived", asy
|
||||
clear() {},
|
||||
});
|
||||
try {
|
||||
model.updateHistory(null, []);
|
||||
model.updateHistory(null, [], null);
|
||||
model.open();
|
||||
model.setQuery("target");
|
||||
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
|
||||
@@ -260,7 +396,7 @@ it("reports the position across the whole chat and corrects it with rendered cou
|
||||
clear() {},
|
||||
});
|
||||
try {
|
||||
model.updateHistory("epoch", [message(1), message(2)]);
|
||||
model.updateHistory("epoch", [message(1), message(2)], null);
|
||||
model.open();
|
||||
model.setQuery("target");
|
||||
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
|
||||
@@ -297,7 +433,7 @@ it("counts one match per message from a host that reports no counts", async () =
|
||||
clear() {},
|
||||
});
|
||||
try {
|
||||
model.updateHistory("epoch", [message(1), message(2)]);
|
||||
model.updateHistory("epoch", [message(1), message(2)], null);
|
||||
model.open();
|
||||
model.setQuery("target");
|
||||
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
|
||||
|
||||
@@ -76,6 +76,10 @@ export class ChatFindModel {
|
||||
private items: StreamItem[] = [];
|
||||
private epoch: string | null = null;
|
||||
private resultEpoch: string | null = null;
|
||||
/** The latest rewind applied to the history. A rewind keeps the epoch and retires messages. */
|
||||
private rewindSeq: number | null = null;
|
||||
/** The latest rewind when the current result set's search started; undefined until a search starts. */
|
||||
private searchedRewindSeq: number | null | undefined = undefined;
|
||||
private locations: Location[] = [];
|
||||
private resolved = new Map<Location, Target>();
|
||||
private current = -1;
|
||||
@@ -113,6 +117,7 @@ export class ChatFindModel {
|
||||
this.cancel();
|
||||
this.locations = [];
|
||||
this.resultEpoch = null;
|
||||
this.searchedRewindSeq = undefined;
|
||||
this.resolved.clear();
|
||||
this.current = -1;
|
||||
this.inMessage = { occurrence: 0, count: 0 };
|
||||
@@ -144,6 +149,7 @@ export class ChatFindModel {
|
||||
});
|
||||
}
|
||||
private async search(signal: AbortSignal) {
|
||||
this.searchedRewindSeq = this.rewindSeq;
|
||||
try {
|
||||
let cursor: number | undefined;
|
||||
do {
|
||||
@@ -168,15 +174,14 @@ export class ChatFindModel {
|
||||
this.fail(error, signal);
|
||||
}
|
||||
}
|
||||
updateHistory(epoch: string | null, items: StreamItem[]) {
|
||||
if (
|
||||
this.resultEpoch !== null &&
|
||||
epoch !== null &&
|
||||
epoch !== this.resultEpoch &&
|
||||
this.state.open
|
||||
) {
|
||||
/** `rewindSeq` is the sequence number of the latest rewind applied to this history. */
|
||||
updateHistory(epoch: string | null, items: StreamItem[], rewindSeq: number | null) {
|
||||
const replaced = this.resultEpoch !== null && epoch !== null && epoch !== this.resultEpoch;
|
||||
const rewound = this.searchedRewindSeq !== undefined && rewindSeq !== this.searchedRewindSeq;
|
||||
if ((replaced || rewound) && this.state.open) {
|
||||
this.fail(new ChatFindFailureError("historyChanged"), this.abort.signal);
|
||||
}
|
||||
this.rewindSeq = rewindSeq;
|
||||
this.epoch = epoch;
|
||||
this.items = items;
|
||||
this.historyListeners.forEach((listener) => listener());
|
||||
|
||||
@@ -9,6 +9,8 @@ export interface ChatFindProps {
|
||||
agentId: string;
|
||||
serverId: string;
|
||||
epoch: string | null;
|
||||
/** The sequence number of the latest rewind applied to this history, if any. */
|
||||
rewindSeq: number | null;
|
||||
items: StreamItem[];
|
||||
viewportRef: RefObject<StreamViewportHandle | null>;
|
||||
revealLoadedMessage(messageId: string): boolean;
|
||||
|
||||
@@ -139,7 +139,7 @@ describe("useChatOutline", () => {
|
||||
kind: "user_message",
|
||||
text: "live prompt",
|
||||
timestamp: new Date(seq),
|
||||
timelineCursor: { epoch: "epoch-1", seq },
|
||||
timelineCursor: { epoch: "epoch-1", seq, anchorSeq: seq },
|
||||
});
|
||||
rerender({ tail: [loadedPrompt(2)] });
|
||||
await waitFor(() => expect(runtime.listAgentTimelinePrompts).toHaveBeenCalledTimes(2));
|
||||
@@ -198,7 +198,7 @@ describe("useChatOutline", () => {
|
||||
kind: "assistant_message",
|
||||
text: "chunk",
|
||||
timestamp: new Date(),
|
||||
timelineCursor: { epoch: "epoch-1", seq: 2 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 2, anchorSeq: 2 },
|
||||
},
|
||||
],
|
||||
timelineEpoch: "epoch-1",
|
||||
@@ -219,7 +219,7 @@ describe("useChatOutline", () => {
|
||||
kind: "user_message",
|
||||
text: "Replaced conversation",
|
||||
timestamp: new Date(2),
|
||||
timelineCursor: { epoch: "epoch-2", seq: 1 },
|
||||
timelineCursor: { epoch: "epoch-2", seq: 1, anchorSeq: 1 },
|
||||
},
|
||||
],
|
||||
timelineEpoch: "epoch-2",
|
||||
@@ -275,7 +275,7 @@ describe("useChatOutline", () => {
|
||||
kind: "user_message" as const,
|
||||
text: "prompt",
|
||||
timestamp: new Date(1),
|
||||
timelineCursor: { epoch: "epoch-1", seq: 1 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 1, anchorSeq: 1 },
|
||||
},
|
||||
];
|
||||
const { result, rerender } = renderHook(
|
||||
@@ -326,7 +326,7 @@ describe("useChatOutline", () => {
|
||||
kind: "user_message" as const,
|
||||
text: "prompt",
|
||||
timestamp: new Date(1),
|
||||
timelineCursor: { epoch: "epoch-1", seq: 1 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 1, anchorSeq: 1 },
|
||||
};
|
||||
const { result, rerender } = renderHook(
|
||||
({ tail, mountedHistoryMessageIds }) =>
|
||||
@@ -381,7 +381,7 @@ describe("useChatOutline", () => {
|
||||
kind: "user_message" as const,
|
||||
text: "prompt",
|
||||
timestamp: new Date(2),
|
||||
timelineCursor: { epoch: "epoch-1", seq: 2 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 2, anchorSeq: 2 },
|
||||
};
|
||||
const revealLoadedMessage = vi.fn();
|
||||
revealLoadedMessage.mockReturnValue(false);
|
||||
|
||||
@@ -58,7 +58,11 @@ function installProbe(
|
||||
return function() {};
|
||||
} };
|
||||
})`;
|
||||
const evaluated = runPluginClientBundle("probe-plugin", clientBundle, runtime);
|
||||
const evaluated = runPluginClientBundle(
|
||||
{ serverId: "test-host", pluginId: "probe-plugin" },
|
||||
clientBundle,
|
||||
runtime,
|
||||
);
|
||||
return {
|
||||
...evaluated,
|
||||
serverId: "host-1",
|
||||
@@ -322,7 +326,7 @@ describe("stream presentation through installed plugins", () => {
|
||||
const source = harness.source();
|
||||
const live = source.head[0];
|
||||
if (live?.kind !== "assistant_message") throw new Error("Expected a live assistant message");
|
||||
const canonical = { ...live, timelineCursor: { epoch: "epoch-1", seq: 42 } };
|
||||
const canonical = { ...live, timelineCursor: { epoch: "epoch-1", seq: 42, anchorSeq: 42 } };
|
||||
const present = createStreamPresentation();
|
||||
present({ ...presentationOptions, tail: [], head: [live], transform: undefined });
|
||||
const repointed = rows(
|
||||
@@ -332,7 +336,7 @@ describe("stream presentation through installed plugins", () => {
|
||||
{
|
||||
id: streamed[0]!.id,
|
||||
text: "Streamed answer",
|
||||
timelineCursor: { epoch: "epoch-1", seq: 42 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 42, anchorSeq: 42 },
|
||||
},
|
||||
]);
|
||||
});
|
||||
@@ -519,7 +523,7 @@ describe("timeline presentation", () => {
|
||||
messageId: "provider-message",
|
||||
clientMessageId: "client-message",
|
||||
turnId: "turn-1",
|
||||
timelineCursor: { epoch: "epoch", seq: 12 },
|
||||
timelineCursor: { epoch: "epoch", seq: 12, anchorSeq: 12 },
|
||||
});
|
||||
const presentMessage = () =>
|
||||
present({
|
||||
|
||||
@@ -7,7 +7,7 @@ import { act } from "react";
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { RetainedPanelActivity } from "@/components/retained-panel";
|
||||
import { reduceStreamUpdate, type StreamItem } from "@/types/stream";
|
||||
import { hydrateStreamState, reduceStreamUpdate, type StreamItem } from "@/types/stream";
|
||||
import type { StreamRenderInput, StreamSegmentRenderers, StreamViewportHandle } from "./strategy";
|
||||
import { createWebStreamStrategy } from "./strategy-web";
|
||||
|
||||
@@ -1660,4 +1660,86 @@ describe("createWebStreamStrategy", () => {
|
||||
expect(container.querySelector('[data-testid="agent-chat-scroll"]')).toBe(scrollContainer);
|
||||
expect(scrollTo).toHaveBeenCalledWith({ top: 2200, behavior: "auto" });
|
||||
});
|
||||
|
||||
it("renders batched user messages sharing a provider messageId without duplicate React keys", () => {
|
||||
const sharedProviderMessageId = "9ffc3d6e-f0ff-4005-8675-e76e9c5eb5a8";
|
||||
const historyMounted = hydrateStreamState(
|
||||
[
|
||||
{
|
||||
event: {
|
||||
type: "timeline",
|
||||
provider: "claude",
|
||||
item: {
|
||||
type: "user_message",
|
||||
text: "first queued prompt",
|
||||
messageId: sharedProviderMessageId,
|
||||
clientMessageId: "client-queued-1",
|
||||
},
|
||||
},
|
||||
timestamp: new Date("2026-11-29T13:00:00.000Z"),
|
||||
timelineCursor: { epoch: "epoch-1", seq: 1, anchorSeq: 1 },
|
||||
},
|
||||
{
|
||||
event: {
|
||||
type: "timeline",
|
||||
provider: "claude",
|
||||
item: {
|
||||
type: "user_message",
|
||||
text: "second direct prompt",
|
||||
messageId: sharedProviderMessageId,
|
||||
clientMessageId: "client-direct-2",
|
||||
},
|
||||
},
|
||||
timestamp: new Date("2026-11-29T13:00:01.000Z"),
|
||||
timelineCursor: { epoch: "epoch-1", seq: 2, anchorSeq: 2 },
|
||||
},
|
||||
],
|
||||
{ source: "canonical" },
|
||||
);
|
||||
const consoleError = vi.spyOn(console, "error").mockImplementation(() => {});
|
||||
const renderers = createRenderers(() => {});
|
||||
const strategy = createWebStreamStrategy({ isMobileBreakpoint: false });
|
||||
container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
root = createRoot(container);
|
||||
|
||||
const rendered = strategy.render({
|
||||
agentId: "agent",
|
||||
segments: { historyVirtualized: [], historyMounted, liveHead: [] },
|
||||
boundary: {
|
||||
hasVirtualizedHistory: false,
|
||||
hasMountedHistory: true,
|
||||
hasLiveHead: false,
|
||||
},
|
||||
renderers,
|
||||
listEmptyComponent: null,
|
||||
viewportRef: React.createRef<StreamViewportHandle>(),
|
||||
routeBottomAnchorRequest: null,
|
||||
isAuthoritativeHistoryReady: true,
|
||||
onNearBottomChange: () => {},
|
||||
onNearHistoryStart: async () => true,
|
||||
isLoadingOlderHistory: false,
|
||||
hasOlderHistory: false,
|
||||
olderHistoryProgressKey: null,
|
||||
scrollEnabled: true,
|
||||
listStyle: null,
|
||||
baseListContentContainerStyle: null,
|
||||
forwardListContentContainerStyle: null,
|
||||
contentMaxWidth: DEFAULT_CONTENT_MAX_WIDTH,
|
||||
});
|
||||
act(() => {
|
||||
root?.render(rendered);
|
||||
});
|
||||
|
||||
const isSameKeyMessage = (arg: unknown) => typeof arg === "string" && arg.includes("same key");
|
||||
const duplicateKeyErrors = consoleError.mock.calls.filter((args) =>
|
||||
args.some(isSameKeyMessage),
|
||||
);
|
||||
expect(duplicateKeyErrors).toEqual([]);
|
||||
expect(
|
||||
Array.from(container.querySelectorAll("[data-history-row-id]")).map((node) =>
|
||||
node.getAttribute("data-history-row-id"),
|
||||
),
|
||||
).toEqual(["client-queued-1", "client-direct-2"]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -33,7 +33,7 @@ describe("resolveAssistantTurnForkBoundary", () => {
|
||||
it("forks a failed assistant turn from its Paseo timeline cursor without a provider message id", () => {
|
||||
const failedTurn = {
|
||||
...assistantMessage("assistant-error", 2),
|
||||
timelineCursor: { epoch: "timeline-1", seq: 42 },
|
||||
timelineCursor: { epoch: "timeline-1", seq: 42, anchorSeq: 42 },
|
||||
};
|
||||
|
||||
expect(
|
||||
@@ -50,7 +50,7 @@ describe("resolveAssistantTurnForkBoundary", () => {
|
||||
it("includes the provider message id with a supported timeline cursor", () => {
|
||||
const selected = {
|
||||
...assistantMessage("assistant-1", 2, "msg-assistant-1"),
|
||||
timelineCursor: { epoch: "timeline-1", seq: 42 },
|
||||
timelineCursor: { epoch: "timeline-1", seq: 42, anchorSeq: 42 },
|
||||
};
|
||||
|
||||
expect(
|
||||
@@ -68,7 +68,7 @@ describe("resolveAssistantTurnForkBoundary", () => {
|
||||
it("falls back to the provider message id when timeline cursors are unsupported", () => {
|
||||
const selected = {
|
||||
...assistantMessage("assistant-1", 2, "msg-assistant-1"),
|
||||
timelineCursor: { epoch: "timeline-1", seq: 42 },
|
||||
timelineCursor: { epoch: "timeline-1", seq: 42, anchorSeq: 42 },
|
||||
};
|
||||
|
||||
expect(
|
||||
@@ -116,7 +116,7 @@ describe("resolveAssistantTurnForkBoundary", () => {
|
||||
it("resolves a fork boundary from the reply a plugin card replaced", () => {
|
||||
const reply = {
|
||||
...assistantMessage("assistant-1", 2, "msg-assistant-1"),
|
||||
timelineCursor: { epoch: "timeline-1", seq: 42 },
|
||||
timelineCursor: { epoch: "timeline-1", seq: 42, anchorSeq: 42 },
|
||||
};
|
||||
const card: StreamItem = {
|
||||
kind: "plugin",
|
||||
@@ -154,7 +154,7 @@ describe("resolveAssistantTurnForkBoundary", () => {
|
||||
const appended: StreamItem = {
|
||||
kind: "plugin",
|
||||
id: "plugin/card-1",
|
||||
timelineCursor: { epoch: "timeline-1", seq: 42 },
|
||||
timelineCursor: { epoch: "timeline-1", seq: 42, anchorSeq: 42 },
|
||||
timestamp: timestamp(2),
|
||||
pluginId: "plugin",
|
||||
pluginItemId: "card-1",
|
||||
|
||||
@@ -1,7 +1,13 @@
|
||||
import { getAssistantReply, type StreamItem, type TimelinePosition } from "@/types/stream";
|
||||
import { getAssistantReply, type StreamItem } from "@/types/stream";
|
||||
|
||||
/** The daemon's timeline cursor; the row's anchor stays in the client. */
|
||||
interface TimelineBoundaryCursor {
|
||||
epoch: string;
|
||||
seq: number;
|
||||
}
|
||||
|
||||
export type AssistantTurnForkBoundary =
|
||||
| { boundaryCursor: TimelinePosition; boundaryMessageId?: string }
|
||||
| { boundaryCursor: TimelineBoundaryCursor; boundaryMessageId?: string }
|
||||
| { boundaryCursor?: undefined; boundaryMessageId: string };
|
||||
|
||||
export function resolveAssistantTurnForkBoundary(input: {
|
||||
@@ -15,7 +21,7 @@ export function resolveAssistantTurnForkBoundary(input: {
|
||||
}
|
||||
if (input.supportsTimelineCursor && reply.timelineCursor) {
|
||||
return {
|
||||
boundaryCursor: reply.timelineCursor,
|
||||
boundaryCursor: { epoch: reply.timelineCursor.epoch, seq: reply.timelineCursor.seq },
|
||||
...(reply.messageId ? { boundaryMessageId: reply.messageId } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -139,7 +139,7 @@ describe("collapseTurns", () => {
|
||||
it("stands at its host's timeline position, taking a new row when that position lands", () => {
|
||||
const live = collapse([user("u1"), shell("c1"), reply("r1")]);
|
||||
expect(live.summaryRowsByHostId.get("u1")).not.toHaveProperty("timelineCursor");
|
||||
const cursor = { epoch: "epoch-1", seq: 7 };
|
||||
const cursor = { epoch: "epoch-1", seq: 7, anchorSeq: 7 };
|
||||
const placed = [{ ...user("u1"), timelineCursor: cursor }, shell("c1"), reply("r1")];
|
||||
const canonical = collapse(placed, { previousSummaryRowsByHostId: live.summaryRowsByHostId });
|
||||
expect(canonical.summaryRowsByHostId.get("u1")).not.toBe(live.summaryRowsByHostId.get("u1"));
|
||||
|
||||
@@ -101,7 +101,7 @@ function summaryRow(
|
||||
}
|
||||
|
||||
function staysVisibleWhenCollapsed(item: StreamItem): boolean {
|
||||
return isTurnTrigger(item) || item.kind === "compaction";
|
||||
return isTurnTrigger(item) || item.kind === "compaction" || item.kind === "provider_switch";
|
||||
}
|
||||
|
||||
function findLastReplyIndex(tail: StreamItem[], start: number, end: number): number {
|
||||
|
||||
@@ -159,10 +159,10 @@ const projectedReply: StreamItem = {
|
||||
id: "reply",
|
||||
messageId: "provider-reply-1",
|
||||
text: 'Done.\n\n```ui\nCard("Summary", [])\n```',
|
||||
timelineCursor: { epoch: "e1", seq: 5 },
|
||||
timelineCursor: { epoch: "e1", seq: 5, anchorSeq: 5 },
|
||||
timestamp: FRIDAY_NIGHT,
|
||||
},
|
||||
timelineCursor: { epoch: "e1", seq: 5 },
|
||||
timelineCursor: { epoch: "e1", seq: 5, anchorSeq: 5 },
|
||||
timestamp: FRIDAY_NIGHT,
|
||||
pluginId: "genui",
|
||||
pluginItemId: "reply/1",
|
||||
|
||||
@@ -37,6 +37,7 @@ import {
|
||||
ToolCall,
|
||||
TodoListCard,
|
||||
CompactionMarker,
|
||||
ProviderSwitchMarker,
|
||||
MessageOuterSpacingProvider,
|
||||
type InlinePathTarget,
|
||||
} from "@/components/message";
|
||||
@@ -57,6 +58,7 @@ import { useFileExplorerActions } from "@/hooks/use-file-explorer-actions";
|
||||
import { useLoadOlderAgentHistory } from "@/hooks/use-load-older-agent-history";
|
||||
import { resolveContentMaxWidth, useSettings } from "@/hooks/use-settings";
|
||||
import type { ToastApi } from "@/components/toast-host";
|
||||
import { isPromptInActiveSegment } from "@/components/rewind/use-rewind-capabilities";
|
||||
import { returnToTimelineTail } from "./timeline-tail-navigation";
|
||||
import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
|
||||
import { ToolCallDetailsContent } from "@/components/tool-call-details";
|
||||
@@ -408,6 +410,10 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
|
||||
const timelineEpoch = useSessionStore(
|
||||
(state) => state.sessions[resolvedServerId]?.agentTimelineCursor.get(agentId)?.epoch ?? null,
|
||||
);
|
||||
const timelineRewindSeq = useSessionStore((state) => {
|
||||
const rewind = state.sessions[resolvedServerId]?.agentTimelineLatestRewind.get(agentId);
|
||||
return rewind && rewind.epoch === timelineEpoch ? rewind.seq : null;
|
||||
});
|
||||
const isTimelineDetached = useSessionStore(
|
||||
(state) => state.sessions[resolvedServerId]?.agentTimelineHasNewer.get(agentId) === true,
|
||||
);
|
||||
@@ -711,8 +717,15 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
|
||||
|
||||
const setToolCallGroupExpanded = toolCallExpansion.setGroupExpanded;
|
||||
|
||||
const activeSegmentStartSeq = useSessionStore(
|
||||
(state) =>
|
||||
state.sessions[resolvedServerId]?.agentTimelineCursor.get(agentId)?.activeSegmentStartSeq ??
|
||||
0,
|
||||
);
|
||||
|
||||
const renderUserMessageItem = useCallback(
|
||||
(layoutItem: StreamLayoutItem, item: Extract<StreamItem, { kind: "user_message" }>) => {
|
||||
const canRewindPrompt = isPromptInActiveSegment(item.timelineCursor, activeSegmentStartSeq);
|
||||
return (
|
||||
<UserMessage
|
||||
itemId={item.id}
|
||||
@@ -724,7 +737,7 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
|
||||
images={item.images}
|
||||
attachments={item.attachments}
|
||||
timestamp={item.timestamp.getTime()}
|
||||
capabilities={context.capabilities}
|
||||
capabilities={canRewindPrompt ? context.capabilities : undefined}
|
||||
client={client}
|
||||
isFirstInGroup={layoutItem.isFirstInUserGroup}
|
||||
isLastInGroup={layoutItem.isLastInUserGroup}
|
||||
@@ -735,7 +748,14 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
|
||||
/>
|
||||
);
|
||||
},
|
||||
[context.capabilities, agentId, client, pendingClientMessageIds, resolvedServerId],
|
||||
[
|
||||
activeSegmentStartSeq,
|
||||
context.capabilities,
|
||||
agentId,
|
||||
client,
|
||||
pendingClientMessageIds,
|
||||
resolvedServerId,
|
||||
],
|
||||
);
|
||||
|
||||
const renderAssistantMessageItem = useCallback(
|
||||
@@ -949,6 +969,18 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
|
||||
/>
|
||||
);
|
||||
|
||||
case "provider_switch":
|
||||
return (
|
||||
<ProviderSwitchMarker
|
||||
serverId={resolvedServerId}
|
||||
fromProvider={item.fromProvider}
|
||||
toProvider={item.toProvider}
|
||||
fromModel={item.fromModel}
|
||||
toModel={item.toModel}
|
||||
context={item.context}
|
||||
/>
|
||||
);
|
||||
|
||||
case "plugin":
|
||||
return (
|
||||
<PluginTimelineItemView agentId={agentId} item={item} serverId={resolvedServerId} />
|
||||
@@ -1174,6 +1206,7 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
|
||||
agentId={agentId}
|
||||
serverId={resolvedServerId}
|
||||
epoch={timelineEpoch}
|
||||
rewindSeq={timelineRewindSeq}
|
||||
items={findItems}
|
||||
viewportRef={viewportRef}
|
||||
revealLoadedMessage={revealLoadedMessage}
|
||||
|
||||
@@ -75,6 +75,7 @@ export function estimateStreamItemHeight({
|
||||
case "notification":
|
||||
return 88;
|
||||
case "compaction":
|
||||
case "provider_switch":
|
||||
return 72;
|
||||
default:
|
||||
return 120;
|
||||
|
||||
@@ -79,6 +79,7 @@ import { HorizontalScrollProvider } from "@/contexts/horizontal-scroll-context";
|
||||
import { SessionProvider } from "@/contexts/session-context";
|
||||
import { SidebarCalloutProvider } from "@/contexts/sidebar-callout-context";
|
||||
import { ToastProvider } from "@/contexts/toast-context";
|
||||
import { WorkspaceTabCloseErrorToasts } from "@/workspace-tabs/close";
|
||||
import { VoiceProvider } from "@/contexts/voice-context";
|
||||
import {
|
||||
resolveStartupBlocker,
|
||||
@@ -994,6 +995,7 @@ function RootOverlayProviders({ children }: { children: ReactNode }) {
|
||||
<BottomSheetModalProvider>
|
||||
{children}
|
||||
<WindowLayoutActionsHost />
|
||||
<WorkspaceTabCloseErrorToasts />
|
||||
</BottomSheetModalProvider>
|
||||
</PortalProvider>
|
||||
</ToastProvider>
|
||||
|
||||
@@ -954,6 +954,19 @@ it("keeps table cell pipes escaped in text/plain table syntax and literal in tex
|
||||
expect(content?.html).toContain("<td>Value | detail</td>");
|
||||
});
|
||||
|
||||
it("keeps a table cell's line breaks inside its row", () => {
|
||||
const message = mountFixture();
|
||||
message.innerHTML =
|
||||
"<table><thead><tr><th>Name<br>label</th><th>Note</th></tr></thead><tbody><tr><td>first<br>second</td><td><br> stays text</td></tr></tbody></table>";
|
||||
const content = createAssistantSelectionClipboardContent(selectNodeContents(message));
|
||||
expect(content?.plainText).toBe(
|
||||
"| Name<br>label | Note |\n| --- | --- |\n| first<br>second | <br> stays text |",
|
||||
);
|
||||
expect(content?.html).toContain("<th>Name<br>\nlabel</th>");
|
||||
expect(content?.html).toContain("<td>first<br>\nsecond</td>");
|
||||
expect(content?.html).toContain("<td><br> stays text</td>");
|
||||
});
|
||||
|
||||
it("copies a workspace image path instead of its temporary display URL", () => {
|
||||
const message = mountFixture();
|
||||
const sources = JSON.stringify({ "blob:preview": "assets/chart.png" });
|
||||
|
||||
@@ -69,12 +69,13 @@ function createTurndown(flavor: "markdown" | "plain"): TurndownService {
|
||||
});
|
||||
turndown.use(gfm);
|
||||
// text/plain still carries tables as GFM syntax, so a cell's pipe stays escaped there.
|
||||
// A row is one line, so a cell's line break goes back to `<br>`.
|
||||
turndown.addRule("escapedGfmTableCell", {
|
||||
filter: ["th", "td"],
|
||||
replacement: (content, node) => {
|
||||
const index = node.parentNode ? Array.from(node.parentNode.childNodes).indexOf(node) : 0;
|
||||
const prefix = index === 0 ? "| " : " ";
|
||||
return `${prefix}${content.replace(/\|/g, "\\|")} |`;
|
||||
return `${prefix}${content.replace(/\|/g, "\\|").replace(/ *\n/g, "<br>")} |`;
|
||||
},
|
||||
});
|
||||
// A link Paseo recognized pastes as the text the reply showed. Rich paste keeps it as a
|
||||
|
||||
@@ -4,6 +4,7 @@ import type {
|
||||
CommandCenterRegistration,
|
||||
CommandCenterRegistrationOwner,
|
||||
} from "./contributions";
|
||||
import { compareText } from "@/utils/collation";
|
||||
|
||||
export interface CommandCenterRegistry {
|
||||
getSnapshot(): CommandCenterContributionSnapshot;
|
||||
@@ -28,10 +29,10 @@ function compareContributions(
|
||||
right: CommandCenterContribution,
|
||||
): number {
|
||||
if (left.groupRank !== right.groupRank) return left.groupRank - right.groupRank;
|
||||
const groupDelta = left.group.localeCompare(right.group);
|
||||
const groupDelta = compareText(left.group, right.group);
|
||||
if (groupDelta !== 0) return groupDelta;
|
||||
if (left.rank !== right.rank) return left.rank - right.rank;
|
||||
return left.id.localeCompare(right.id);
|
||||
return compareText(left.id, right.id);
|
||||
}
|
||||
|
||||
function sameContributions(
|
||||
|
||||
@@ -205,6 +205,7 @@ export function useWorkspaceCommandCenterActions(): void {
|
||||
const { overrides } = useKeyboardShortcutOverrides();
|
||||
const { gitActions, isGit, archiveWorkspace } = useGitActions({
|
||||
serverId: serverId ?? "",
|
||||
workspaceId,
|
||||
cwd: cwd ?? "",
|
||||
icons: GIT_ACTION_ICONS,
|
||||
});
|
||||
|
||||
@@ -81,6 +81,7 @@ export function ArchivedAgentCallout({
|
||||
agentId,
|
||||
isWorkspaceRestoring = false,
|
||||
}: ArchivedAgentCalloutProps) {
|
||||
const { t } = useTranslation();
|
||||
const targetKey = `${serverId}:${agentId}`;
|
||||
const toast = useToast();
|
||||
const { unarchive, isUnarchiving, canUnarchive } = useUnarchiveAgent({ serverId, agentId });
|
||||
@@ -110,7 +111,15 @@ export function ArchivedAgentCallout({
|
||||
const attemptKey = targetKey;
|
||||
setUnarchiveErrorState(null);
|
||||
try {
|
||||
await unarchive();
|
||||
await unarchive({
|
||||
onRefreshed: (refreshed) => {
|
||||
if (refreshed.historyDiverged) {
|
||||
toast.show(t("workspace.tabs.toasts.reloadedAgentHistoryDiverged"), {
|
||||
variant: "warning",
|
||||
});
|
||||
}
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
deliverUnarchiveError({
|
||||
error,
|
||||
@@ -121,7 +130,7 @@ export function ArchivedAgentCallout({
|
||||
onToastError: toast.error,
|
||||
});
|
||||
}
|
||||
}, [canUnarchive, targetKey, toast, unarchive]);
|
||||
}, [canUnarchive, t, targetKey, toast, unarchive]);
|
||||
|
||||
return (
|
||||
<KeyboardTranslateView style={styles.container}>
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { Parser } from "htmlparser2";
|
||||
import { fromMarkdown } from "mdast-util-from-markdown";
|
||||
import { gfmTableFromMarkdown } from "mdast-util-gfm-table";
|
||||
import { gfmTable } from "micromark-extension-gfm-table";
|
||||
import { decodeString } from "micromark-util-decode-string";
|
||||
import type { Nodes } from "mdast";
|
||||
|
||||
@@ -53,6 +55,8 @@ export function normalizeMarkdownHtml(source: string): string {
|
||||
} else if ("children" in node) node.children.forEach(protectCode);
|
||||
}
|
||||
protectCode(tree);
|
||||
// Only `<br>` reads these, so a source without one skips the extra parse.
|
||||
const tableRanges = /<br/i.test(source) ? collectTableRanges(source, codeRanges) : [];
|
||||
const links: (string | undefined)[] = [];
|
||||
let previousTag: { name: string; end: number } | null = null;
|
||||
const convert = (raw: string, offset: number): string => {
|
||||
@@ -84,7 +88,16 @@ export function normalizeMarkdownHtml(source: string): string {
|
||||
: /^\s*$/.test(source.slice(0, offset));
|
||||
previousTag = { name, end: offset + raw.length };
|
||||
if (EMPHASIS[name]) return EMPHASIS[name];
|
||||
const boundary = layoutBoundary(name, source, raw, offset, closing, startsAfterBoundary);
|
||||
const inTable = tableRanges.some(({ start, end }) => offset >= start && offset < end);
|
||||
const boundary = layoutBoundary(
|
||||
name,
|
||||
source,
|
||||
raw,
|
||||
offset,
|
||||
closing,
|
||||
startsAfterBoundary,
|
||||
inTable,
|
||||
);
|
||||
if (boundary !== null) return boundary;
|
||||
if (name === "a") return markdownAnchor(raw, closing, links);
|
||||
if (name === "img" && !closing) {
|
||||
@@ -167,8 +180,15 @@ function layoutBoundary(
|
||||
offset: number,
|
||||
closing: boolean,
|
||||
startsAfterBoundary: boolean,
|
||||
inTable: boolean,
|
||||
): string | null {
|
||||
if (name === "br") return closing ? "" : " \n";
|
||||
// Inside GFM table cells, emit ` \u2028 ` so row boundaries stay intact while giving flanking
|
||||
// emphasis/strikethrough delimiters and URLs/autolinks whitespace boundaries on both sides before
|
||||
// the cell-scoped parser turns ` \u2028 ` back into a `LineBreak` node.
|
||||
if (name === "br") {
|
||||
if (closing) return "";
|
||||
return inTable ? " \u2028 " : " \n";
|
||||
}
|
||||
if (name === "summary") return closing ? "**\n\n" : "**";
|
||||
if (name === "details")
|
||||
return (closing ? offset + raw.length === source.length : offset === 0) ? "" : "\n\n";
|
||||
@@ -177,3 +197,67 @@ function layoutBoundary(
|
||||
return /^<t[dh]\b/i.test(source.slice(offset + raw.length)) ? " " : "";
|
||||
return null;
|
||||
}
|
||||
|
||||
function hasNonWhitespaceAfterNewline(value: string): boolean {
|
||||
const lastNewline = value.lastIndexOf("\n");
|
||||
return /[^\s]/.test(lastNewline === -1 ? value : value.slice(lastNewline + 1));
|
||||
}
|
||||
|
||||
function isTableWrapperTag(raw: string, inCode: boolean): boolean {
|
||||
if (inCode) return false;
|
||||
if (raw.startsWith("<!--")) return true;
|
||||
const name = /^<\/?([A-Za-z][A-Za-z0-9-]*)/.exec(raw)?.[1].toLowerCase();
|
||||
return name === "summary" || name === "details" || (name !== undefined && BLOCK_TAGS.has(name));
|
||||
}
|
||||
|
||||
function collectTableRanges(
|
||||
source: string,
|
||||
codeRanges: readonly { start: number; end: number }[],
|
||||
): { start: number; end: number }[] {
|
||||
let cursor = 0;
|
||||
let codeIndex = 0;
|
||||
let lineHasPrefixText = false;
|
||||
// Advance line/code state monotonically in a single forward pass so large single-line HTML tables stay O(n)
|
||||
// while nested leading wrappers (e.g. `<details><summary>Results</summary><div>| A | B |`) follow
|
||||
// line breaks introduced by earlier masked tags.
|
||||
const tableSource = source.replace(HTML, (raw, offset: number) => {
|
||||
for (let index = cursor; index < offset; index++) {
|
||||
const code = source.charCodeAt(index);
|
||||
if (code === 10) lineHasPrefixText = false;
|
||||
else if (code !== 32 && code !== 9 && code !== 13) lineHasPrefixText = true;
|
||||
}
|
||||
cursor = offset + raw.length;
|
||||
while (codeIndex < codeRanges.length && codeRanges[codeIndex].end <= offset) codeIndex++;
|
||||
const inCode = codeIndex < codeRanges.length && offset >= codeRanges[codeIndex].start;
|
||||
if (!isTableWrapperTag(raw, inCode)) {
|
||||
if (inCode || /^<code\b/i.test(raw)) {
|
||||
if (hasNonWhitespaceAfterNewline(raw)) lineHasPrefixText = true;
|
||||
else if (raw.includes("\n")) lineHasPrefixText = false;
|
||||
} else if (raw.includes("\n")) {
|
||||
lineHasPrefixText = false;
|
||||
}
|
||||
return raw;
|
||||
}
|
||||
const blanked = raw.replace(/[^\n]/g, " ");
|
||||
if (!lineHasPrefixText && blanked.length > 0 && !blanked.endsWith("\n")) {
|
||||
return `${blanked.slice(0, -1)}\n`;
|
||||
}
|
||||
if (blanked.includes("\n")) lineHasPrefixText = false;
|
||||
return blanked;
|
||||
});
|
||||
const tableRanges: { start: number; end: number }[] = [];
|
||||
function findTables(node: Nodes) {
|
||||
if (node.type === "table" && node.position) {
|
||||
const start = node.position.start.offset;
|
||||
const end = node.position.end.offset;
|
||||
if (start !== undefined && end !== undefined) tableRanges.push({ start, end });
|
||||
} else if ("children" in node) node.children.forEach(findTables);
|
||||
}
|
||||
findTables(
|
||||
fromMarkdown(tableSource, {
|
||||
extensions: [{ disable: { null: ["htmlFlow", "htmlText"] } }, gfmTable()],
|
||||
mdastExtensions: [gfmTableFromMarkdown()],
|
||||
}),
|
||||
);
|
||||
return tableRanges;
|
||||
}
|
||||
|
||||
@@ -688,6 +688,32 @@ it("keeps workspace-relative hover titles on explicit absolute file links", () =
|
||||
);
|
||||
});
|
||||
|
||||
it.each([
|
||||
[
|
||||
"an angle-bracket destination",
|
||||
"[Open](</repo/src/file.ts>)",
|
||||
'[Open](</repo/src/file.ts> "src/file.ts")',
|
||||
],
|
||||
["an escaped slash", "[Open](\\/repo/src/file.ts)", '[Open](\\/repo/src/file.ts "src/file.ts")'],
|
||||
[
|
||||
"an escaped separator",
|
||||
"[Open](/repo\\/src/file.ts)",
|
||||
'[Open](/repo\\/src/file.ts "src/file.ts")',
|
||||
],
|
||||
[
|
||||
"a character reference",
|
||||
"[Open](/repo/src/file.ts)",
|
||||
'[Open](/repo/src/file.ts "src/file.ts")',
|
||||
],
|
||||
])("keeps the workspace hover title on a link written with %s", (_form, source, rendered) => {
|
||||
expect(prepareMarkdownSource(source, "/repo").render()).toBe(rendered);
|
||||
});
|
||||
|
||||
it("leaves links outside the workspace as written", () => {
|
||||
const source = "[Docs](https://example.com/repo/x) and [Other](/repository/x) near /repo/x";
|
||||
expect(prepareMarkdownSource(source, "/repo").render()).toBe(source);
|
||||
});
|
||||
|
||||
it.each(['""', "''", "()"])("preserves an authored empty link title: %s", (title) => {
|
||||
const source = `[Open](/repo/file.ts ${title})`;
|
||||
expect(prepareMarkdownSource(source, "/repo").render()).toBe(source);
|
||||
@@ -812,6 +838,188 @@ describe("GitHub comment HTML normalization", () => {
|
||||
])("normalizes %s without changing code", (source, expected) => {
|
||||
expect(prepareMarkdownSource(source).render()).toBe(expected);
|
||||
});
|
||||
|
||||
it("keeps <br> line breaks inside GFM table headers and cells within a single row", async () => {
|
||||
const source = [
|
||||
"| Col<br>One | Col<br />Two |",
|
||||
"| --- | --- |",
|
||||
"| First<br>Second<br/>Third | Plain |",
|
||||
].join("\n");
|
||||
const tree = await parseMarkdown(prepareMarkdownSource(source).render(), {
|
||||
hardSoftBreaks: true,
|
||||
latexMath: false,
|
||||
});
|
||||
const table = tree.children?.find((node) => node.type === "Table");
|
||||
expect(table).toBeDefined();
|
||||
const headRows = table?.children?.find((node) => node.type === "TableHead")?.children ?? [];
|
||||
const bodyRows = table?.children?.find((node) => node.type === "TableBody")?.children ?? [];
|
||||
expect(headRows).toHaveLength(1);
|
||||
expect(bodyRows).toHaveLength(1);
|
||||
const [headCells, bodyCells] = [headRows[0].children ?? [], bodyRows[0].children ?? []];
|
||||
expect(headCells[0].children).toEqual([
|
||||
{ type: "Text", content: "Col" },
|
||||
{ type: "LineBreak" },
|
||||
{ type: "Text", content: "One" },
|
||||
]);
|
||||
expect(headCells[1].children).toEqual([
|
||||
{ type: "Text", content: "Col" },
|
||||
{ type: "LineBreak" },
|
||||
{ type: "Text", content: "Two" },
|
||||
]);
|
||||
expect(bodyCells[0].children).toEqual([
|
||||
{ type: "Text", content: "First" },
|
||||
{ type: "LineBreak" },
|
||||
{ type: "Text", content: "Second" },
|
||||
{ type: "LineBreak" },
|
||||
{ type: "Text", content: "Third" },
|
||||
]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
"<details><summary>Results</summary>\n\n| A | B |\n| - | - |\n| 1<br>2 | 3 |\n</details>",
|
||||
"<details><summary>Results</summary>| A | B |\n| - | - |\n| 1<br>2 | 3 |</details>",
|
||||
"<details><summary>Results</summary><div>| A | B |\n| - | - |\n| 1<br>2 | 3 |</div></details>",
|
||||
"<span></span><div>| A | B |\n| - | - |\n| 1<br>2 | 3 |</div>",
|
||||
])("keeps table <br> inside wrapped table cells: %s", async (source) => {
|
||||
const tree = await parseMarkdown(prepareMarkdownSource(source).render(), {
|
||||
hardSoftBreaks: true,
|
||||
latexMath: false,
|
||||
});
|
||||
const table = tree.children?.find((node) => node.type === "Table");
|
||||
expect(table).toBeDefined();
|
||||
const body = table?.children?.find((node) => node.type === "TableBody");
|
||||
expect(body?.children).toHaveLength(1);
|
||||
expect(body?.children?.[0]?.children?.[0]?.children).toEqual([
|
||||
{ type: "Text", content: "1" },
|
||||
{ type: "LineBreak" },
|
||||
{ type: "Text", content: "2" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("recognizes file paths and URLs separated by <br> inside table cells", async () => {
|
||||
const source = [
|
||||
"| Paths | Mixed | URLs |",
|
||||
"| --- | --- | --- |",
|
||||
"| src/first.ts<br>src/second.ts | https://example.com/first<br>src/second.ts | https://example.com/first<br>https://example.com/second |",
|
||||
].join("\n");
|
||||
const prepared = prepareMarkdownSource(source);
|
||||
const linked = recognizeTextLinks(
|
||||
await parseMarkdown(prepared.render(), {
|
||||
hardSoftBreaks: true,
|
||||
latexMath: false,
|
||||
}),
|
||||
prepared.linkRecognition.text,
|
||||
prepared.linkRecognition.inlineCode,
|
||||
);
|
||||
const table = linked.children?.find((node) => node.type === "Table");
|
||||
const row = table?.children?.find((node) => node.type === "TableBody")?.children?.[0];
|
||||
expect(row?.children?.[0]?.children).toEqual([
|
||||
{
|
||||
type: "Link",
|
||||
attributes: { url: "src/first.ts", recognizedLink: "true" },
|
||||
children: [{ type: "Text", content: "src/first.ts" }],
|
||||
},
|
||||
{ type: "LineBreak" },
|
||||
{
|
||||
type: "Link",
|
||||
attributes: { url: "src/second.ts", recognizedLink: "true" },
|
||||
children: [{ type: "Text", content: "src/second.ts" }],
|
||||
},
|
||||
]);
|
||||
expect(row?.children?.[1]?.children).toEqual([
|
||||
{
|
||||
type: "Link",
|
||||
attributes: { url: "https://example.com/first" },
|
||||
children: [{ type: "Text", content: "https://example.com/first" }],
|
||||
},
|
||||
{ type: "LineBreak" },
|
||||
{
|
||||
type: "Link",
|
||||
attributes: { url: "src/second.ts", recognizedLink: "true" },
|
||||
children: [{ type: "Text", content: "src/second.ts" }],
|
||||
},
|
||||
]);
|
||||
expect(row?.children?.[2]?.children).toEqual([
|
||||
{
|
||||
type: "Link",
|
||||
attributes: { url: "https://example.com/first" },
|
||||
children: [{ type: "Text", content: "https://example.com/first" }],
|
||||
},
|
||||
{ type: "LineBreak" },
|
||||
{
|
||||
type: "Link",
|
||||
attributes: { url: "https://example.com/second" },
|
||||
children: [{ type: "Text", content: "https://example.com/second" }],
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps literal U+2028 outside tables, inline code, and escaped <br> untouched", async () => {
|
||||
const source = [
|
||||
"before\u2028after `before\u2028after`",
|
||||
"",
|
||||
"| Inline | Escaped | Entity |",
|
||||
"| --- | --- | --- |",
|
||||
"| `before\u2028after` | \\<br> | <br> `<br>` |",
|
||||
].join("\n");
|
||||
const tree = await parseMarkdown(prepareMarkdownSource(source).render(), {
|
||||
hardSoftBreaks: true,
|
||||
latexMath: false,
|
||||
});
|
||||
const collectLineBreaks = (node: ASTNode): number =>
|
||||
(node.type === "LineBreak" ? 1 : 0) +
|
||||
(node.children?.reduce((count, child) => count + collectLineBreaks(child), 0) ?? 0);
|
||||
expect(collectLineBreaks(tree)).toBe(0);
|
||||
|
||||
const paragraph = tree.children?.find((node) => node.type === "Paragraph");
|
||||
expect(paragraph?.children).toEqual([
|
||||
{ type: "Text", content: "before\u2028after " },
|
||||
{ type: "Code", children: [{ type: "Text", content: "before\u2028after" }] },
|
||||
]);
|
||||
|
||||
const row = tree.children
|
||||
?.find((node) => node.type === "Table")
|
||||
?.children?.find((node) => node.type === "TableBody")?.children?.[0];
|
||||
expect(row?.children?.[0]?.children).toEqual([
|
||||
{ type: "Code", children: [{ type: "Text", content: "before\u2028after" }] },
|
||||
]);
|
||||
expect(row?.children?.[1]?.children).toEqual([{ type: "Text", content: "<br>" }]);
|
||||
expect(row?.children?.[2]?.children).toEqual([
|
||||
{ type: "Text", content: "<br> " },
|
||||
{ type: "Code", children: [{ type: "Text", content: "<br>" }] },
|
||||
]);
|
||||
expect(prepareMarkdownSource("<table><tr><td>a<br>b</td></tr></table>").render()).toBe(
|
||||
"a \nb",
|
||||
);
|
||||
});
|
||||
|
||||
it("preserves emphasis and strong delimiters adjacent to <br> inside table cells", async () => {
|
||||
const source = [
|
||||
"| A | B |",
|
||||
"| --- | --- |",
|
||||
"| **方案 B(最猛 · 推荐)**<br>阶梯首充 | **`基准 → 30% → 50%`**<br>*(复购:基准)* |",
|
||||
].join("\n");
|
||||
const tree = await parseMarkdown(prepareMarkdownSource(source).render(), {
|
||||
hardSoftBreaks: true,
|
||||
latexMath: false,
|
||||
});
|
||||
const row = tree.children
|
||||
?.find((node) => node.type === "Table")
|
||||
?.children?.find((node) => node.type === "TableBody")?.children?.[0];
|
||||
expect(row?.children?.[0]?.children).toEqual([
|
||||
{ type: "Strong", children: [{ type: "Text", content: "方案 B(最猛 · 推荐)" }] },
|
||||
{ type: "LineBreak" },
|
||||
{ type: "Text", content: "阶梯首充" },
|
||||
]);
|
||||
expect(row?.children?.[1]?.children).toEqual([
|
||||
{
|
||||
type: "Strong",
|
||||
children: [{ type: "Code", children: [{ type: "Text", content: "基准 → 30% → 50%" }] }],
|
||||
},
|
||||
{ type: "LineBreak" },
|
||||
{ type: "Emphasis", children: [{ type: "Text", content: "(复购:基准)" }] },
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
it("preserves backslashes and decodes entities inside HTML code", () => {
|
||||
|
||||
@@ -150,6 +150,13 @@ function workspaceHoverTitle(link: Link, markup: string, workspaceRoot?: string)
|
||||
return link.url.slice(workspaceRoot.length + 1);
|
||||
}
|
||||
|
||||
// Only a link into the workspace gets an edit, its hover title. A link's URL differs from its
|
||||
// source text only by backslash escapes and character references, and `&` already takes the parse.
|
||||
function mayLinkIntoWorkspace(source: string, workspaceRoot?: string): boolean {
|
||||
if (!workspaceRoot || !source.includes("](")) return false;
|
||||
return source.includes(`${workspaceRoot}/`) || source.includes("\\");
|
||||
}
|
||||
|
||||
/** Preserve source spelling; adapt workspace images, spoiler delimiters, and entity text. */
|
||||
export function prepareMarkdownSource(
|
||||
source: string,
|
||||
@@ -191,7 +198,7 @@ export function prepareMarkdownSource(
|
||||
!/^[\t >]*[^\t >\r\n][^\r\n]*(?:\r\n|\r|\n)[^\r\n]+(?:\r\n|\r|\n)(?=[\t >:|-]*\|)[\t >|]*:?-[-\t :|]*$/m.test(
|
||||
source,
|
||||
) &&
|
||||
!(workspaceRoot && source.includes("](")) &&
|
||||
!mayLinkIntoWorkspace(source, workspaceRoot) &&
|
||||
!(external && /\]|<[a-z]+:/i.test(source))
|
||||
) {
|
||||
return { images, ...metadata, render: () => source };
|
||||
|
||||
@@ -21,9 +21,11 @@ import {
|
||||
type RewindMode,
|
||||
} from "@/components/rewind";
|
||||
import { TaskListRow } from "@/components/task-list-row";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { LoadingSpinner } from "@/components/ui/loading-spinner";
|
||||
import { useIsCompactFormFactor } from "@/constants/layout";
|
||||
import { isNative, isWeb } from "@/constants/platform";
|
||||
import { useProvidersSnapshot } from "@/hooks/use-providers-snapshot";
|
||||
import { useRevealedText, type MarkdownPhase } from "@/hooks/use-revealed-text";
|
||||
import { ICON_SIZE, type Theme } from "@/styles/theme";
|
||||
import { inlineUnistylesStyle } from "@/styles/unistyles-inline-style";
|
||||
@@ -47,13 +49,17 @@ import type { AgentMessage } from "@getpaseo/protocol/agent-message";
|
||||
import type {
|
||||
AgentCapabilityFlags,
|
||||
AgentMetric,
|
||||
AgentProvider,
|
||||
ProviderSwitchContextSummary,
|
||||
ToolCallDetail,
|
||||
} from "@getpaseo/protocol/agent-types";
|
||||
import type { AgentAttachment } from "@getpaseo/protocol/messages";
|
||||
import MaskedView from "@react-native-masked-view/masked-view";
|
||||
import {
|
||||
ArrowRightLeft,
|
||||
Check,
|
||||
CheckSquare,
|
||||
ChevronDown,
|
||||
ChevronRight,
|
||||
CircleDot,
|
||||
Copy,
|
||||
@@ -1575,6 +1581,206 @@ export const CompactionMarker = memo(function CompactionMarker({
|
||||
);
|
||||
});
|
||||
|
||||
const StyledSwitchIcon = withUnistyles(ArrowRightLeft, (theme) => ({
|
||||
color: theme.colors.foregroundMuted,
|
||||
}));
|
||||
const StyledChevronDownIcon = withUnistyles(ChevronDown, (theme) => ({
|
||||
color: theme.colors.foregroundMuted,
|
||||
}));
|
||||
const StyledChevronRightIcon = withUnistyles(ChevronRight, (theme) => ({
|
||||
color: theme.colors.foregroundMuted,
|
||||
}));
|
||||
|
||||
export interface ProviderSwitchMarkerProps {
|
||||
serverId?: string | null;
|
||||
fromProvider: AgentProvider;
|
||||
toProvider: AgentProvider;
|
||||
fromModel?: string | null;
|
||||
toModel?: string | null;
|
||||
context?: ProviderSwitchContextSummary;
|
||||
}
|
||||
|
||||
const providerSwitchStylesheet = StyleSheet.create((theme) => ({
|
||||
wrapper: {
|
||||
paddingVertical: theme.spacing[2],
|
||||
gap: theme.spacing[2],
|
||||
},
|
||||
row: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: theme.spacing[2],
|
||||
width: "100%",
|
||||
},
|
||||
line: {
|
||||
flex: 1,
|
||||
minWidth: 12,
|
||||
height: 1,
|
||||
backgroundColor: theme.colors.border,
|
||||
},
|
||||
triggerButton: {
|
||||
flexShrink: 1,
|
||||
minWidth: 0,
|
||||
maxWidth: "85%",
|
||||
},
|
||||
triggerContent: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
flexShrink: 1,
|
||||
minWidth: 0,
|
||||
maxWidth: "100%",
|
||||
gap: theme.spacing[1.5],
|
||||
},
|
||||
triggerText: {
|
||||
flexShrink: 1,
|
||||
minWidth: 0,
|
||||
fontFamily: theme.fontFamily.ui,
|
||||
fontSize: 13,
|
||||
color: theme.colors.foregroundMuted,
|
||||
},
|
||||
chevronSlot: {
|
||||
width: 12,
|
||||
height: 12,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
},
|
||||
detailsCard: {
|
||||
alignSelf: "center",
|
||||
maxWidth: 480,
|
||||
width: "100%",
|
||||
paddingVertical: theme.spacing[2],
|
||||
paddingHorizontal: theme.spacing[3],
|
||||
borderRadius: theme.borderRadius.md,
|
||||
borderWidth: 1,
|
||||
borderColor: theme.colors.border,
|
||||
backgroundColor: theme.colors.surface0,
|
||||
gap: theme.spacing[1],
|
||||
},
|
||||
detailRow: {
|
||||
fontFamily: theme.fontFamily.ui,
|
||||
fontSize: 12,
|
||||
color: theme.colors.foregroundMuted,
|
||||
},
|
||||
}));
|
||||
|
||||
function resolveProviderSwitchLabel(
|
||||
provider: string,
|
||||
entries: ReturnType<typeof useProvidersSnapshot>["entries"],
|
||||
): string {
|
||||
return entries?.find((entry) => entry.provider === provider)?.label ?? provider;
|
||||
}
|
||||
|
||||
function resolveProviderSwitchModelLabel(
|
||||
provider: string,
|
||||
modelId: string | null | undefined,
|
||||
entries: ReturnType<typeof useProvidersSnapshot>["entries"],
|
||||
): string | null {
|
||||
if (!modelId) return null;
|
||||
const entry = entries?.find((candidate) => candidate.provider === provider);
|
||||
return entry?.models?.find((model) => model.id === modelId)?.label ?? modelId;
|
||||
}
|
||||
|
||||
function formatProviderSwitchEndpoint(providerLabel: string, modelLabel: string | null): string {
|
||||
return modelLabel ? `${providerLabel} (${modelLabel})` : providerLabel;
|
||||
}
|
||||
|
||||
export const ProviderSwitchMarker = memo(function ProviderSwitchMarker({
|
||||
serverId = null,
|
||||
fromProvider,
|
||||
toProvider,
|
||||
fromModel,
|
||||
toModel,
|
||||
context,
|
||||
}: ProviderSwitchMarkerProps) {
|
||||
const { t } = useTranslation();
|
||||
const { entries: providerEntries } = useProvidersSnapshot(serverId);
|
||||
const [expanded, setExpanded] = useState(false);
|
||||
const handleToggle = useCallback(() => setExpanded((prev) => !prev), []);
|
||||
|
||||
const fromLabel = resolveProviderSwitchLabel(fromProvider, providerEntries);
|
||||
const toLabel = resolveProviderSwitchLabel(toProvider, providerEntries);
|
||||
const fromModelLabel = resolveProviderSwitchModelLabel(fromProvider, fromModel, providerEntries);
|
||||
const toModelLabel = resolveProviderSwitchModelLabel(toProvider, toModel, providerEntries);
|
||||
|
||||
const title = t("message.providerSwitch.switched", {
|
||||
from: fromLabel,
|
||||
to: toLabel,
|
||||
});
|
||||
const contextLine = context
|
||||
? t("message.providerSwitch.contextSummary", {
|
||||
count: context.includedItems,
|
||||
chars: context.charCount.toLocaleString(),
|
||||
budget: context.budgetChars.toLocaleString(),
|
||||
})
|
||||
: null;
|
||||
const reasonsLine =
|
||||
context?.truncated && context.omittedReasons?.length
|
||||
? t("message.providerSwitch.trimmed", {
|
||||
reasons: context.omittedReasons
|
||||
.map((reason) => {
|
||||
if (reason === "tail_window_limit") {
|
||||
return t("message.providerSwitch.reasonTailWindow");
|
||||
}
|
||||
if (reason === "char_budget") {
|
||||
return t("message.providerSwitch.reasonCharBudget");
|
||||
}
|
||||
return reason;
|
||||
})
|
||||
.join(", "),
|
||||
})
|
||||
: null;
|
||||
|
||||
let chevronIcon: React.ReactNode = null;
|
||||
if (context) {
|
||||
chevronIcon = expanded ? (
|
||||
<StyledChevronDownIcon size={12} />
|
||||
) : (
|
||||
<StyledChevronRightIcon size={12} />
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<View style={providerSwitchStylesheet.wrapper} testID="provider-switch-marker">
|
||||
<View style={providerSwitchStylesheet.row}>
|
||||
<View style={providerSwitchStylesheet.line} />
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
style={providerSwitchStylesheet.triggerButton}
|
||||
onPress={context ? handleToggle : undefined}
|
||||
accessibilityLabel={title}
|
||||
testID="provider-switch-marker-toggle"
|
||||
>
|
||||
<View style={providerSwitchStylesheet.triggerContent}>
|
||||
<StyledSwitchIcon size={12} />
|
||||
<Text
|
||||
style={providerSwitchStylesheet.triggerText}
|
||||
numberOfLines={1}
|
||||
ellipsizeMode="tail"
|
||||
>
|
||||
{title}
|
||||
</Text>
|
||||
<View style={providerSwitchStylesheet.chevronSlot}>{chevronIcon}</View>
|
||||
</View>
|
||||
</Button>
|
||||
<View style={providerSwitchStylesheet.line} />
|
||||
</View>
|
||||
{expanded && context ? (
|
||||
<View style={providerSwitchStylesheet.detailsCard} testID="provider-switch-marker-details">
|
||||
<Text style={providerSwitchStylesheet.detailRow}>
|
||||
{`${formatProviderSwitchEndpoint(fromLabel, fromModelLabel)} → ${formatProviderSwitchEndpoint(toLabel, toModelLabel)}`}
|
||||
</Text>
|
||||
{contextLine ? (
|
||||
<Text style={providerSwitchStylesheet.detailRow}>{contextLine}</Text>
|
||||
) : null}
|
||||
{reasonsLine ? (
|
||||
<Text style={providerSwitchStylesheet.detailRow}>{reasonsLine}</Text>
|
||||
) : null}
|
||||
</View>
|
||||
) : null}
|
||||
</View>
|
||||
);
|
||||
});
|
||||
|
||||
interface TodoListCardProps {
|
||||
items: TodoEntry[];
|
||||
activity: TaskActivity;
|
||||
|
||||
@@ -11,11 +11,6 @@ describe("pairing target password", () => {
|
||||
expect(target.changeUrl(second)).toBe(false);
|
||||
});
|
||||
|
||||
it("clears the direct form credential when its advanced URI changes to a relay target", () => {
|
||||
const target = new PairingTargetTracker("", true);
|
||||
expect(target.changeUrl("relay://relay.example:443/srv_new?key=BBBB&ssl=true")).toBe(true);
|
||||
});
|
||||
|
||||
it("keeps the password when a relay URI receives harmless whitespace", () => {
|
||||
const uri = "relay://relay.example:443/srv_a?key=AAAA&ssl=true";
|
||||
const target = new PairingTargetTracker(uri);
|
||||
|
||||
@@ -19,8 +19,8 @@ function pairingTarget(url: string): string | null {
|
||||
export class PairingTargetTracker {
|
||||
private currentTarget: string | null;
|
||||
|
||||
constructor(initialUrl = "", startsFromDirectForm = false) {
|
||||
this.currentTarget = pairingTarget(initialUrl) ?? (startsFromDirectForm ? "direct-form" : null);
|
||||
constructor(initialUrl = "") {
|
||||
this.currentTarget = pairingTarget(initialUrl);
|
||||
}
|
||||
|
||||
changeUrl(nextUrl: string): boolean {
|
||||
|
||||
@@ -10,7 +10,11 @@ import { useToast } from "@/contexts/toast-context";
|
||||
import type { AgentScreenReadySyncState } from "@/hooks/use-agent-screen-state-machine";
|
||||
import { selectAgentTimelineState, useSessionStore } from "@/stores/session-store";
|
||||
import { useRewindAgentMutation } from "./use-rewind-agent-mutation";
|
||||
import { isRewindableMessage, useRewindMenuItems } from "./use-rewind-capabilities";
|
||||
import {
|
||||
isPromptInActiveSegment,
|
||||
isRewindableMessage,
|
||||
useRewindMenuItems,
|
||||
} from "./use-rewind-capabilities";
|
||||
|
||||
export function RewindCommandCenterRegistration({
|
||||
serverId,
|
||||
@@ -42,10 +46,16 @@ export function RewindCommandCenterRegistration({
|
||||
if (timeline.status !== "synced" || timeline.newer === "available") {
|
||||
return undefined;
|
||||
}
|
||||
return (
|
||||
const candidate =
|
||||
session.agentStreamHead.get(agentId)?.findLast((item) => item.kind === "user_message") ??
|
||||
timeline.items.findLast((item) => item.kind === "user_message")
|
||||
);
|
||||
timeline.items.findLast((item) => item.kind === "user_message");
|
||||
if (
|
||||
!candidate ||
|
||||
!isPromptInActiveSegment(candidate.timelineCursor, timeline.range?.activeSegmentStartSeq)
|
||||
) {
|
||||
return undefined;
|
||||
}
|
||||
return candidate;
|
||||
});
|
||||
const { rewindAgent, isPending } = useRewindAgentMutation({
|
||||
serverId,
|
||||
|
||||
@@ -9,6 +9,7 @@ import { useRewindComposerRestore } from "./composer-restore";
|
||||
import { useSessionStore } from "@/stores/session-store";
|
||||
import { shouldRestoreComposerForRewindMode } from "./rewind-mode";
|
||||
import { getHostRuntimeStore } from "@/runtime/host-runtime";
|
||||
import { hostSupportsFeature } from "@/runtime/host-features";
|
||||
|
||||
interface UseRewindAgentMutationInput {
|
||||
serverId?: string;
|
||||
@@ -42,7 +43,16 @@ export function useRewindAgentMutation(input: UseRewindAgentMutationInput): {
|
||||
throw new Error(t("common.errors.daemonClientUnavailable"));
|
||||
}
|
||||
await input.client.rewindAgent(input.agentId, input.messageId, mode);
|
||||
if (mode !== "files") {
|
||||
// COMPAT(timelineRewindOperations): added in v0.18.0, remove after 2027-05-25. A daemon with
|
||||
// the feature delivers the rewind on the live timeline; an older one replaced the timeline
|
||||
// and this client has to read it again.
|
||||
const appliesLive =
|
||||
input.serverId !== undefined &&
|
||||
hostSupportsFeature(
|
||||
useSessionStore.getState().sessions[input.serverId]?.serverInfo,
|
||||
"timelineRewindOperations",
|
||||
);
|
||||
if (mode !== "files" && !appliesLive) {
|
||||
const cursor = input.serverId
|
||||
? useSessionStore
|
||||
.getState()
|
||||
|
||||
@@ -26,6 +26,20 @@ export function isRewindableMessage(messageId: string | undefined, text: string)
|
||||
return Boolean(messageId) && text.trim().length > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a user prompt belongs to the active provider segment (after the latest provider switch).
|
||||
* Prompts from earlier provider segments cannot be rewound.
|
||||
*/
|
||||
export function isPromptInActiveSegment(
|
||||
timelineCursor: { anchorSeq?: number; seq?: number } | undefined,
|
||||
activeSegmentStartSeq: number | undefined,
|
||||
): boolean {
|
||||
if (!activeSegmentStartSeq || activeSegmentStartSeq <= 0) return true;
|
||||
const anchor = timelineCursor?.anchorSeq ?? timelineCursor?.seq;
|
||||
if (anchor === undefined) return true;
|
||||
return anchor > activeSegmentStartSeq;
|
||||
}
|
||||
|
||||
export function resolveRewindMenuItems(
|
||||
capabilities:
|
||||
| Pick<
|
||||
|
||||
@@ -54,6 +54,8 @@ import type { WorkspaceTabDescriptor } from "@/screens/workspace/workspace-tabs-
|
||||
import {
|
||||
collectAllPanes,
|
||||
createDefaultLayout,
|
||||
resolveGroupSizes,
|
||||
resolveMainSplitTree,
|
||||
selectExplorerSidebarPaneId,
|
||||
useWorkspaceLayoutStore,
|
||||
type SplitNode,
|
||||
@@ -80,7 +82,7 @@ interface SplitContainerProps {
|
||||
uiTabs: WorkspaceTab[];
|
||||
hoveredCloseTabKey: string | null;
|
||||
setHoveredCloseTabKey: Dispatch<SetStateAction<string | null>>;
|
||||
closingTabIds: Set<string>;
|
||||
closingTabIds: ReadonlySet<string>;
|
||||
onNavigateTab: (tabId: string) => void;
|
||||
onCloseTab: (tabId: string) => Promise<void> | void;
|
||||
onCopyResumeCommand: (agentId: string) => Promise<void> | void;
|
||||
@@ -205,7 +207,7 @@ export function SplitContainer({
|
||||
);
|
||||
|
||||
const mainRoot = useMemo(
|
||||
() => removePaneFromSplitTree(layout.root, explorerSidebarPaneId),
|
||||
() => resolveMainSplitTree(layout.root, explorerSidebarPaneId),
|
||||
[layout.root, explorerSidebarPaneId],
|
||||
);
|
||||
const workspaceHasMultiplePanes = Boolean(mainRoot && hasMultipleVisiblePanes(mainRoot));
|
||||
@@ -459,11 +461,10 @@ function SplitNodeView({
|
||||
);
|
||||
const groupChildren = node.kind === "group" ? node.group.children : EMPTY_SPLIT_NODES;
|
||||
// Dragged sizes live per group id, apart from the layout tree, and a group keeps its id when
|
||||
// panes are added or removed. They only apply while they still have one entry per child;
|
||||
// otherwise the dividers past the end of the list could not move.
|
||||
const layoutGroupSizes = node.kind === "group" ? node.group.sizes : EMPTY_SPLIT_SIZES;
|
||||
// panes are added or removed. A list of the wrong length would leave the dividers past its end
|
||||
// unable to move.
|
||||
const groupSizes =
|
||||
storedGroupSizes?.length === groupChildren.length ? storedGroupSizes : layoutGroupSizes;
|
||||
node.kind === "group" ? resolveGroupSizes(node.group, storedGroupSizes) : EMPTY_SPLIT_SIZES;
|
||||
const visibleFlex = useMemo(
|
||||
() => resolveVisibleGroupFlex(groupChildren, groupSizes, maximizedPaneId),
|
||||
[groupChildren, groupSizes, maximizedPaneId],
|
||||
@@ -910,34 +911,6 @@ function wrapRootPaneForStableMount(node: SplitNode): SplitNode {
|
||||
};
|
||||
}
|
||||
|
||||
function removePaneFromSplitTree(node: SplitNode, paneId: string | null): SplitNode | null {
|
||||
if (!paneId) {
|
||||
return node;
|
||||
}
|
||||
if (node.kind === "pane") {
|
||||
return node.pane.id === paneId ? null : node;
|
||||
}
|
||||
|
||||
const children = node.group.children.flatMap((child) => {
|
||||
const nextChild = removePaneFromSplitTree(child, paneId);
|
||||
return nextChild ? [nextChild] : [];
|
||||
});
|
||||
if (children.length === 0) {
|
||||
return null;
|
||||
}
|
||||
if (children.length === 1) {
|
||||
return children[0] ?? null;
|
||||
}
|
||||
return {
|
||||
kind: "group",
|
||||
group: {
|
||||
...node.group,
|
||||
children,
|
||||
sizes: children.map(() => 1 / children.length),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
workspaceShell: {
|
||||
flex: 1,
|
||||
|
||||
@@ -2,6 +2,7 @@ import {
|
||||
BottomSheetModal as GorhomBottomSheetModal,
|
||||
type BottomSheetModalProps,
|
||||
type BottomSheetBackdropProps,
|
||||
useBottomSheetInternal,
|
||||
} from "@gorhom/bottom-sheet";
|
||||
import React from "react";
|
||||
import {
|
||||
@@ -25,6 +26,7 @@ import {
|
||||
type AttachSheetContentDrag,
|
||||
type SheetContentDragGesture,
|
||||
} from "@/components/ui/bottom-sheet-scope";
|
||||
import { runOnJS, useAnimatedReaction, useSharedValue } from "react-native-reanimated";
|
||||
import { SheetBackdrop } from "./sheet-backdrop";
|
||||
|
||||
type GorhomBottomSheetModalMethods = ElementRef<typeof GorhomBottomSheetModal>;
|
||||
@@ -56,7 +58,7 @@ type IsolatedBottomSheetModalProps = Omit<
|
||||
/**
|
||||
* Whether closing (drag, backdrop, Back) also dismisses, which unmounts the content. Default
|
||||
* true: the owner hears `onDismiss` and drops its state. Pass `false` for a sheet whose close the
|
||||
* owner may veto: it parks at index -1 with its content mounted, the owner hears `onChange(-1)`,
|
||||
* owner may veto: it parks at index -1 with its content mounted, the owner hears `onClosed`,
|
||||
* and either snaps it back or unmounts it, which dismisses it from the stack.
|
||||
*/
|
||||
enableDismissOnClose?: boolean;
|
||||
@@ -74,6 +76,15 @@ type IsolatedBottomSheetModalProps = Omit<
|
||||
* inside the sheet and it throws on device only.
|
||||
*/
|
||||
contextBridge: ContextBridge | null;
|
||||
/**
|
||||
* Runs when a close animation settles at the closed detent, whoever started it.
|
||||
*
|
||||
* Gorhom reports that through `onChange(-1)`, but skips `onChange` when its index bookkeeping
|
||||
* already reads -1. An interrupted mount animation leaves it there, so the next close ends where
|
||||
* it began and the owner never hears about it. Watch this signal, not `onChange`, when a close
|
||||
* the owner may veto still has to reach the owner.
|
||||
*/
|
||||
onClosed?: () => void;
|
||||
};
|
||||
|
||||
export type IsolatedBottomSheetModalRef = GorhomBottomSheetModalMethods;
|
||||
@@ -105,6 +116,7 @@ export const IsolatedBottomSheetModal = forwardRef<
|
||||
contextBridge,
|
||||
backdropOpacity,
|
||||
enableDismissOnClose = true,
|
||||
onClosed,
|
||||
waitFor,
|
||||
simultaneousHandlers,
|
||||
...bottomSheetProps
|
||||
@@ -151,6 +163,7 @@ export const IsolatedBottomSheetModal = forwardRef<
|
||||
simultaneousHandlers={contentDragHandlers.simultaneousHandlers}
|
||||
>
|
||||
<BottomSheetScope attachContentDrag={attachContentDrag}>
|
||||
{onClosed ? <SheetCloseSignal onClosed={onClosed} /> : null}
|
||||
{contextBridge ? contextBridge(children) : children}
|
||||
</BottomSheetScope>
|
||||
</GorhomBottomSheetModal>
|
||||
@@ -159,6 +172,43 @@ export const IsolatedBottomSheetModal = forwardRef<
|
||||
return modal;
|
||||
});
|
||||
|
||||
/**
|
||||
* Reports a close animation that settles at the closed detent — the signal Gorhom only routes
|
||||
* through `onChange(-1)`, which it drops when the sheet's current index already reads -1.
|
||||
*
|
||||
* `animatedAnimationState.nextIndex` is -1 for the whole close animation and undefined once it
|
||||
* completes. The settled position then tells a real close from a spring back and an interruption.
|
||||
*/
|
||||
function SheetCloseSignal({ onClosed }: { onClosed: () => void }) {
|
||||
const { animatedAnimationState, animatedDetentsState, animatedPosition } =
|
||||
useBottomSheetInternal();
|
||||
const closing = useSharedValue(false);
|
||||
useAnimatedReaction(
|
||||
() => {
|
||||
const { nextIndex } = animatedAnimationState.get();
|
||||
if (nextIndex === -1) return -1;
|
||||
return nextIndex === undefined ? 0 : 1;
|
||||
},
|
||||
(phase, previousPhase) => {
|
||||
if (phase === -1) {
|
||||
closing.value = true;
|
||||
return;
|
||||
}
|
||||
if (phase === 1) {
|
||||
closing.value = false;
|
||||
return;
|
||||
}
|
||||
if (previousPhase !== -1 || !closing.value) return;
|
||||
closing.value = false;
|
||||
const closedPosition = animatedDetentsState.get().closedDetentPosition;
|
||||
if (closedPosition === undefined) return;
|
||||
if (Math.abs(animatedPosition.value - closedPosition) < 1) runOnJS(onClosed)();
|
||||
},
|
||||
[animatedAnimationState, animatedDetentsState, animatedPosition, onClosed],
|
||||
);
|
||||
return null;
|
||||
}
|
||||
|
||||
export function useIsolatedBottomSheetVisibility({
|
||||
visible,
|
||||
isEnabled,
|
||||
|
||||
@@ -1,11 +1,15 @@
|
||||
import type { SelectedFile } from "@/attachments/selected-file";
|
||||
import { prepareImageAttachmentsForSend } from "@/attachments/service";
|
||||
import { FILE_UPLOAD_MAX_BYTES } from "@/attachments/upload-limit";
|
||||
import type { AgentProvider, ProviderOptions } from "@getpaseo/protocol/agent-types";
|
||||
import type {
|
||||
ActiveTurnBehavior,
|
||||
AgentSnapshotPayload,
|
||||
ForgeSearchItem,
|
||||
UploadedFileAttachment,
|
||||
} from "@getpaseo/protocol/messages";
|
||||
import { AgentProviderSwitchError } from "@getpaseo/client/internal/daemon-client";
|
||||
import type { StagedProviderSwitch } from "@/composer/provider-switch";
|
||||
import type {
|
||||
AttachmentMetadata,
|
||||
ComposerAttachment,
|
||||
@@ -19,7 +23,13 @@ import {
|
||||
splitComposerAttachmentsForSubmit,
|
||||
type ComposerAttachmentSubmitFormat,
|
||||
} from "@/composer/attachments/submit";
|
||||
import { createUserMessage, generateMessageId, type UserMessageItem } from "@/types/stream";
|
||||
import {
|
||||
createPendingProviderSwitchItem,
|
||||
createUserMessage,
|
||||
generateMessageId,
|
||||
type ProviderSwitchItem,
|
||||
type UserMessageItem,
|
||||
} from "@/types/stream";
|
||||
import type { MessageSubmissionRejectionOutcome } from "@/composer/submission/model";
|
||||
import type { PickedImageAttachmentInput } from "@/hooks/image-attachment-picker";
|
||||
import { i18n } from "@/i18n/i18next";
|
||||
@@ -60,6 +70,20 @@ export interface ComposerSendClient {
|
||||
attachments: ReturnType<typeof splitComposerAttachmentsForSubmit>["attachments"];
|
||||
},
|
||||
) => Promise<unknown>;
|
||||
switchAgentProvider?: (
|
||||
agentId: string,
|
||||
options: {
|
||||
provider: AgentProvider;
|
||||
model?: string | null;
|
||||
modeId?: string | null;
|
||||
thinkingOptionId?: string | null;
|
||||
providerOptions?: ProviderOptions;
|
||||
text: string;
|
||||
messageId: string;
|
||||
images?: Array<{ data: string; mimeType: string }>;
|
||||
attachments?: ReturnType<typeof splitComposerAttachmentsForSubmit>["attachments"];
|
||||
},
|
||||
) => Promise<{ agent?: AgentSnapshotPayload }>;
|
||||
uploadFile: (input: { fileName: string; mimeType: string; bytes: Uint8Array }) => Promise<{
|
||||
requestId: string;
|
||||
file: UploadedFileAttachment | null;
|
||||
@@ -73,7 +97,11 @@ export interface ComposerCancelClient {
|
||||
}
|
||||
|
||||
export interface MessageSubmissionWriter {
|
||||
begin: (agentId: string, message: UserMessageItem) => void;
|
||||
begin: (
|
||||
agentId: string,
|
||||
message: UserMessageItem,
|
||||
options?: { providerSwitch?: ProviderSwitchItem },
|
||||
) => void;
|
||||
accept: (agentId: string, clientMessageId: string) => void;
|
||||
reject: (agentId: string, clientMessageId: string) => MessageSubmissionRejectionOutcome;
|
||||
}
|
||||
@@ -193,6 +221,33 @@ export interface DispatchComposerAgentMessageInput {
|
||||
submission: MessageSubmissionWriter;
|
||||
activeTurnBehavior?: ActiveTurnBehavior;
|
||||
activeTurnId?: string;
|
||||
currentProvider?: AgentProvider | null;
|
||||
currentModel?: string | null;
|
||||
stagedProviderSwitch?: StagedProviderSwitch | null;
|
||||
onProviderSwitchCommitted?: (agent: AgentSnapshotPayload | undefined) => void | Promise<void>;
|
||||
}
|
||||
|
||||
function buildPendingProviderSwitch(
|
||||
input: DispatchComposerAgentMessageInput,
|
||||
clientMessageId: string,
|
||||
timestamp: Date,
|
||||
): ProviderSwitchItem | undefined {
|
||||
if (
|
||||
!input.stagedProviderSwitch ||
|
||||
!input.client.switchAgentProvider ||
|
||||
!input.currentProvider ||
|
||||
input.stagedProviderSwitch.provider === input.currentProvider
|
||||
) {
|
||||
return undefined;
|
||||
}
|
||||
return createPendingProviderSwitchItem({
|
||||
clientMessageId,
|
||||
fromProvider: input.currentProvider,
|
||||
toProvider: input.stagedProviderSwitch.provider,
|
||||
fromModel: input.currentModel ?? null,
|
||||
toModel: input.stagedProviderSwitch.model,
|
||||
timestamp,
|
||||
});
|
||||
}
|
||||
|
||||
export async function dispatchComposerAgentMessage(
|
||||
@@ -202,17 +257,23 @@ export async function dispatchComposerAgentMessage(
|
||||
format: input.attachmentSubmitFormat,
|
||||
});
|
||||
const clientMessageId = generateMessageId();
|
||||
const timestamp = new Date();
|
||||
const userMessage = createUserMessage({
|
||||
clientMessageId,
|
||||
text: input.text,
|
||||
timestamp: new Date(),
|
||||
timestamp,
|
||||
images: wirePayload.images,
|
||||
attachments: wirePayload.attachments,
|
||||
...(input.activeTurnBehavior === "steer" && input.activeTurnId
|
||||
...(input.activeTurnBehavior === "steer" && input.activeTurnId && !input.stagedProviderSwitch
|
||||
? { turnId: input.activeTurnId }
|
||||
: {}),
|
||||
});
|
||||
input.submission.begin(input.agentId, userMessage);
|
||||
const pendingProviderSwitch = buildPendingProviderSwitch(input, clientMessageId, timestamp);
|
||||
input.submission.begin(
|
||||
input.agentId,
|
||||
userMessage,
|
||||
pendingProviderSwitch ? { providerSwitch: pendingProviderSwitch } : undefined,
|
||||
);
|
||||
try {
|
||||
const imagePayload = input.uploadImages
|
||||
? { attachments: await input.uploadImages(wirePayload.images) }
|
||||
@@ -220,6 +281,22 @@ export async function dispatchComposerAgentMessage(
|
||||
client: input.client,
|
||||
images: wirePayload.images,
|
||||
});
|
||||
if (input.stagedProviderSwitch && input.client.switchAgentProvider) {
|
||||
const result = await input.client.switchAgentProvider(input.agentId, {
|
||||
provider: input.stagedProviderSwitch.provider,
|
||||
model: input.stagedProviderSwitch.model,
|
||||
modeId: input.stagedProviderSwitch.modeId,
|
||||
thinkingOptionId: input.stagedProviderSwitch.thinkingOptionId,
|
||||
providerOptions: input.stagedProviderSwitch.providerOptions,
|
||||
text: input.text,
|
||||
messageId: clientMessageId,
|
||||
...(imagePayload.images ? { images: imagePayload.images } : {}),
|
||||
attachments: [...wirePayload.attachments, ...(imagePayload.attachments ?? [])],
|
||||
});
|
||||
input.submission.accept(input.agentId, clientMessageId);
|
||||
await input.onProviderSwitchCommitted?.(result.agent);
|
||||
return;
|
||||
}
|
||||
await input.client.sendAgentMessage(input.agentId, input.text, {
|
||||
messageId: clientMessageId,
|
||||
...(input.activeTurnBehavior ? { activeTurnBehavior: input.activeTurnBehavior } : {}),
|
||||
@@ -229,6 +306,9 @@ export async function dispatchComposerAgentMessage(
|
||||
input.submission.accept(input.agentId, clientMessageId);
|
||||
} catch (error) {
|
||||
input.submission.reject(input.agentId, clientMessageId);
|
||||
if (error instanceof AgentProviderSwitchError && error.agent) {
|
||||
await input.onProviderSwitchCommitted?.(error.agent);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,12 +16,21 @@ import { formatThinkingOptionLabel } from "@/agent-controls/labels";
|
||||
import { CombinedModelSelector } from "@/components/combined-model-selector";
|
||||
import {
|
||||
buildProviderSelectorProviders,
|
||||
buildSelectableProviderSelectorProviders,
|
||||
buildSelectorProvider,
|
||||
type ProviderSelectorProvider,
|
||||
} from "@/provider-selection/provider-selection";
|
||||
import { filterSelectableModels } from "@/provider-selection/model-catalog";
|
||||
import { useSessionStore } from "@/stores/session-store";
|
||||
import { useProvidersSnapshot } from "@/hooks/use-providers-snapshot";
|
||||
import { useDraftProviderOptions } from "@/hooks/use-draft-provider-options";
|
||||
import {
|
||||
clearStagedProviderSwitch,
|
||||
isStagedProviderSwitchInFlight,
|
||||
type StagedProviderSwitch,
|
||||
useStagedProviderSwitch,
|
||||
useStagedProviderSwitchStore,
|
||||
} from "@/composer/provider-switch";
|
||||
import { resolveProviderDefinition } from "@/utils/provider-definitions";
|
||||
import { mergeProviderPreferences, useFormPreferences } from "@/hooks/use-form-preferences";
|
||||
import {
|
||||
@@ -104,6 +113,7 @@ import {
|
||||
type AgentProfilePicker,
|
||||
type AgentProfileSeed,
|
||||
type DraftAgentProfileControls,
|
||||
type MaterializedAgentProfile,
|
||||
} from "@/agent-profiles";
|
||||
import { buildSettingsHostSectionRoute } from "@/utils/host-routes";
|
||||
|
||||
@@ -996,6 +1006,148 @@ function useAgentOptionControls(
|
||||
);
|
||||
}
|
||||
|
||||
function resolveActiveStagedSwitch(
|
||||
supportsProviderSwitching: boolean,
|
||||
rawStagedSwitch: StagedProviderSwitch | null,
|
||||
liveProvider: string | undefined,
|
||||
): StagedProviderSwitch | null {
|
||||
if (!supportsProviderSwitching || !rawStagedSwitch || !liveProvider) {
|
||||
return null;
|
||||
}
|
||||
return rawStagedSwitch.provider !== liveProvider ? rawStagedSwitch : null;
|
||||
}
|
||||
|
||||
function resolveDraftTargetModelId(
|
||||
modelId: string,
|
||||
preferredModel: string | undefined,
|
||||
nextModels: AgentModelDefinition[] | null,
|
||||
): string | null {
|
||||
if (modelId) return modelId;
|
||||
if (preferredModel) return preferredModel;
|
||||
const defaultModel = nextModels?.find((m) => m.isDefault);
|
||||
return defaultModel?.id ?? nextModels?.[0]?.id ?? null;
|
||||
}
|
||||
|
||||
function resolveDraftThinkingOptionId(
|
||||
targetModelId: string | null,
|
||||
targetModel: AgentModelDefinition | undefined,
|
||||
thinkingByModel: Record<string, string> | undefined,
|
||||
): string | null {
|
||||
const preferred = targetModelId ? thinkingByModel?.[targetModelId] : undefined;
|
||||
if (preferred) return preferred;
|
||||
return targetModel?.defaultThinkingOptionId ?? targetModel?.thinkingOptions?.[0]?.id ?? null;
|
||||
}
|
||||
|
||||
function resolveDraftModeId(
|
||||
preferredMode: string | undefined,
|
||||
nextEntry: ReturnType<typeof resolveProviderSnapshotEntry>,
|
||||
): string | null {
|
||||
if (preferredMode) return preferredMode;
|
||||
return nextEntry?.defaultModeId ?? nextEntry?.modes?.[0]?.id ?? null;
|
||||
}
|
||||
|
||||
function buildStagedProviderSwitchDraft(input: {
|
||||
nextProvider: string;
|
||||
modelId: string;
|
||||
snapshotEntries: ReturnType<typeof useProvidersSnapshot>["entries"];
|
||||
providerPreferences: ReturnType<typeof useFormPreferences>["preferences"]["providerPreferences"];
|
||||
}): StagedProviderSwitch {
|
||||
const { nextProvider, modelId, snapshotEntries, providerPreferences } = input;
|
||||
const nextEntry = resolveProviderSnapshotEntry(snapshotEntries, nextProvider);
|
||||
const nextModels = filterSelectableModels(nextEntry?.models ?? null);
|
||||
const preferred = providerPreferences?.[nextProvider];
|
||||
const targetModelId = resolveDraftTargetModelId(modelId, preferred?.model, nextModels);
|
||||
const targetModel = nextModels?.find((m) => m.id === targetModelId);
|
||||
return {
|
||||
provider: nextProvider,
|
||||
model: targetModelId,
|
||||
thinkingOptionId: resolveDraftThinkingOptionId(
|
||||
targetModelId,
|
||||
targetModel,
|
||||
preferred?.thinkingByModel,
|
||||
),
|
||||
modeId: resolveDraftModeId(preferred?.mode, nextEntry),
|
||||
providerOptions: preferred?.options ? { ...preferred.options } : {},
|
||||
};
|
||||
}
|
||||
|
||||
function resolveAgentModelSelectionWithStagedSwitch(input: {
|
||||
models: AgentModelDefinition[] | null;
|
||||
agent: AgentControlsSlice;
|
||||
activeStagedSwitch: StagedProviderSwitch | null;
|
||||
}) {
|
||||
const { models, agent, activeStagedSwitch } = input;
|
||||
return resolveAgentModelSelection({
|
||||
models,
|
||||
runtimeModelId: activeStagedSwitch ? null : agent?.runtimeModelId,
|
||||
configuredModelId: activeStagedSwitch ? activeStagedSwitch.model : agent?.model,
|
||||
runtimeThinkingOptionId: activeStagedSwitch ? null : agent?.runtimeThinkingOptionId,
|
||||
explicitThinkingOptionId: activeStagedSwitch
|
||||
? activeStagedSwitch.thinkingOptionId
|
||||
: agent?.thinkingOptionId,
|
||||
});
|
||||
}
|
||||
|
||||
function buildStagedDraftOptionsParams(input: {
|
||||
serverId: string;
|
||||
agentCwd: string | null | undefined;
|
||||
activeStagedSwitch: StagedProviderSwitch | null;
|
||||
getProvider: () => AgentProvider | null;
|
||||
modelId: string | null;
|
||||
thinkingOptionId: string | null;
|
||||
}) {
|
||||
const { serverId, agentCwd, activeStagedSwitch, getProvider, modelId, thinkingOptionId } = input;
|
||||
return {
|
||||
serverId: activeStagedSwitch ? serverId : null,
|
||||
provider: activeStagedSwitch ? activeStagedSwitch.provider : null,
|
||||
getProvider,
|
||||
cwd: agentCwd,
|
||||
modeId: activeStagedSwitch?.modeId ?? null,
|
||||
modelId,
|
||||
thinkingOptionId,
|
||||
initialOptions: activeStagedSwitch?.providerOptions,
|
||||
};
|
||||
}
|
||||
|
||||
function resolveAgentOptionControlsForComposer(input: {
|
||||
activeStagedSwitch: StagedProviderSwitch | null;
|
||||
stagedControls: ComposerOptionControls | null | undefined;
|
||||
liveOptionControls: ComposerOptionControls;
|
||||
onSetOption: (key: string, value: unknown) => void;
|
||||
}): ComposerOptionControls {
|
||||
const { activeStagedSwitch, stagedControls, liveOptionControls, onSetOption } = input;
|
||||
if (!activeStagedSwitch) {
|
||||
return liveOptionControls;
|
||||
}
|
||||
if (stagedControls) {
|
||||
return { ...stagedControls, onSetOption };
|
||||
}
|
||||
return { controls: [], options: activeStagedSwitch.providerOptions, onSetOption };
|
||||
}
|
||||
|
||||
function resolveControlledAgentControlsProps(input: {
|
||||
effectiveProvider: string | undefined;
|
||||
liveProvider: string;
|
||||
selectedModelId: string | null;
|
||||
selectedThinkingId: string | null;
|
||||
thinkingOptions: AgentControlOption[];
|
||||
supportsProviderSwitching: boolean;
|
||||
handleSelectProviderAndModel: (provider: string, modelId: string) => void;
|
||||
snapshotIsLoading: boolean;
|
||||
selectedProviderIsLoading: boolean;
|
||||
}) {
|
||||
return {
|
||||
provider: input.effectiveProvider ?? input.liveProvider,
|
||||
selectedModelId: input.selectedModelId ?? undefined,
|
||||
selectedThinkingOptionId: input.selectedThinkingId ?? undefined,
|
||||
thinkingOptions: input.thinkingOptions.length > 0 ? input.thinkingOptions : undefined,
|
||||
onSelectProviderAndModel: input.supportsProviderSwitching
|
||||
? input.handleSelectProviderAndModel
|
||||
: undefined,
|
||||
isModelLoading: input.snapshotIsLoading || input.selectedProviderIsLoading,
|
||||
};
|
||||
}
|
||||
|
||||
export const AgentControls = memo(function AgentControls({
|
||||
showToolbar,
|
||||
agentId,
|
||||
@@ -1003,15 +1155,22 @@ export const AgentControls = memo(function AgentControls({
|
||||
onDropdownClose,
|
||||
isCompactLayout,
|
||||
}: AgentControlsProps) {
|
||||
const { updatePreferences } = useFormPreferences();
|
||||
const { preferences, updatePreferences } = useFormPreferences();
|
||||
const agent = useSessionStore(
|
||||
useShallow((state) => selectAgentControlsSlice(state, serverId, agentId)),
|
||||
);
|
||||
const client = useSessionStore((state) => state.sessions[serverId]?.client ?? null);
|
||||
const supportsProviderSwitching = useSessionStore(
|
||||
(state) => state.sessions[serverId]?.serverInfo?.features?.providerSwitching === true,
|
||||
);
|
||||
const rawStagedSwitch = useStagedProviderSwitch(serverId, agentId);
|
||||
const activeStagedSwitch = resolveActiveStagedSwitch(
|
||||
supportsProviderSwitching,
|
||||
rawStagedSwitch,
|
||||
agent?.provider,
|
||||
);
|
||||
const toast = useToast();
|
||||
const modeControl = useLiveAgentModeControl(serverId, agentId);
|
||||
const commandCenterModes = toCommandCenterModes(modeControl);
|
||||
const modeProviderDefinitions = getModeProviderDefinitions(modeControl);
|
||||
const liveModeControl = useLiveAgentModeControl(serverId, agentId);
|
||||
|
||||
const {
|
||||
entries: snapshotEntries,
|
||||
@@ -1021,24 +1180,35 @@ export const AgentControls = memo(function AgentControls({
|
||||
refetchIfStale: refetchSnapshotIfStale,
|
||||
} = useProvidersSnapshot(serverId, { cwd: agent?.cwd });
|
||||
|
||||
const stagedProvider = activeStagedSwitch ? activeStagedSwitch.provider : null;
|
||||
const effectiveProvider = stagedProvider ?? agent?.provider;
|
||||
const stagedProviderRef = useRef<AgentProvider | null>(stagedProvider);
|
||||
stagedProviderRef.current = stagedProvider;
|
||||
|
||||
const snapshotSelectedEntry = useMemo(
|
||||
() => resolveProviderSnapshotEntry(snapshotEntries, agent?.provider),
|
||||
[snapshotEntries, agent?.provider],
|
||||
() => resolveProviderSnapshotEntry(snapshotEntries, effectiveProvider),
|
||||
[snapshotEntries, effectiveProvider],
|
||||
);
|
||||
|
||||
const models = filterSelectableModels(snapshotSelectedEntry?.models ?? null);
|
||||
const selectedProviderIsLoading = snapshotSelectedEntry?.status === "loading";
|
||||
|
||||
const agentProviderDefinitions = useMemo(
|
||||
() => buildAgentProviderDefinitions(agent?.provider, snapshotEntries),
|
||||
[agent?.provider, snapshotEntries],
|
||||
() => buildAgentProviderDefinitions(effectiveProvider, snapshotEntries),
|
||||
[effectiveProvider, snapshotEntries],
|
||||
);
|
||||
|
||||
const agentProviderModels = useMemo(
|
||||
() => buildAgentProviderModels(agent?.provider, models),
|
||||
[agent?.provider, models],
|
||||
() => buildAgentProviderModels(effectiveProvider, models),
|
||||
[effectiveProvider, models],
|
||||
);
|
||||
const agentModelSelectorProviders = useMemo(() => {
|
||||
if (supportsProviderSwitching && snapshotEntries && snapshotEntries.length > 0) {
|
||||
const selectable = buildSelectableProviderSelectorProviders(snapshotEntries, {
|
||||
selectedProvider: effectiveProvider ?? null,
|
||||
});
|
||||
if (selectable.length > 0) return selectable;
|
||||
}
|
||||
if (snapshotSelectedEntry) {
|
||||
return [buildSelectorProvider(snapshotSelectedEntry)];
|
||||
}
|
||||
@@ -1046,14 +1216,19 @@ export const AgentControls = memo(function AgentControls({
|
||||
providerDefinitions: agentProviderDefinitions,
|
||||
modelsByProvider: agentProviderModels,
|
||||
});
|
||||
}, [agentProviderDefinitions, agentProviderModels, snapshotSelectedEntry]);
|
||||
}, [
|
||||
agentProviderDefinitions,
|
||||
agentProviderModels,
|
||||
effectiveProvider,
|
||||
snapshotEntries,
|
||||
snapshotSelectedEntry,
|
||||
supportsProviderSwitching,
|
||||
]);
|
||||
|
||||
const modelSelection = resolveAgentModelSelection({
|
||||
const modelSelection = resolveAgentModelSelectionWithStagedSwitch({
|
||||
models,
|
||||
runtimeModelId: agent?.runtimeModelId,
|
||||
configuredModelId: agent?.model,
|
||||
runtimeThinkingOptionId: agent?.runtimeThinkingOptionId,
|
||||
explicitThinkingOptionId: agent?.thinkingOptionId,
|
||||
agent,
|
||||
activeStagedSwitch,
|
||||
});
|
||||
|
||||
const modelOptions = useMemo<AgentControlOption[]>(() => {
|
||||
@@ -1070,13 +1245,71 @@ export const AgentControls = memo(function AgentControls({
|
||||
const agentProvider = agent?.provider;
|
||||
const activeModelId = modelSelection.activeModelId;
|
||||
|
||||
const handleSelectModel = useCallback(
|
||||
const stagedModeOptions = useMemo<AgentMode[]>(() => {
|
||||
if (!activeStagedSwitch || !snapshotSelectedEntry?.modes) return [];
|
||||
return snapshotSelectedEntry.modes.map((mode) => ({
|
||||
id: mode.id,
|
||||
label: mode.label,
|
||||
description: mode.description ?? "",
|
||||
}));
|
||||
}, [activeStagedSwitch, snapshotSelectedEntry?.modes]);
|
||||
|
||||
const handleSelectStagedMode = useCallback(
|
||||
(modeId: string) => {
|
||||
useStagedProviderSwitchStore.getState().patch(serverId, agentId, (current) => ({
|
||||
...current,
|
||||
modeId,
|
||||
}));
|
||||
},
|
||||
[agentId, serverId],
|
||||
);
|
||||
|
||||
const modeControl = useMemo<AgentModeControlValue | null>(() => {
|
||||
if (!activeStagedSwitch) return liveModeControl;
|
||||
if (stagedModeOptions.length === 0) return null;
|
||||
return {
|
||||
provider: activeStagedSwitch.provider,
|
||||
providerDefinitions: agentProviderDefinitions,
|
||||
modeOptions: stagedModeOptions,
|
||||
selectedModeId:
|
||||
activeStagedSwitch.modeId ??
|
||||
snapshotSelectedEntry?.defaultModeId ??
|
||||
stagedModeOptions[0]?.id ??
|
||||
null,
|
||||
onSelectMode: handleSelectStagedMode,
|
||||
disabled: !client,
|
||||
};
|
||||
}, [
|
||||
activeStagedSwitch,
|
||||
agentProviderDefinitions,
|
||||
client,
|
||||
handleSelectStagedMode,
|
||||
liveModeControl,
|
||||
snapshotSelectedEntry?.defaultModeId,
|
||||
stagedModeOptions,
|
||||
]);
|
||||
const commandCenterModes = toCommandCenterModes(modeControl);
|
||||
const modeProviderDefinitions = getModeProviderDefinitions(modeControl);
|
||||
|
||||
const getStagedProvider = useCallback(() => stagedProviderRef.current, []);
|
||||
const stagedDraftOptions = useDraftProviderOptions(
|
||||
buildStagedDraftOptionsParams({
|
||||
serverId,
|
||||
agentCwd: agent?.cwd,
|
||||
activeStagedSwitch,
|
||||
getProvider: getStagedProvider,
|
||||
modelId: modelSelection.activeModelId,
|
||||
thinkingOptionId: modelSelection.selectedThinkingId,
|
||||
}),
|
||||
);
|
||||
|
||||
const applyLiveModel = useCallback(
|
||||
async (modelId: string) => {
|
||||
if (!client || !agentProvider) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await client.setAgentModel(agentId, modelId);
|
||||
await client.setAgentModel(agentId, modelId, { expectedProvider: agentProvider });
|
||||
await updatePreferences((current) =>
|
||||
mergeProviderPreferences({
|
||||
preferences: current,
|
||||
@@ -1091,21 +1324,147 @@ export const AgentControls = memo(function AgentControls({
|
||||
},
|
||||
[agentId, agentProvider, client, toast, updatePreferences],
|
||||
);
|
||||
const handleSelectCommandCenterModel = useCallback(
|
||||
(_provider: AgentProvider, modelId: string) => handleSelectModel(modelId),
|
||||
[handleSelectModel],
|
||||
|
||||
const handleSelectModel = useCallback(
|
||||
async (modelId: string) => {
|
||||
if (activeStagedSwitch) {
|
||||
const nextModel = models?.find((candidate) => candidate.id === modelId);
|
||||
const preferredThinking =
|
||||
preferences.providerPreferences?.[activeStagedSwitch.provider]?.thinkingByModel?.[
|
||||
modelId
|
||||
];
|
||||
const nextThinking =
|
||||
preferredThinking ??
|
||||
nextModel?.defaultThinkingOptionId ??
|
||||
nextModel?.thinkingOptions?.[0]?.id ??
|
||||
null;
|
||||
useStagedProviderSwitchStore.getState().patch(serverId, agentId, (current) => ({
|
||||
...current,
|
||||
model: modelId,
|
||||
thinkingOptionId: nextThinking,
|
||||
}));
|
||||
return;
|
||||
}
|
||||
await applyLiveModel(modelId);
|
||||
},
|
||||
[
|
||||
activeStagedSwitch,
|
||||
agentId,
|
||||
applyLiveModel,
|
||||
models,
|
||||
preferences.providerPreferences,
|
||||
serverId,
|
||||
],
|
||||
);
|
||||
|
||||
// A running agent is one provider's process, so only that provider's profiles
|
||||
// can apply to it.
|
||||
const profileProviders = useMemo(() => (agentProvider ? [agentProvider] : []), [agentProvider]);
|
||||
const handleSelectProviderAndModel = useCallback(
|
||||
(nextProvider: string, modelId: string) => {
|
||||
if (!agentProvider) return;
|
||||
if (nextProvider === agentProvider && !isStagedProviderSwitchInFlight(serverId, agentId)) {
|
||||
clearStagedProviderSwitch(serverId, agentId);
|
||||
const liveModelId = agent?.runtimeModelId ?? agent?.model ?? null;
|
||||
if (modelId && modelId !== liveModelId) {
|
||||
void applyLiveModel(modelId);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (!supportsProviderSwitching) return;
|
||||
useStagedProviderSwitchStore.getState().stage(
|
||||
serverId,
|
||||
agentId,
|
||||
buildStagedProviderSwitchDraft({
|
||||
nextProvider,
|
||||
modelId,
|
||||
snapshotEntries,
|
||||
providerPreferences: preferences.providerPreferences,
|
||||
}),
|
||||
);
|
||||
},
|
||||
[
|
||||
agent?.model,
|
||||
agent?.runtimeModelId,
|
||||
agentId,
|
||||
agentProvider,
|
||||
applyLiveModel,
|
||||
preferences.providerPreferences,
|
||||
serverId,
|
||||
snapshotEntries,
|
||||
supportsProviderSwitching,
|
||||
],
|
||||
);
|
||||
|
||||
const handleSelectCommandCenterModel = useCallback(
|
||||
(provider: AgentProvider, modelId: string) => {
|
||||
if (supportsProviderSwitching) {
|
||||
handleSelectProviderAndModel(provider, modelId);
|
||||
return;
|
||||
}
|
||||
void handleSelectModel(modelId);
|
||||
},
|
||||
[handleSelectModel, handleSelectProviderAndModel, supportsProviderSwitching],
|
||||
);
|
||||
|
||||
const handleStageAgentProfileSwitch = useCallback(
|
||||
(resolved: MaterializedAgentProfile) => {
|
||||
if (!supportsProviderSwitching) return;
|
||||
const nextEntry = resolveProviderSnapshotEntry(snapshotEntries, resolved.provider);
|
||||
const modeIds = resolveSnapshotModeIds(nextEntry);
|
||||
const validModeId =
|
||||
resolved.modeId && (!modeIds || modeIds.includes(resolved.modeId))
|
||||
? resolved.modeId
|
||||
: (nextEntry?.defaultModeId ?? nextEntry?.modes?.[0]?.id ?? null);
|
||||
useStagedProviderSwitchStore.getState().stage(serverId, agentId, {
|
||||
provider: resolved.provider,
|
||||
model: resolved.modelId ?? null,
|
||||
modeId: validModeId,
|
||||
thinkingOptionId: resolved.thinkingOptionId ?? null,
|
||||
providerOptions: resolved.options ? { ...resolved.options } : {},
|
||||
});
|
||||
stagedDraftOptions.applyProfile({
|
||||
provider: resolved.provider,
|
||||
options: resolved.options ?? {},
|
||||
});
|
||||
},
|
||||
[agentId, serverId, snapshotEntries, stagedDraftOptions, supportsProviderSwitching],
|
||||
);
|
||||
|
||||
const handleClearStagedSwitchOnProfile = useCallback(() => {
|
||||
clearStagedProviderSwitch(serverId, agentId);
|
||||
}, [agentId, serverId]);
|
||||
|
||||
const profileProviders = useMemo(() => {
|
||||
if (supportsProviderSwitching) {
|
||||
return agentModelSelectorProviders.map((entry) => entry.id);
|
||||
}
|
||||
return agentProvider ? [agentProvider] : [];
|
||||
}, [agentModelSelectorProviders, agentProvider, supportsProviderSwitching]);
|
||||
const liveSnapshotEntry = useMemo(
|
||||
() => resolveProviderSnapshotEntry(snapshotEntries, agentProvider),
|
||||
[snapshotEntries, agentProvider],
|
||||
);
|
||||
const profileModeIds = useMemo(
|
||||
() => resolveSnapshotModeIds(snapshotSelectedEntry),
|
||||
[snapshotSelectedEntry],
|
||||
() => resolveSnapshotModeIds(liveSnapshotEntry),
|
||||
[liveSnapshotEntry],
|
||||
);
|
||||
const profileTarget = useMemo<AgentProfileApplyTarget>(
|
||||
() => ({ kind: "agent", agentId, availableModeIds: profileModeIds }),
|
||||
[agentId, profileModeIds],
|
||||
() => ({
|
||||
kind: "agent",
|
||||
agentId,
|
||||
availableModeIds: profileModeIds,
|
||||
currentProvider: agentProvider,
|
||||
isSwitchInFlight: () => isStagedProviderSwitchInFlight(serverId, agentId),
|
||||
onApplySameProvider: handleClearStagedSwitchOnProfile,
|
||||
onStageProviderSwitch: supportsProviderSwitching ? handleStageAgentProfileSwitch : undefined,
|
||||
}),
|
||||
[
|
||||
agentId,
|
||||
agentProvider,
|
||||
handleClearStagedSwitchOnProfile,
|
||||
handleStageAgentProfileSwitch,
|
||||
profileModeIds,
|
||||
serverId,
|
||||
supportsProviderSwitching,
|
||||
],
|
||||
);
|
||||
const agentProfiles = useAgentProfilePicker({
|
||||
serverId,
|
||||
@@ -1118,6 +1477,13 @@ export const AgentControls = memo(function AgentControls({
|
||||
|
||||
const handleSelectThinkingOption = useCallback(
|
||||
(thinkingOptionId: string) => {
|
||||
if (activeStagedSwitch) {
|
||||
useStagedProviderSwitchStore.getState().patch(serverId, agentId, (current) => ({
|
||||
...current,
|
||||
thinkingOptionId,
|
||||
}));
|
||||
return;
|
||||
}
|
||||
if (!client || !agentProvider) {
|
||||
return;
|
||||
}
|
||||
@@ -1138,18 +1504,35 @@ export const AgentControls = memo(function AgentControls({
|
||||
});
|
||||
}
|
||||
void client
|
||||
.setAgentThinkingOption(agentId, thinkingOptionId)
|
||||
.setAgentThinkingOption(agentId, thinkingOptionId, { expectedProvider: agentProvider })
|
||||
.then((notice) => showProviderNoticeToast(toast, notice))
|
||||
.catch((error) => {
|
||||
console.warn("[AgentControls] setAgentThinkingOption failed", error);
|
||||
toast.error(toErrorMessage(error));
|
||||
});
|
||||
},
|
||||
[activeModelId, agentId, agentProvider, client, toast, updatePreferences],
|
||||
[
|
||||
activeModelId,
|
||||
activeStagedSwitch,
|
||||
agentId,
|
||||
agentProvider,
|
||||
client,
|
||||
serverId,
|
||||
toast,
|
||||
updatePreferences,
|
||||
],
|
||||
);
|
||||
|
||||
const handleSetOption = useCallback(
|
||||
(key: string, value: unknown) => {
|
||||
if (activeStagedSwitch) {
|
||||
stagedDraftOptions.setOption(key, value);
|
||||
useStagedProviderSwitchStore.getState().patch(serverId, agentId, (current) => ({
|
||||
...current,
|
||||
providerOptions: { ...current.providerOptions, [key]: value },
|
||||
}));
|
||||
return;
|
||||
}
|
||||
if (!client || !agentProvider) {
|
||||
return;
|
||||
}
|
||||
@@ -1166,15 +1549,36 @@ export const AgentControls = memo(function AgentControls({
|
||||
).catch((error) => {
|
||||
console.warn("[AgentControls] persist option preference failed", error);
|
||||
});
|
||||
void client.setAgentOptions(agentId, { [key]: value }).catch((error) => {
|
||||
console.warn("[AgentControls] setAgentOptions failed", error);
|
||||
toast.error(toErrorMessage(error));
|
||||
});
|
||||
void client
|
||||
.setAgentOptions(agentId, { [key]: value }, { expectedProvider: agentProvider })
|
||||
.catch((error) => {
|
||||
console.warn("[AgentControls] setAgentOptions failed", error);
|
||||
toast.error(toErrorMessage(error));
|
||||
});
|
||||
},
|
||||
[agentId, agentProvider, client, toast, updatePreferences],
|
||||
[
|
||||
activeStagedSwitch,
|
||||
agentId,
|
||||
agentProvider,
|
||||
client,
|
||||
serverId,
|
||||
stagedDraftOptions,
|
||||
toast,
|
||||
updatePreferences,
|
||||
],
|
||||
);
|
||||
|
||||
const agentOptionControls = useAgentOptionControls(agent, handleSetOption);
|
||||
const liveOptionControls = useAgentOptionControls(agent, handleSetOption);
|
||||
const agentOptionControls = useMemo<ComposerOptionControls>(
|
||||
() =>
|
||||
resolveAgentOptionControlsForComposer({
|
||||
activeStagedSwitch,
|
||||
stagedControls: stagedDraftOptions.optionControls,
|
||||
liveOptionControls,
|
||||
onSetOption: handleSetOption,
|
||||
}),
|
||||
[activeStagedSwitch, handleSetOption, liveOptionControls, stagedDraftOptions.optionControls],
|
||||
);
|
||||
|
||||
// The agent's composer exists apart from this component; while this is mounted, prompt
|
||||
// commands go through the input the user is typing in.
|
||||
@@ -1198,12 +1602,12 @@ export const AgentControls = memo(function AgentControls({
|
||||
() => ({
|
||||
serverId,
|
||||
ownerKey: agentId,
|
||||
provider: agentProvider,
|
||||
provider: effectiveProvider,
|
||||
providerDefinitions: modeProviderDefinitions,
|
||||
profiles: agentProfiles,
|
||||
models: {
|
||||
providers: agentModelSelectorProviders,
|
||||
selectedProvider: agentProvider,
|
||||
selectedProvider: effectiveProvider,
|
||||
selectedModelId: activeModelId,
|
||||
select: handleSelectCommandCenterModel,
|
||||
},
|
||||
@@ -1222,7 +1626,7 @@ export const AgentControls = memo(function AgentControls({
|
||||
client,
|
||||
agentId,
|
||||
agentModelSelectorProviders,
|
||||
agentProvider,
|
||||
effectiveProvider,
|
||||
commandCenterModes,
|
||||
handleSelectCommandCenterModel,
|
||||
handleSelectThinkingOption,
|
||||
@@ -1242,8 +1646,8 @@ export const AgentControls = memo(function AgentControls({
|
||||
);
|
||||
|
||||
const handleModelSelectorOpen = useCallback(() => {
|
||||
refetchSnapshotIfStale(agentProvider);
|
||||
}, [agentProvider, refetchSnapshotIfStale]);
|
||||
refetchSnapshotIfStale(supportsProviderSwitching ? undefined : effectiveProvider);
|
||||
}, [effectiveProvider, refetchSnapshotIfStale, supportsProviderSwitching]);
|
||||
|
||||
const handleRetryModelProvider = useCallback(
|
||||
(provider: AgentProvider) => {
|
||||
@@ -1256,6 +1660,18 @@ export const AgentControls = memo(function AgentControls({
|
||||
return null;
|
||||
}
|
||||
|
||||
const resolvedControlProps = resolveControlledAgentControlsProps({
|
||||
effectiveProvider,
|
||||
liveProvider: agent.provider,
|
||||
selectedModelId: modelSelection.activeModelId,
|
||||
selectedThinkingId: modelSelection.selectedThinkingId,
|
||||
thinkingOptions,
|
||||
supportsProviderSwitching,
|
||||
handleSelectProviderAndModel,
|
||||
snapshotIsLoading,
|
||||
selectedProviderIsLoading,
|
||||
});
|
||||
|
||||
return (
|
||||
<ComposerModelProvider value={composer}>
|
||||
{commandCenterRegistration}
|
||||
@@ -1263,21 +1679,17 @@ export const AgentControls = memo(function AgentControls({
|
||||
<>
|
||||
{profileEditor.element}
|
||||
<ControlledAgentControls
|
||||
provider={agent.provider}
|
||||
{...resolvedControlProps}
|
||||
modelSelectorProviders={agentModelSelectorProviders}
|
||||
modelOptions={modelOptions}
|
||||
selectedModelId={modelSelection.activeModelId ?? undefined}
|
||||
onSelectModel={handleSelectModel}
|
||||
agentProfiles={agentProfiles}
|
||||
onApplyAgentProfile={agentProfiles?.applyProfile}
|
||||
onEditAgentProfiles={handleEditAgentProfiles}
|
||||
onCreateAgentProfile={profileActions.create}
|
||||
onEditAgentProfile={profileActions.edit}
|
||||
thinkingOptions={thinkingOptions.length > 0 ? thinkingOptions : undefined}
|
||||
selectedThinkingOptionId={modelSelection.selectedThinkingId ?? undefined}
|
||||
onSelectThinkingOption={handleSelectThinkingOption}
|
||||
optionControls={agentOptionControls}
|
||||
isModelLoading={snapshotIsLoading || selectedProviderIsLoading}
|
||||
onModelSelectorOpen={handleModelSelectorOpen}
|
||||
onRetryModelProvider={handleRetryModelProvider}
|
||||
isRetryingModelProvider={snapshotIsRefreshing}
|
||||
|
||||
@@ -296,7 +296,7 @@ export function useLiveAgentModeControl(
|
||||
console.warn("[AgentModeControl] persist mode preference failed", error);
|
||||
});
|
||||
void client
|
||||
.setAgentMode(agentId, modeId)
|
||||
.setAgentMode(agentId, modeId, { expectedProvider: slice.provider })
|
||||
.then((notice) => showProviderNoticeToast(toast, notice))
|
||||
.catch((error) => {
|
||||
console.warn("[AgentModeControl] setAgentMode failed", error);
|
||||
|
||||
@@ -9,6 +9,21 @@ import { useStore } from "zustand";
|
||||
import { getHostRuntimeStore } from "@/runtime/host-runtime";
|
||||
import { LoadingSpinner } from "@/components/ui/loading-spinner";
|
||||
import { Alert } from "@/components/ui/alert";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
beginStagedProviderSwitch,
|
||||
clearStagedProviderSwitch,
|
||||
endStagedProviderSwitch,
|
||||
getStagedProviderSwitch,
|
||||
isStagedProviderSwitchInFlight,
|
||||
settleCommittedProviderSwitch,
|
||||
useFailedStartupSettings,
|
||||
useIsStagedProviderSwitchInFlight,
|
||||
useStagedProviderSwitch,
|
||||
} from "@/composer/provider-switch";
|
||||
import { useProvidersSnapshot } from "@/hooks/use-providers-snapshot";
|
||||
import { normalizeAgentSnapshot } from "@/utils/agent-snapshots";
|
||||
import { resolveProviderLabel } from "@/utils/provider-definitions";
|
||||
import {
|
||||
View,
|
||||
Pressable,
|
||||
@@ -48,6 +63,7 @@ import { usePanelStore, type MobilePanelView } from "@/stores/panel-store";
|
||||
import { usePointerCapabilities } from "@/hooks/pointer-capabilities";
|
||||
import { useShallow } from "zustand/shallow";
|
||||
import {
|
||||
ArrowRightLeft,
|
||||
ArrowUp,
|
||||
Square,
|
||||
Pencil,
|
||||
@@ -298,16 +314,29 @@ function buildRealtimeVoiceButtonStyle(pressed: boolean, voiceButtonDisabled: bo
|
||||
|
||||
const EMPTY_METRICS: AgentMetric[] = [];
|
||||
|
||||
const EMPTY_AGENT_STATE = {
|
||||
provider: null,
|
||||
status: null,
|
||||
contextWindowMaxTokens: null,
|
||||
contextWindowUsedTokens: null,
|
||||
totalCostUsd: null,
|
||||
sessionMetrics: EMPTY_METRICS,
|
||||
model: null,
|
||||
};
|
||||
|
||||
function buildAgentStateSelector(serverId: string, agentId: string) {
|
||||
return (state: ReturnType<typeof useSessionStore.getState>) => {
|
||||
const agent = state.sessions[serverId]?.agents?.get(agentId) ?? null;
|
||||
if (!agent) return EMPTY_AGENT_STATE;
|
||||
const usage = agent.lastUsage;
|
||||
return {
|
||||
status: agent?.status ?? null,
|
||||
contextWindowMaxTokens: agent?.lastUsage?.contextWindowMaxTokens ?? null,
|
||||
contextWindowUsedTokens: agent?.lastUsage?.contextWindowUsedTokens ?? null,
|
||||
totalCostUsd: agent?.lastUsage?.totalCostUsd ?? null,
|
||||
sessionMetrics: agent?.sessionMetrics ?? EMPTY_METRICS,
|
||||
model: agent?.model ?? null,
|
||||
provider: agent.provider ?? null,
|
||||
status: agent.status ?? null,
|
||||
contextWindowMaxTokens: usage?.contextWindowMaxTokens ?? null,
|
||||
contextWindowUsedTokens: usage?.contextWindowUsedTokens ?? null,
|
||||
totalCostUsd: usage?.totalCostUsd ?? null,
|
||||
sessionMetrics: agent.sessionMetrics ?? EMPTY_METRICS,
|
||||
model: agent.model ?? null,
|
||||
};
|
||||
};
|
||||
}
|
||||
@@ -1352,10 +1381,57 @@ function ComposerContentImpl({
|
||||
const { settings: appSettings } = useAppSettings();
|
||||
|
||||
const agentState = useSessionStore(useShallow(buildAgentStateSelector(serverId, agentId)));
|
||||
const supportsProviderSwitching = useSessionStore(
|
||||
(state) => state.sessions[serverId]?.serverInfo?.features?.providerSwitching === true,
|
||||
);
|
||||
const rawStagedSwitch = useStagedProviderSwitch(serverId, agentId);
|
||||
const isStagedSwitchInFlight = useIsStagedProviderSwitchInFlight(serverId, agentId);
|
||||
const failedStartupSettings = useFailedStartupSettings(serverId, agentId);
|
||||
const stagedSwitch =
|
||||
supportsProviderSwitching &&
|
||||
rawStagedSwitch &&
|
||||
agentState.provider &&
|
||||
rawStagedSwitch.provider !== agentState.provider
|
||||
? rawStagedSwitch
|
||||
: null;
|
||||
const { entries: providerSnapshotEntries } = useProvidersSnapshot(serverId, { cwd });
|
||||
const stagedProviderLabel = stagedSwitch
|
||||
? resolveProviderLabel(stagedSwitch.provider, providerSnapshotEntries)
|
||||
: null;
|
||||
|
||||
useEffect(() => {
|
||||
if (
|
||||
rawStagedSwitch &&
|
||||
agentState.provider &&
|
||||
rawStagedSwitch.provider === agentState.provider &&
|
||||
!isStagedProviderSwitchInFlight(serverId, agentId)
|
||||
) {
|
||||
clearStagedProviderSwitch(serverId, agentId);
|
||||
}
|
||||
}, [agentId, agentState.provider, rawStagedSwitch, serverId]);
|
||||
|
||||
const handleCancelStagedSwitch = useCallback(() => {
|
||||
clearStagedProviderSwitch(serverId, agentId);
|
||||
setSendError(null);
|
||||
useSessionStore.getState().setQueuedSendError(serverId, agentId, null);
|
||||
}, [agentId, serverId]);
|
||||
|
||||
const handleRetryFailedStartupSettings = useCallback(() => {
|
||||
setSendError(null);
|
||||
void getHostRuntimeStore().recoverFailedStartupSettings(serverId, agentId, "retry");
|
||||
}, [agentId, serverId]);
|
||||
|
||||
const handleDismissFailedStartupSettings = useCallback(() => {
|
||||
setSendError(null);
|
||||
void getHostRuntimeStore().recoverFailedStartupSettings(serverId, agentId, "discard");
|
||||
}, [agentId, serverId]);
|
||||
|
||||
const queuedMessagesRaw = useSessionStore((state) =>
|
||||
state.sessions[serverId]?.queuedMessages?.get(agentId),
|
||||
);
|
||||
const queuedSendError = useSessionStore(
|
||||
(state) => state.sessions[serverId]?.queuedSendErrors?.get(agentId) ?? null,
|
||||
);
|
||||
const queuedMessages = queuedMessagesRaw ?? EMPTY_ARRAY;
|
||||
|
||||
const setQueuedMessages = useSessionStore((state) => state.setQueuedMessages);
|
||||
@@ -1719,24 +1795,63 @@ function ComposerContentImpl({
|
||||
if (!client) {
|
||||
throw new Error(t("workspace.terminal.hostDisconnected"));
|
||||
}
|
||||
await dispatchComposerAgentMessage({
|
||||
client,
|
||||
agentId: targetAgentId,
|
||||
text,
|
||||
attachments: sendAttachments,
|
||||
attachmentSubmitFormat: resolveComposerAttachmentSubmitFormat({
|
||||
supportsForgeAttachments: supportsForgeSearch,
|
||||
}),
|
||||
submission: createMessageSubmissionWriter(serverId),
|
||||
activeTurnBehavior,
|
||||
activeTurnId:
|
||||
activeTurnBehavior === "steer"
|
||||
? (selectAgentTurnPresentation(
|
||||
useSessionStore.getState().sessions[serverId],
|
||||
targetAgentId,
|
||||
).turnId ?? undefined)
|
||||
: undefined,
|
||||
});
|
||||
const sessionState = useSessionStore.getState().sessions[serverId];
|
||||
const liveProvider = sessionState?.agents.get(targetAgentId)?.provider;
|
||||
const canSwitch = sessionState?.serverInfo?.features?.providerSwitching === true;
|
||||
const pendingSwitch = canSwitch ? getStagedProviderSwitch(serverId, targetAgentId) : null;
|
||||
const stagedProviderSwitch =
|
||||
pendingSwitch && pendingSwitch.provider !== liveProvider ? pendingSwitch : null;
|
||||
useSessionStore.getState().setQueuedSendError(serverId, targetAgentId, null);
|
||||
if (stagedProviderSwitch) {
|
||||
beginStagedProviderSwitch(serverId, targetAgentId);
|
||||
}
|
||||
try {
|
||||
await dispatchComposerAgentMessage({
|
||||
client,
|
||||
agentId: targetAgentId,
|
||||
text,
|
||||
attachments: sendAttachments,
|
||||
attachmentSubmitFormat: resolveComposerAttachmentSubmitFormat({
|
||||
supportsForgeAttachments: supportsForgeSearch,
|
||||
}),
|
||||
submission: createMessageSubmissionWriter(serverId),
|
||||
currentProvider: liveProvider ?? null,
|
||||
currentModel: sessionState?.agents.get(targetAgentId)?.model ?? null,
|
||||
stagedProviderSwitch,
|
||||
onProviderSwitchCommitted: async (agent) => {
|
||||
if (agent) {
|
||||
getHostRuntimeStore().tryAcceptAgentSnapshot(
|
||||
serverId,
|
||||
normalizeAgentSnapshot(agent, serverId),
|
||||
);
|
||||
}
|
||||
if (stagedProviderSwitch) {
|
||||
const settled = await settleCommittedProviderSwitch({
|
||||
serverId,
|
||||
agentId: targetAgentId,
|
||||
sentDraft: stagedProviderSwitch,
|
||||
committedProvider: agent?.provider ?? null,
|
||||
client,
|
||||
});
|
||||
if (!settled.applied) {
|
||||
setSendError(settled.errorMessage);
|
||||
}
|
||||
}
|
||||
},
|
||||
activeTurnBehavior,
|
||||
activeTurnId:
|
||||
activeTurnBehavior === "steer"
|
||||
? (selectAgentTurnPresentation(
|
||||
useSessionStore.getState().sessions[serverId],
|
||||
targetAgentId,
|
||||
).turnId ?? undefined)
|
||||
: undefined,
|
||||
});
|
||||
} finally {
|
||||
if (stagedProviderSwitch) {
|
||||
endStagedProviderSwitch(serverId, targetAgentId);
|
||||
}
|
||||
}
|
||||
onAttentionPromptSend?.();
|
||||
};
|
||||
}, [appSettings.sendBehavior, client, onAttentionPromptSend, serverId, supportsForgeSearch, t]);
|
||||
@@ -1812,7 +1927,7 @@ function ComposerContentImpl({
|
||||
attachments: outgoingAttachments,
|
||||
hasExternalContent,
|
||||
allowEmptySubmit,
|
||||
forceSend,
|
||||
forceSend: stagedSwitch && isAgentRunning ? false : forceSend,
|
||||
submitBehavior,
|
||||
isAgentRunning,
|
||||
// Parent-managed submits are still valid submit paths even when the
|
||||
@@ -1854,6 +1969,7 @@ function ComposerContentImpl({
|
||||
queueMessage,
|
||||
setSelectedAttachments,
|
||||
replaceUserInput,
|
||||
stagedSwitch,
|
||||
submitBehavior,
|
||||
submitMessage,
|
||||
t,
|
||||
@@ -2106,15 +2222,17 @@ function ComposerContentImpl({
|
||||
queue: queueWriter,
|
||||
});
|
||||
if (!result) return;
|
||||
useSessionStore.getState().setQueuedSendError(serverId, agentId, null);
|
||||
replaceUserInput(result.text);
|
||||
setSelectedAttachments(result.attachments);
|
||||
},
|
||||
[agentId, queueWriter, replaceUserInput, setSelectedAttachments],
|
||||
[agentId, queueWriter, replaceUserInput, serverId, setSelectedAttachments],
|
||||
);
|
||||
|
||||
const handleSendQueuedNow = useCallback(
|
||||
async (id: string) => {
|
||||
if (!sendAgentMessageRef.current && !onSubmitMessageRef.current) return;
|
||||
useSessionStore.getState().setQueuedSendError(serverId, agentId, null);
|
||||
// Reuse the regular send path; server-side send atomically interrupts any active run.
|
||||
const result = await sendQueuedComposerMessageNow({
|
||||
agentId,
|
||||
@@ -2128,7 +2246,7 @@ function ComposerContentImpl({
|
||||
setSendError(result.errorMessage);
|
||||
}
|
||||
},
|
||||
[agentId, queueWriter, submitMessage, t],
|
||||
[agentId, queueWriter, serverId, submitMessage, t],
|
||||
);
|
||||
|
||||
const handleQueue = useCallback(
|
||||
@@ -2581,18 +2699,78 @@ function ComposerContentImpl({
|
||||
// Focusing the composer on a touch screen raises the on-screen keyboard over the conversation.
|
||||
const messageInputAutoFocus = autoFocus && isDesktopWebBreakpoint && hasFinePointer;
|
||||
const submitLoadingPressHandler = isAgentRunning ? handleCancelAgent : undefined;
|
||||
const displayError = externalError || sendError;
|
||||
const displayError =
|
||||
externalError || sendError || failedStartupSettings?.errorMessage || queuedSendError;
|
||||
const sendErrorNode = useMemo(
|
||||
() =>
|
||||
displayError ? (
|
||||
<Alert variant="error" size="sm" description={displayError} testID="composer-error" />
|
||||
<Alert variant="error" size="sm" description={displayError} testID="composer-error">
|
||||
{failedStartupSettings ? (
|
||||
<>
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
onPress={handleRetryFailedStartupSettings}
|
||||
testID="retry-failed-startup-settings"
|
||||
>
|
||||
{t("common.actions.retry")}
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onPress={handleDismissFailedStartupSettings}
|
||||
testID="dismiss-failed-startup-settings"
|
||||
>
|
||||
{t("common.actions.dismiss")}
|
||||
</Button>
|
||||
</>
|
||||
) : null}
|
||||
</Alert>
|
||||
) : null,
|
||||
[displayError],
|
||||
[
|
||||
displayError,
|
||||
failedStartupSettings,
|
||||
handleDismissFailedStartupSettings,
|
||||
handleRetryFailedStartupSettings,
|
||||
t,
|
||||
],
|
||||
);
|
||||
const githubEmptyText = githubSearchResultsQuery.isFetching
|
||||
? t("composer.github.searching")
|
||||
: t("composer.github.noResults");
|
||||
|
||||
const stagedSwitchBannerNode = useMemo(() => {
|
||||
if (!stagedSwitch || !stagedProviderLabel || isStagedSwitchInFlight) return null;
|
||||
const message = isAgentRunning
|
||||
? t("composer.providerSwitch.switchingAfterTurn", { provider: stagedProviderLabel })
|
||||
: t("composer.providerSwitch.switchingNextMessage", { provider: stagedProviderLabel });
|
||||
return (
|
||||
<View style={styles.stagedSwitchBanner} testID="staged-provider-switch-banner">
|
||||
<View style={styles.stagedSwitchLabelRow}>
|
||||
<ThemedArrowRightLeft size={ICON_SIZE.sm} uniProps={iconForegroundMutedMapping} />
|
||||
<Text style={styles.stagedSwitchText} numberOfLines={1}>
|
||||
{message}
|
||||
</Text>
|
||||
</View>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onPress={handleCancelStagedSwitch}
|
||||
testID="cancel-staged-provider-switch"
|
||||
>
|
||||
{t("common.actions.cancel")}
|
||||
</Button>
|
||||
</View>
|
||||
);
|
||||
}, [
|
||||
handleCancelStagedSwitch,
|
||||
isAgentRunning,
|
||||
isStagedSwitchInFlight,
|
||||
stagedProviderLabel,
|
||||
stagedSwitch,
|
||||
t,
|
||||
]);
|
||||
|
||||
return (
|
||||
<>
|
||||
<ComposerKeyboardRegistration
|
||||
@@ -2618,6 +2796,7 @@ function ComposerContentImpl({
|
||||
>
|
||||
<View style={inputAreaContentStyle}>
|
||||
{isFullscreen ? null : queueList}
|
||||
{isFullscreen ? null : stagedSwitchBannerNode}
|
||||
{!isFullscreen && sendErrorNode}
|
||||
|
||||
<ComposerAutocompleteBinding
|
||||
@@ -2873,9 +3052,35 @@ const styles = StyleSheet.create((theme: Theme) => ({
|
||||
queueSendButton: {
|
||||
backgroundColor: theme.colors.accent,
|
||||
},
|
||||
stagedSwitchBanner: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
justifyContent: "space-between",
|
||||
paddingLeft: theme.spacing[3],
|
||||
paddingRight: theme.spacing[1.5],
|
||||
paddingVertical: theme.spacing[1],
|
||||
backgroundColor: theme.colors.surface1,
|
||||
borderRadius: theme.borderRadius.md,
|
||||
borderWidth: theme.borderWidth[1],
|
||||
borderColor: theme.colors.border,
|
||||
gap: theme.spacing[2],
|
||||
},
|
||||
stagedSwitchLabelRow: {
|
||||
flex: 1,
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: theme.spacing[1.5],
|
||||
minWidth: 0,
|
||||
},
|
||||
stagedSwitchText: {
|
||||
flex: 1,
|
||||
fontSize: theme.fontSize.sm,
|
||||
color: theme.colors.foregroundMuted,
|
||||
},
|
||||
})) as unknown as Record<string, object>;
|
||||
|
||||
const ThemedAttachmentSpinner = withUnistyles(LoadingSpinner);
|
||||
const ThemedArrowRightLeft = withUnistyles(ArrowRightLeft);
|
||||
const ThemedPencil = withUnistyles(Pencil);
|
||||
const ThemedArrowUp = withUnistyles(ArrowUp);
|
||||
const ThemedGitPullRequest = withUnistyles(GitPullRequest);
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
import React, { act, useCallback, useMemo, useRef, useState, type FormEvent } from "react";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { expect, it } from "vitest";
|
||||
import { useComposerHeight } from "./height.web";
|
||||
|
||||
it("keeps height measurement bounded when editing a long multiline draft", () => {
|
||||
function Composer() {
|
||||
const textarea = useRef<HTMLTextAreaElement>(null);
|
||||
const [renderedLines, setRenderedLines] = useState(1);
|
||||
const getText = useCallback(() => textarea.current?.value ?? "", []);
|
||||
const sizing = useComposerHeight({
|
||||
getText,
|
||||
textareaRef: textarea,
|
||||
minHeight: 24,
|
||||
maxHeight: 96,
|
||||
onRenderedLinesChange: setRenderedLines,
|
||||
});
|
||||
if (sizing.mode !== "measured") throw new Error("Expected web height measurement");
|
||||
|
||||
const { onTextChange } = sizing;
|
||||
const edit = useCallback(
|
||||
(event: FormEvent<HTMLTextAreaElement>) => onTextChange("", event.currentTarget.value),
|
||||
[onTextChange],
|
||||
);
|
||||
const style = useMemo(
|
||||
() => ({ height: Number(sizing.style.height), width: 400, lineHeight: "20px" }),
|
||||
[sizing.style.height],
|
||||
);
|
||||
|
||||
return (
|
||||
<textarea ref={textarea} onInput={edit} style={style} data-multiline={renderedLines > 2} />
|
||||
);
|
||||
}
|
||||
|
||||
const container = document.body.appendChild(document.createElement("div"));
|
||||
const root = createRoot(container);
|
||||
try {
|
||||
act(() => root.render(<Composer />));
|
||||
const editor = container.querySelector("textarea")!;
|
||||
const draft = "Review the resulting change.\n".repeat(9_000);
|
||||
|
||||
function replaceText(text: string) {
|
||||
act(() => {
|
||||
editor.value = text;
|
||||
editor.dispatchEvent(new InputEvent("input", { bubbles: true }));
|
||||
});
|
||||
}
|
||||
|
||||
replaceText(draft);
|
||||
replaceText(draft + "x");
|
||||
|
||||
expect(editor.value).toBe(draft + "x");
|
||||
expect(editor.style.height).toBe("96px");
|
||||
expect(editor.dataset.multiline).toBe("true");
|
||||
const measurement = document.querySelector<HTMLTextAreaElement>(
|
||||
'textarea[aria-hidden="true"]',
|
||||
)!;
|
||||
expect(measurement.value.length).toBeLessThan(400);
|
||||
|
||||
replaceText("Short draft");
|
||||
expect(editor.style.height).toBe("24px");
|
||||
expect(editor.dataset.multiline).toBe("false");
|
||||
} finally {
|
||||
act(() => root.unmount());
|
||||
container.remove();
|
||||
}
|
||||
});
|
||||
@@ -33,6 +33,15 @@ const COPIED_STYLES = [
|
||||
"paddingLeft",
|
||||
] as const;
|
||||
|
||||
function prefixThroughHardLines(text: string, lines: number): string {
|
||||
let lineEnd = -1;
|
||||
for (let line = 0; line < lines; line += 1) {
|
||||
lineEnd = text.indexOf("\n", lineEnd + 1);
|
||||
if (lineEnd === -1) return text;
|
||||
}
|
||||
return text.slice(0, lineEnd + 1);
|
||||
}
|
||||
|
||||
export function useComposerHeight({
|
||||
getText,
|
||||
textareaRef,
|
||||
@@ -68,15 +77,29 @@ export function useComposerHeight({
|
||||
mirror.style[property] = computedStyle[property];
|
||||
}
|
||||
mirror.style.width = `${sourceWidth}px`;
|
||||
mirror.value = text.endsWith("\n") ? `${text} ` : text;
|
||||
const padding =
|
||||
parseFloat(computedStyle.paddingTop) + parseFloat(computedStyle.paddingBottom);
|
||||
const lineHeight = parseFloat(computedStyle.lineHeight);
|
||||
if (lineHeight > 0)
|
||||
paramsRef.current.onRenderedLinesChange?.(
|
||||
Math.round((mirror.scrollHeight - padding) / lineHeight),
|
||||
);
|
||||
setBoundedHeight(mirror.scrollHeight);
|
||||
const { maxHeight: currentMax, onRenderedLinesChange: reportLines } = paramsRef.current;
|
||||
// Complete hard lines can prove the height cap and the three-line fullscreen threshold.
|
||||
// Keep measuring the whole draft when the prefix cannot prove both.
|
||||
const measuredText =
|
||||
Number.isFinite(currentMax) && lineHeight > 0
|
||||
? prefixThroughHardLines(
|
||||
text,
|
||||
Math.max(3, Math.ceil((currentMax - padding) / lineHeight)),
|
||||
)
|
||||
: text;
|
||||
mirror.value = measuredText.endsWith("\n") ? `${measuredText} ` : measuredText;
|
||||
let scrollHeight = mirror.scrollHeight;
|
||||
if (measuredText !== text && scrollHeight < currentMax) {
|
||||
mirror.value = text.endsWith("\n") ? `${text} ` : text;
|
||||
scrollHeight = mirror.scrollHeight;
|
||||
}
|
||||
if (lineHeight > 0) {
|
||||
reportLines?.(Math.round((scrollHeight - padding) / lineHeight));
|
||||
}
|
||||
setBoundedHeight(scrollHeight);
|
||||
},
|
||||
[setBoundedHeight, textareaRef],
|
||||
);
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
export {
|
||||
applyFailedStartupSettings,
|
||||
beginStagedProviderSwitch,
|
||||
clearStagedProviderSwitch,
|
||||
discardFailedStartupSettings,
|
||||
endStagedProviderSwitch,
|
||||
getFailedStartupSettings,
|
||||
getStagedProviderSwitch,
|
||||
isStagedProviderSwitchInFlight,
|
||||
settleCommittedProviderSwitch,
|
||||
settleStagedProviderSwitch,
|
||||
useFailedStartupSettings,
|
||||
useIsStagedProviderSwitchInFlight,
|
||||
useStagedProviderSwitch,
|
||||
useStagedProviderSwitchStore,
|
||||
type FailedStartupSettings,
|
||||
type LiveAgentSettingsWriter,
|
||||
type SettleCommittedProviderSwitchResult,
|
||||
type StagedProviderSwitch,
|
||||
} from "./store";
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,86 @@
|
||||
import { beforeEach, describe, expect, it } from "vitest";
|
||||
import {
|
||||
clearStagedProviderSwitch,
|
||||
getStagedProviderSwitch,
|
||||
settleStagedProviderSwitch,
|
||||
useStagedProviderSwitchStore,
|
||||
} from "./index";
|
||||
|
||||
describe("staged provider switch store", () => {
|
||||
beforeEach(() => {
|
||||
useStagedProviderSwitchStore.setState({ stagedByKey: new Map() });
|
||||
});
|
||||
|
||||
it("stages, patches, and clears per server and agent", () => {
|
||||
const store = useStagedProviderSwitchStore.getState();
|
||||
store.stage("srv-1", "agent-1", {
|
||||
provider: "codex",
|
||||
model: "gpt-5.4",
|
||||
thinkingOptionId: "high",
|
||||
modeId: "auto",
|
||||
providerOptions: { fast_mode: true },
|
||||
});
|
||||
store.stage("srv-1", "agent-2", {
|
||||
provider: "opencode",
|
||||
model: null,
|
||||
thinkingOptionId: null,
|
||||
modeId: null,
|
||||
providerOptions: {},
|
||||
});
|
||||
|
||||
expect(getStagedProviderSwitch("srv-1", "agent-1")).toEqual({
|
||||
provider: "codex",
|
||||
model: "gpt-5.4",
|
||||
thinkingOptionId: "high",
|
||||
modeId: "auto",
|
||||
providerOptions: { fast_mode: true },
|
||||
});
|
||||
|
||||
store.patch("srv-1", "agent-1", (current) => ({
|
||||
...current,
|
||||
thinkingOptionId: "medium",
|
||||
}));
|
||||
expect(getStagedProviderSwitch("srv-1", "agent-1")?.thinkingOptionId).toBe("medium");
|
||||
|
||||
clearStagedProviderSwitch("srv-1", "agent-1");
|
||||
expect(getStagedProviderSwitch("srv-1", "agent-1")).toBeNull();
|
||||
expect(getStagedProviderSwitch("srv-1", "agent-2")?.provider).toBe("opencode");
|
||||
|
||||
store.clearForServer("srv-1");
|
||||
expect(getStagedProviderSwitch("srv-1", "agent-2")).toBeNull();
|
||||
});
|
||||
|
||||
it("settles only the draft that was sent and preserves any newer selection or edit", () => {
|
||||
const store = useStagedProviderSwitchStore.getState();
|
||||
store.stage("srv-1", "agent-1", {
|
||||
provider: "codex",
|
||||
model: "gpt-5.4",
|
||||
thinkingOptionId: null,
|
||||
modeId: null,
|
||||
providerOptions: {},
|
||||
});
|
||||
const sentDraft = getStagedProviderSwitch("srv-1", "agent-1")!;
|
||||
|
||||
// User chooses Copilot before Codex reply returns -> settling Codex draft preserves Copilot.
|
||||
store.stage("srv-1", "agent-1", {
|
||||
provider: "copilot",
|
||||
model: "gpt-5",
|
||||
thinkingOptionId: null,
|
||||
modeId: null,
|
||||
providerOptions: {},
|
||||
});
|
||||
settleStagedProviderSwitch("srv-1", "agent-1", sentDraft);
|
||||
const copilotDraft = getStagedProviderSwitch("srv-1", "agent-1")!;
|
||||
expect(copilotDraft.provider).toBe("copilot");
|
||||
|
||||
// Patching the draft also produces a newer revision that settling the older reference preserves.
|
||||
store.patch("srv-1", "agent-1", (current) => ({ ...current, thinkingOptionId: "high" }));
|
||||
settleStagedProviderSwitch("srv-1", "agent-1", copilotDraft);
|
||||
const patchedCopilot = getStagedProviderSwitch("srv-1", "agent-1")!;
|
||||
expect(patchedCopilot.thinkingOptionId).toBe("high");
|
||||
|
||||
// Settling the current draft clears it cleanly.
|
||||
settleStagedProviderSwitch("srv-1", "agent-1", patchedCopilot);
|
||||
expect(getStagedProviderSwitch("srv-1", "agent-1")).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,407 @@
|
||||
import { create } from "zustand";
|
||||
import type { AgentProvider, ProviderOptions } from "@getpaseo/protocol/agent-types";
|
||||
import type { AgentConfigApply } from "@getpaseo/protocol/messages";
|
||||
|
||||
export interface StagedProviderSwitch {
|
||||
provider: AgentProvider;
|
||||
model: string | null;
|
||||
thinkingOptionId: string | null;
|
||||
modeId: string | null;
|
||||
providerOptions: ProviderOptions;
|
||||
}
|
||||
|
||||
function stagedKey(serverId: string, agentId: string): string {
|
||||
return `${serverId}:${agentId}`;
|
||||
}
|
||||
|
||||
export interface LiveAgentSettingsWriter {
|
||||
applyAgentConfig?: (
|
||||
agentId: string,
|
||||
config: AgentConfigApply,
|
||||
options?: { expectedProvider?: AgentProvider },
|
||||
) => Promise<unknown>;
|
||||
setAgentModel?: (
|
||||
agentId: string,
|
||||
modelId: string | null,
|
||||
options?: { expectedProvider?: AgentProvider },
|
||||
) => Promise<unknown>;
|
||||
setAgentMode?: (
|
||||
agentId: string,
|
||||
modeId: string,
|
||||
options?: { expectedProvider?: AgentProvider },
|
||||
) => Promise<unknown>;
|
||||
setAgentThinkingOption?: (
|
||||
agentId: string,
|
||||
thinkingOptionId: string,
|
||||
options?: { expectedProvider?: AgentProvider },
|
||||
) => Promise<unknown>;
|
||||
setAgentOptions?: (
|
||||
agentId: string,
|
||||
options: ProviderOptions,
|
||||
mutationOptions?: { expectedProvider?: AgentProvider },
|
||||
) => Promise<unknown>;
|
||||
}
|
||||
|
||||
export interface FailedStartupSettings {
|
||||
provider: AgentProvider;
|
||||
bundle: AgentConfigApply;
|
||||
errorMessage: string;
|
||||
}
|
||||
|
||||
export type SettleCommittedProviderSwitchResult =
|
||||
| { applied: true }
|
||||
| { applied: false; errorMessage: string };
|
||||
|
||||
interface StagedProviderSwitchState {
|
||||
stagedByKey: Map<string, StagedProviderSwitch>;
|
||||
inFlightByKey: Map<string, number>;
|
||||
failedStartupSettingsByKey: Map<string, FailedStartupSettings>;
|
||||
stage: (serverId: string, agentId: string, draft: StagedProviderSwitch) => void;
|
||||
patch: (
|
||||
serverId: string,
|
||||
agentId: string,
|
||||
updater: (current: StagedProviderSwitch) => StagedProviderSwitch,
|
||||
) => void;
|
||||
beginSwitch: (serverId: string, agentId: string) => void;
|
||||
endSwitch: (serverId: string, agentId: string) => void;
|
||||
setFailedStartupSettings: (
|
||||
serverId: string,
|
||||
agentId: string,
|
||||
failed: FailedStartupSettings | null,
|
||||
) => void;
|
||||
settle: (serverId: string, agentId: string, sentDraft: StagedProviderSwitch) => void;
|
||||
clear: (serverId: string, agentId: string) => void;
|
||||
clearForServer: (serverId: string) => void;
|
||||
}
|
||||
|
||||
export const useStagedProviderSwitchStore = create<StagedProviderSwitchState>((set) => ({
|
||||
stagedByKey: new Map(),
|
||||
inFlightByKey: new Map(),
|
||||
failedStartupSettingsByKey: new Map(),
|
||||
|
||||
stage: (serverId, agentId, draft) =>
|
||||
set((state) => {
|
||||
const next = new Map(state.stagedByKey);
|
||||
next.set(stagedKey(serverId, agentId), draft);
|
||||
return { stagedByKey: next };
|
||||
}),
|
||||
|
||||
patch: (serverId, agentId, updater) =>
|
||||
set((state) => {
|
||||
const key = stagedKey(serverId, agentId);
|
||||
const current = state.stagedByKey.get(key);
|
||||
if (!current) return state;
|
||||
const updated = updater(current);
|
||||
if (updated === current) return state;
|
||||
const next = new Map(state.stagedByKey);
|
||||
next.set(key, updated);
|
||||
return { stagedByKey: next };
|
||||
}),
|
||||
|
||||
beginSwitch: (serverId, agentId) =>
|
||||
set((state) => {
|
||||
const key = stagedKey(serverId, agentId);
|
||||
const next = new Map(state.inFlightByKey);
|
||||
next.set(key, (next.get(key) ?? 0) + 1);
|
||||
return { inFlightByKey: next };
|
||||
}),
|
||||
|
||||
endSwitch: (serverId, agentId) =>
|
||||
set((state) => {
|
||||
const key = stagedKey(serverId, agentId);
|
||||
const count = state.inFlightByKey.get(key) ?? 0;
|
||||
if (count <= 0) return state;
|
||||
const next = new Map(state.inFlightByKey);
|
||||
if (count === 1) {
|
||||
next.delete(key);
|
||||
} else {
|
||||
next.set(key, count - 1);
|
||||
}
|
||||
return { inFlightByKey: next };
|
||||
}),
|
||||
|
||||
setFailedStartupSettings: (serverId, agentId, failed) =>
|
||||
set((state) => {
|
||||
const key = stagedKey(serverId, agentId);
|
||||
const next = new Map(state.failedStartupSettingsByKey);
|
||||
if (failed === null) {
|
||||
if (!next.has(key)) return state;
|
||||
next.delete(key);
|
||||
} else {
|
||||
next.set(key, failed);
|
||||
}
|
||||
return { failedStartupSettingsByKey: next };
|
||||
}),
|
||||
|
||||
settle: (serverId, agentId, sentDraft) =>
|
||||
set((state) => {
|
||||
const key = stagedKey(serverId, agentId);
|
||||
const current = state.stagedByKey.get(key);
|
||||
if (!current || current !== sentDraft) return state;
|
||||
const next = new Map(state.stagedByKey);
|
||||
next.delete(key);
|
||||
return { stagedByKey: next };
|
||||
}),
|
||||
|
||||
clear: (serverId, agentId) =>
|
||||
set((state) => {
|
||||
const key = stagedKey(serverId, agentId);
|
||||
if (!state.stagedByKey.has(key)) return state;
|
||||
const next = new Map(state.stagedByKey);
|
||||
next.delete(key);
|
||||
return { stagedByKey: next };
|
||||
}),
|
||||
|
||||
clearForServer: (serverId) =>
|
||||
set((state) => {
|
||||
const prefix = `${serverId}:`;
|
||||
let changed = false;
|
||||
const next = new Map(state.stagedByKey);
|
||||
for (const key of next.keys()) {
|
||||
if (key.startsWith(prefix)) {
|
||||
next.delete(key);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
const nextInFlight = new Map(state.inFlightByKey);
|
||||
for (const key of nextInFlight.keys()) {
|
||||
if (key.startsWith(prefix)) {
|
||||
nextInFlight.delete(key);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
const nextFailed = new Map(state.failedStartupSettingsByKey);
|
||||
for (const key of nextFailed.keys()) {
|
||||
if (key.startsWith(prefix)) {
|
||||
nextFailed.delete(key);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
return changed
|
||||
? {
|
||||
stagedByKey: next,
|
||||
inFlightByKey: nextInFlight,
|
||||
failedStartupSettingsByKey: nextFailed,
|
||||
}
|
||||
: state;
|
||||
}),
|
||||
}));
|
||||
|
||||
export function getStagedProviderSwitch(
|
||||
serverId: string,
|
||||
agentId: string,
|
||||
): StagedProviderSwitch | null {
|
||||
return (
|
||||
useStagedProviderSwitchStore.getState().stagedByKey.get(stagedKey(serverId, agentId)) ?? null
|
||||
);
|
||||
}
|
||||
|
||||
export function beginStagedProviderSwitch(serverId: string, agentId: string): void {
|
||||
useStagedProviderSwitchStore.getState().beginSwitch(serverId, agentId);
|
||||
}
|
||||
|
||||
export function endStagedProviderSwitch(serverId: string, agentId: string): void {
|
||||
useStagedProviderSwitchStore.getState().endSwitch(serverId, agentId);
|
||||
}
|
||||
|
||||
export function isStagedProviderSwitchInFlight(serverId: string, agentId: string): boolean {
|
||||
return (
|
||||
(useStagedProviderSwitchStore.getState().inFlightByKey.get(stagedKey(serverId, agentId)) ?? 0) >
|
||||
0
|
||||
);
|
||||
}
|
||||
|
||||
export function getFailedStartupSettings(
|
||||
serverId: string,
|
||||
agentId: string,
|
||||
): FailedStartupSettings | null {
|
||||
return (
|
||||
useStagedProviderSwitchStore
|
||||
.getState()
|
||||
.failedStartupSettingsByKey.get(stagedKey(serverId, agentId)) ?? null
|
||||
);
|
||||
}
|
||||
|
||||
export function useFailedStartupSettings(
|
||||
serverId: string,
|
||||
agentId: string,
|
||||
): FailedStartupSettings | null {
|
||||
return useStagedProviderSwitchStore(
|
||||
(state) => state.failedStartupSettingsByKey.get(stagedKey(serverId, agentId)) ?? null,
|
||||
);
|
||||
}
|
||||
|
||||
export function discardFailedStartupSettings(serverId: string, agentId: string): void {
|
||||
useStagedProviderSwitchStore.getState().setFailedStartupSettings(serverId, agentId, null);
|
||||
}
|
||||
|
||||
export function settleStagedProviderSwitch(
|
||||
serverId: string,
|
||||
agentId: string,
|
||||
sentDraft: StagedProviderSwitch,
|
||||
): void {
|
||||
useStagedProviderSwitchStore.getState().settle(serverId, agentId, sentDraft);
|
||||
}
|
||||
|
||||
function diffProviderOptions(
|
||||
sent: ProviderOptions,
|
||||
edited: ProviderOptions,
|
||||
): ProviderOptions | null {
|
||||
const patch: ProviderOptions = {};
|
||||
let hasDiff = false;
|
||||
for (const [key, value] of Object.entries(edited)) {
|
||||
if (sent[key] !== value) {
|
||||
patch[key] = value;
|
||||
hasDiff = true;
|
||||
}
|
||||
}
|
||||
return hasDiff ? patch : null;
|
||||
}
|
||||
|
||||
function buildEditedSettingsBundle(
|
||||
sentDraft: StagedProviderSwitch,
|
||||
editedDraft: StagedProviderSwitch,
|
||||
): AgentConfigApply | null {
|
||||
const config: AgentConfigApply = {};
|
||||
let hasChanges = false;
|
||||
if (editedDraft.model !== sentDraft.model) {
|
||||
config.modelId = editedDraft.model;
|
||||
hasChanges = true;
|
||||
}
|
||||
if (editedDraft.modeId !== sentDraft.modeId && editedDraft.modeId !== null) {
|
||||
config.modeId = editedDraft.modeId;
|
||||
hasChanges = true;
|
||||
}
|
||||
if (
|
||||
editedDraft.thinkingOptionId !== sentDraft.thinkingOptionId &&
|
||||
editedDraft.thinkingOptionId !== null
|
||||
) {
|
||||
config.thinkingOptionId = editedDraft.thinkingOptionId;
|
||||
hasChanges = true;
|
||||
}
|
||||
const optionsPatch = diffProviderOptions(sentDraft.providerOptions, editedDraft.providerOptions);
|
||||
if (optionsPatch) {
|
||||
config.options = optionsPatch;
|
||||
hasChanges = true;
|
||||
}
|
||||
return hasChanges ? config : null;
|
||||
}
|
||||
|
||||
async function applyEditedDraftSettingsToLiveAgent(
|
||||
agentId: string,
|
||||
bundle: AgentConfigApply,
|
||||
expectedProvider: AgentProvider,
|
||||
client: LiveAgentSettingsWriter,
|
||||
): Promise<void> {
|
||||
const providerGuard = { expectedProvider };
|
||||
if (client.applyAgentConfig) {
|
||||
await client.applyAgentConfig(agentId, bundle, providerGuard);
|
||||
return;
|
||||
}
|
||||
if (bundle.modelId !== undefined && client.setAgentModel) {
|
||||
await client.setAgentModel(agentId, bundle.modelId, providerGuard);
|
||||
}
|
||||
if (bundle.modeId !== undefined && client.setAgentMode) {
|
||||
await client.setAgentMode(agentId, bundle.modeId, providerGuard);
|
||||
}
|
||||
if (
|
||||
bundle.thinkingOptionId !== undefined &&
|
||||
bundle.thinkingOptionId !== null &&
|
||||
client.setAgentThinkingOption
|
||||
) {
|
||||
await client.setAgentThinkingOption(agentId, bundle.thinkingOptionId, providerGuard);
|
||||
}
|
||||
if (bundle.options && client.setAgentOptions) {
|
||||
await client.setAgentOptions(agentId, bundle.options, providerGuard);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Settles the staged draft captured by a committed switch and awaits any edited settings
|
||||
* for the provider that just became live before callers release queued follow-up prompts.
|
||||
* - Untouched draft: cleared.
|
||||
* - Newer draft targeting a different provider: preserved for the next switch.
|
||||
* - Newer draft editing settings of the provider that just became live: applied atomically
|
||||
* (via `applyAgentConfig` when available, else sequential setters) before settling the draft.
|
||||
* If the daemon rejects an edit, the draft is kept intact and `{ applied: false, errorMessage }`
|
||||
* is returned so callers surface the error and hold any queued follow-up prompt.
|
||||
*/
|
||||
export async function settleCommittedProviderSwitch(input: {
|
||||
serverId: string;
|
||||
agentId: string;
|
||||
sentDraft: StagedProviderSwitch;
|
||||
committedProvider?: AgentProvider | null;
|
||||
client?: LiveAgentSettingsWriter | null;
|
||||
}): Promise<SettleCommittedProviderSwitchResult> {
|
||||
const { serverId, agentId, sentDraft, committedProvider, client } = input;
|
||||
const store = useStagedProviderSwitchStore.getState();
|
||||
store.settle(serverId, agentId, sentDraft);
|
||||
const remaining = getStagedProviderSwitch(serverId, agentId);
|
||||
const liveProvider = committedProvider ?? sentDraft.provider;
|
||||
if (!remaining || remaining.provider !== liveProvider) {
|
||||
return { applied: true };
|
||||
}
|
||||
const bundle = buildEditedSettingsBundle(sentDraft, remaining);
|
||||
if (!bundle || !client) {
|
||||
store.settle(serverId, agentId, remaining);
|
||||
return { applied: true };
|
||||
}
|
||||
try {
|
||||
await applyEditedDraftSettingsToLiveAgent(agentId, bundle, liveProvider, client);
|
||||
store.settle(serverId, agentId, remaining);
|
||||
return { applied: true };
|
||||
} catch (error) {
|
||||
const errorMessage = error instanceof Error ? error.message : String(error);
|
||||
store.settle(serverId, agentId, remaining);
|
||||
store.setFailedStartupSettings(serverId, agentId, {
|
||||
provider: liveProvider,
|
||||
bundle,
|
||||
errorMessage,
|
||||
});
|
||||
console.warn("[ProviderSwitch] failed to forward edited settings after switch", error);
|
||||
return { applied: false, errorMessage };
|
||||
}
|
||||
}
|
||||
|
||||
/** Retries applying previously failed startup settings for a committed provider switch. */
|
||||
export async function applyFailedStartupSettings(input: {
|
||||
serverId: string;
|
||||
agentId: string;
|
||||
client: LiveAgentSettingsWriter;
|
||||
}): Promise<SettleCommittedProviderSwitchResult> {
|
||||
const { serverId, agentId, client } = input;
|
||||
const failed = getFailedStartupSettings(serverId, agentId);
|
||||
if (!failed) {
|
||||
return { applied: true };
|
||||
}
|
||||
const store = useStagedProviderSwitchStore.getState();
|
||||
try {
|
||||
await applyEditedDraftSettingsToLiveAgent(agentId, failed.bundle, failed.provider, client);
|
||||
store.setFailedStartupSettings(serverId, agentId, null);
|
||||
return { applied: true };
|
||||
} catch (error) {
|
||||
const errorMessage = error instanceof Error ? error.message : String(error);
|
||||
store.setFailedStartupSettings(serverId, agentId, { ...failed, errorMessage });
|
||||
console.warn("[ProviderSwitch] failed to retry startup settings", error);
|
||||
return { applied: false, errorMessage };
|
||||
}
|
||||
}
|
||||
|
||||
export function clearStagedProviderSwitch(serverId: string, agentId: string): void {
|
||||
useStagedProviderSwitchStore.getState().clear(serverId, agentId);
|
||||
}
|
||||
|
||||
export function useStagedProviderSwitch(
|
||||
serverId: string,
|
||||
agentId: string,
|
||||
): StagedProviderSwitch | null {
|
||||
return useStagedProviderSwitchStore(
|
||||
(state) => state.stagedByKey.get(stagedKey(serverId, agentId)) ?? null,
|
||||
);
|
||||
}
|
||||
|
||||
export function useIsStagedProviderSwitchInFlight(serverId: string, agentId: string): boolean {
|
||||
return useStagedProviderSwitchStore(
|
||||
(state) => (state.inFlightByKey.get(stagedKey(serverId, agentId)) ?? 0) > 0,
|
||||
);
|
||||
}
|
||||
@@ -3,17 +3,30 @@ import { useSessionStore } from "@/stores/session-store";
|
||||
import {
|
||||
appendSubmittedUserMessage,
|
||||
removeSubmittedUserMessage,
|
||||
type ProviderSwitchItem,
|
||||
type UserMessageItem,
|
||||
} from "@/types/stream";
|
||||
|
||||
function appendUntrackedSubmission(serverId: string, agentId: string, message: UserMessageItem) {
|
||||
function appendUntrackedSubmission(
|
||||
serverId: string,
|
||||
agentId: string,
|
||||
message: UserMessageItem,
|
||||
options?: { providerSwitch?: ProviderSwitchItem },
|
||||
) {
|
||||
const session = useSessionStore.getState().sessions[serverId];
|
||||
if (!session) return;
|
||||
const tail = session.agentStreamTail.get(agentId) ?? [];
|
||||
const head = session.agentStreamHead.get(agentId) ?? [];
|
||||
useSessionStore
|
||||
.getState()
|
||||
.setAgentStreamState(serverId, agentId, appendSubmittedUserMessage({ tail, head, message }));
|
||||
useSessionStore.getState().setAgentStreamState(
|
||||
serverId,
|
||||
agentId,
|
||||
appendSubmittedUserMessage({
|
||||
tail,
|
||||
head,
|
||||
message,
|
||||
providerSwitch: options?.providerSwitch,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
function removeUntrackedSubmission(
|
||||
@@ -36,7 +49,8 @@ function removeUntrackedSubmission(
|
||||
|
||||
function createUntrackedMessageSubmissionWriter(serverId: string): MessageSubmissionWriter {
|
||||
return {
|
||||
begin: (agentId, message) => appendUntrackedSubmission(serverId, agentId, message),
|
||||
begin: (agentId, message, options) =>
|
||||
appendUntrackedSubmission(serverId, agentId, message, options),
|
||||
accept: () => undefined,
|
||||
reject: (agentId, clientMessageId) => {
|
||||
removeUntrackedSubmission(serverId, agentId, clientMessageId);
|
||||
@@ -54,8 +68,8 @@ export function createMessageSubmissionWriter(serverId: string): MessageSubmissi
|
||||
return createUntrackedMessageSubmissionWriter(serverId);
|
||||
}
|
||||
return {
|
||||
begin: (agentId, message) =>
|
||||
useSessionStore.getState().beginAgentMessageSubmission(serverId, agentId, message),
|
||||
begin: (agentId, message, options) =>
|
||||
useSessionStore.getState().beginAgentMessageSubmission(serverId, agentId, message, options),
|
||||
accept: (agentId, clientMessageId) =>
|
||||
useSessionStore.getState().acceptAgentMessageSubmission(serverId, agentId, clientMessageId),
|
||||
reject: (agentId, clientMessageId) =>
|
||||
|
||||
@@ -293,6 +293,16 @@ function SessionProviderInternal({ children, serverId, client }: SessionProvider
|
||||
console.warn("[Session] timeline replacement refresh failed", { serverId, error });
|
||||
});
|
||||
};
|
||||
const onRewind = (message: SessionOutboundMessage) => {
|
||||
if (message.type !== "agent.timeline.rewind") return;
|
||||
const { agentId, epoch, seq, retireFromSeq } = message.payload;
|
||||
sync.applyStreamEvent(agentId, {
|
||||
event: { type: "rewind", retireFromSeq },
|
||||
seq,
|
||||
epoch,
|
||||
timestamp: new Date(),
|
||||
});
|
||||
};
|
||||
const sync = getHostRuntimeStore().createViewedTimelineOwner(serverId, {
|
||||
canCheckFreshness: () =>
|
||||
client.getLastServerInfoMessage()?.features?.timelineFreshnessCheck === true,
|
||||
@@ -303,6 +313,7 @@ function SessionProviderInternal({ children, serverId, client }: SessionProvider
|
||||
update: (message) => {
|
||||
if (message.type === "agent_stream") onStream(message);
|
||||
else if (message.type === "agent.timeline.replacement") onReplacement(message);
|
||||
else if (message.type === "agent.timeline.rewind") onRewind(message);
|
||||
},
|
||||
});
|
||||
return observation;
|
||||
@@ -355,6 +366,8 @@ function SessionProviderInternal({ children, serverId, client }: SessionProvider
|
||||
viewedTimelineSyncRef.current = sync;
|
||||
setViewedTimelineSync(serverId, sync);
|
||||
sync.setActive(getIsAppVisible(appStateRef.current));
|
||||
// An online client replacement leaves isConnected unchanged, so seed each new owner.
|
||||
sync.setConnected(client.getConnectionState().status === "connected");
|
||||
const stopObservingOpenChats = observeOpenWorkspaceAgentIds(serverId, (agentIds) =>
|
||||
sync.replaceOpenTabAgentIds(agentIds),
|
||||
);
|
||||
|
||||
@@ -6,9 +6,13 @@ import { createProviderSnapshotCache, type ProviderSnapshotCache } from "./provi
|
||||
|
||||
const SNAPSHOT_KEY_PREFIX = "@paseo/provider-snapshot/v2:";
|
||||
const SNAPSHOT_INDEX_KEY = "@paseo/provider-snapshot-index/v2";
|
||||
const STORED_INDEX_KEY = "@paseo/provider-snapshot-index/v3";
|
||||
function createStorage(maxSnapshotBytes = Number.POSITIVE_INFINITY) {
|
||||
const values = new Map<string, string>();
|
||||
const stats = { getAllKeysCalls: 0 };
|
||||
const stats = { getAllKeysCalls: 0, snapshotsRead: [] as string[] };
|
||||
function recordRead(key: string) {
|
||||
if (key.startsWith(SNAPSHOT_KEY_PREFIX)) stats.snapshotsRead.push(key);
|
||||
}
|
||||
type Operation = "setItem" | "removeItem" | "multiRemove";
|
||||
let failure: { operation: Operation; timing: "before" | "after"; key?: string } | null = null;
|
||||
|
||||
@@ -31,6 +35,7 @@ function createStorage(maxSnapshotBytes = Number.POSITIVE_INFINITY) {
|
||||
failure = { operation, timing, key };
|
||||
},
|
||||
async getItem(key: string) {
|
||||
recordRead(key);
|
||||
return values.get(key) ?? null;
|
||||
},
|
||||
async setItem(key: string, value: string) {
|
||||
@@ -61,6 +66,7 @@ function createStorage(maxSnapshotBytes = Number.POSITIVE_INFINITY) {
|
||||
return [...values.keys()];
|
||||
},
|
||||
async multiGet(keys: readonly string[]) {
|
||||
keys.forEach(recordRead);
|
||||
return keys.map((key) => [key, values.get(key) ?? null] as const);
|
||||
},
|
||||
async multiRemove(keys: readonly string[]) {
|
||||
@@ -385,6 +391,62 @@ describe("provider snapshot cache", () => {
|
||||
expect(storage.stats.getAllKeysCalls).toBe(1);
|
||||
});
|
||||
|
||||
it("reads only the requested snapshot after a restart and still enforces the budget", async () => {
|
||||
const storage = createStorage();
|
||||
const cache = createProviderSnapshotCache(storage);
|
||||
for (const [day, label] of ["one", "two", "three"].entries()) {
|
||||
await writeSnapshot(cache, {
|
||||
cwd: `/${label}`,
|
||||
label,
|
||||
generatedAt: `2026-08-0${day + 1}T00:00:00.000Z`,
|
||||
});
|
||||
}
|
||||
const maxBytes = snapshotBytes(storage.values);
|
||||
storage.stats.snapshotsRead.length = 0;
|
||||
|
||||
const restarted = createProviderSnapshotCache(storage, { maxBytes });
|
||||
await expect(restarted.read("server-1", "/two")).resolves.toMatchObject({ hash: "two" });
|
||||
|
||||
expect(storage.stats.snapshotsRead).toEqual([
|
||||
`${SNAPSHOT_KEY_PREFIX}["server-1","cwd","/two"]`,
|
||||
`${SNAPSHOT_KEY_PREFIX}["server-1","hash","two"]`,
|
||||
]);
|
||||
await writeSnapshot(restarted, {
|
||||
cwd: "/four",
|
||||
label: "four",
|
||||
generatedAt: "2026-08-04T00:00:00.000Z",
|
||||
});
|
||||
await expect(restarted.read("server-1", "/one")).resolves.toBeNull();
|
||||
await expect(restarted.read("server-1", "/four")).resolves.not.toBeNull();
|
||||
expect(snapshotBytes(storage.values)).toBeLessThanOrEqual(maxBytes);
|
||||
expectConsistentSnapshots(storage.values);
|
||||
});
|
||||
|
||||
it("counts snapshots that another cache instance stored after a restart", async () => {
|
||||
const storage = createStorage();
|
||||
const first = createProviderSnapshotCache(storage);
|
||||
const second = createProviderSnapshotCache(storage);
|
||||
await second.read("server-1", "/none");
|
||||
await writeSnapshot(first, {
|
||||
cwd: "/first",
|
||||
label: "first",
|
||||
generatedAt: "2026-08-01T00:00:00.000Z",
|
||||
});
|
||||
await writeSnapshot(second, {
|
||||
cwd: "/second",
|
||||
label: "second",
|
||||
generatedAt: "2026-08-02T00:00:00.000Z",
|
||||
});
|
||||
const maxBytes = snapshotBytes(storage.values) - 1;
|
||||
|
||||
const restarted = createProviderSnapshotCache(storage, { maxBytes });
|
||||
|
||||
await expect(restarted.read("server-1", "/second")).resolves.toMatchObject({ hash: "second" });
|
||||
await expect(restarted.read("server-1", "/first")).resolves.toBeNull();
|
||||
expect(snapshotBytes(storage.values)).toBeLessThanOrEqual(maxBytes);
|
||||
expectConsistentSnapshots(storage.values);
|
||||
});
|
||||
|
||||
it("replaces an indexed snapshot without counting both versions", async () => {
|
||||
const storage = createStorage();
|
||||
const maxBytes = 1_000;
|
||||
@@ -559,6 +621,13 @@ describe("provider snapshot cache", () => {
|
||||
entries: [{ key: `${SNAPSHOT_KEY_PREFIX}phantom`, bytes: 999_999, writtenAt: "bad" }],
|
||||
}),
|
||||
);
|
||||
storage.values.set(
|
||||
STORED_INDEX_KEY,
|
||||
JSON.stringify({
|
||||
version: 3,
|
||||
entries: [{ key: `${SNAPSHOT_KEY_PREFIX}phantom`, bytes: 999_999, writtenAt: "bad" }],
|
||||
}),
|
||||
);
|
||||
|
||||
const restarted = createProviderSnapshotCache(storage, { maxBytes });
|
||||
await writeSnapshot(restarted, {
|
||||
|
||||
@@ -15,7 +15,8 @@ type SnapshotPayload = GetProvidersSnapshotResponseMessage["payload"];
|
||||
|
||||
const CACHE_VERSION = 2;
|
||||
const CACHE_KEY_PREFIX = "@paseo/provider-snapshot/v2";
|
||||
const CACHE_INDEX_KEY = "@paseo/provider-snapshot-index/v2";
|
||||
const CACHE_INDEX_VERSION = 3;
|
||||
const CACHE_INDEX_KEY = "@paseo/provider-snapshot-index/v3";
|
||||
const DEFAULT_MAX_CACHE_BYTES = 4 * 1024 * 1024;
|
||||
|
||||
interface ProviderSnapshotStorage {
|
||||
@@ -43,8 +44,22 @@ interface ProviderSnapshotIndexEntry {
|
||||
key: string;
|
||||
bytes: number;
|
||||
writtenAt: string;
|
||||
// A directory association names the body it depends on.
|
||||
body?: string;
|
||||
}
|
||||
|
||||
const ProviderSnapshotIndexSchema = z.object({
|
||||
version: z.literal(CACHE_INDEX_VERSION),
|
||||
entries: z.array(
|
||||
z.object({
|
||||
key: z.string(),
|
||||
bytes: z.number(),
|
||||
writtenAt: z.string(),
|
||||
body: z.string().optional(),
|
||||
}),
|
||||
),
|
||||
});
|
||||
|
||||
const StoredProviderSnapshotSchema: z.ZodType<StoredProviderSnapshot> = z.strictObject({
|
||||
version: z.literal(CACHE_VERSION),
|
||||
hash: z.string(),
|
||||
@@ -109,14 +124,26 @@ function decodeCacheKey(key: string) {
|
||||
return CacheKeySchema.parse(JSON.parse(key.slice(CACHE_KEY_PREFIX.length + 1)));
|
||||
}
|
||||
|
||||
// Timestamps and keys are machine strings: code-unit order is the intended order, and it spares
|
||||
// a collator call per comparison.
|
||||
function oldestFirst(left: ProviderSnapshotIndexEntry, right: ProviderSnapshotIndexEntry): number {
|
||||
const writtenAtOrder = left.writtenAt.localeCompare(right.writtenAt);
|
||||
if (writtenAtOrder !== 0) return writtenAtOrder;
|
||||
if (left.writtenAt !== right.writtenAt) return left.writtenAt < right.writtenAt ? -1 : 1;
|
||||
// References must be evicted before equally recent bodies, regardless of key encoding.
|
||||
const leftKind = decodeCacheKey(left.key)[1];
|
||||
const rightKind = decodeCacheKey(right.key)[1];
|
||||
if (leftKind !== rightKind) return leftKind === "cwd" ? -1 : 1;
|
||||
return left.key.localeCompare(right.key);
|
||||
const leftIsReference = left.body !== undefined;
|
||||
if (leftIsReference !== (right.body !== undefined)) return leftIsReference ? -1 : 1;
|
||||
if (left.key === right.key) return 0;
|
||||
return left.key < right.key ? -1 : 1;
|
||||
}
|
||||
|
||||
function parseStoredIndex(value: string | null): ProviderSnapshotIndexEntry[] {
|
||||
if (value === null) return [];
|
||||
try {
|
||||
const result = ProviderSnapshotIndexSchema.safeParse(JSON.parse(value));
|
||||
return result.success ? result.data.entries : [];
|
||||
} catch (error) {
|
||||
if (!(error instanceof SyntaxError)) throw error;
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
function parseStoredProviderSnapshot(key: string, value: string): StoredProviderSnapshot | null {
|
||||
@@ -135,9 +162,23 @@ export function createProviderSnapshotCache(
|
||||
): ProviderSnapshotCache {
|
||||
const maxBytes = options.maxBytes ?? DEFAULT_MAX_CACHE_BYTES;
|
||||
let index: ProviderSnapshotIndexEntry[] | null = null;
|
||||
// The index value last read from or written to storage.
|
||||
let storedIndex: string | null = null;
|
||||
let operationQueue = Promise.resolve();
|
||||
const bodies = new Map<string, CachedProviderSnapshot>();
|
||||
|
||||
// The stored index spares a restart from reading every snapshot to learn its size and age.
|
||||
// Storage keys stay the authority on what exists: an indexed key that is gone is dropped, and
|
||||
// a stored key the index does not list is read and measured here.
|
||||
async function commitIndex(entries: ProviderSnapshotIndexEntry[]): Promise<void> {
|
||||
const serialized = JSON.stringify({ version: CACHE_INDEX_VERSION, entries });
|
||||
if (serialized !== storedIndex) {
|
||||
await storage.setItem(CACHE_INDEX_KEY, serialized);
|
||||
storedIndex = serialized;
|
||||
}
|
||||
index = entries;
|
||||
}
|
||||
|
||||
async function reconcileCache(): Promise<void> {
|
||||
const allKeys = await storage.getAllKeys();
|
||||
// COMPAT(providerSnapshotCache): added in v0.7.2, remove legacy cleanup after 2027-03-06.
|
||||
@@ -145,14 +186,17 @@ export function createProviderSnapshotCache(
|
||||
(key) =>
|
||||
key.startsWith("@paseo/provider-snapshot/v1:") ||
|
||||
key === "@paseo/provider-snapshot-index/v1" ||
|
||||
key === CACHE_INDEX_KEY,
|
||||
key === "@paseo/provider-snapshot-index/v2",
|
||||
);
|
||||
if (legacyKeys.length) await storage.multiRemove(legacyKeys);
|
||||
const keys = allKeys.filter((key) => key.startsWith(`${CACHE_KEY_PREFIX}:`));
|
||||
const values = await storage.multiGet(keys);
|
||||
storedIndex = allKeys.includes(CACHE_INDEX_KEY) ? await storage.getItem(CACHE_INDEX_KEY) : null;
|
||||
const storedKeys = new Set(keys);
|
||||
const entries = parseStoredIndex(storedIndex).filter((entry) => storedKeys.has(entry.key));
|
||||
const indexedKeys = new Set(entries.map((entry) => entry.key));
|
||||
const unindexedKeys = keys.filter((key) => !indexedKeys.has(key));
|
||||
const values = unindexedKeys.length > 0 ? await storage.multiGet(unindexedKeys) : [];
|
||||
const keysToRemove: string[] = [];
|
||||
const entries: ProviderSnapshotIndexEntry[] = [];
|
||||
const references: Array<{ key: string; body: string; writtenAt: string }> = [];
|
||||
for (const [key, value] of values) {
|
||||
if (value === null) continue;
|
||||
try {
|
||||
@@ -162,13 +206,12 @@ export function createProviderSnapshotCache(
|
||||
continue;
|
||||
}
|
||||
const [serverId, kind] = decodeCacheKey(key);
|
||||
entries.push({ key, bytes: storedBytes(key, value), writtenAt: stored.generatedAt });
|
||||
if (kind === "cwd")
|
||||
references.push({
|
||||
key,
|
||||
body: bodyKey(serverId, stored.hash),
|
||||
writtenAt: stored.generatedAt,
|
||||
});
|
||||
entries.push({
|
||||
key,
|
||||
bytes: storedBytes(key, value),
|
||||
writtenAt: stored.generatedAt,
|
||||
...(kind === "cwd" ? { body: bodyKey(serverId, stored.hash) } : {}),
|
||||
});
|
||||
} catch (error) {
|
||||
if (
|
||||
!(error instanceof SyntaxError) &&
|
||||
@@ -181,7 +224,8 @@ export function createProviderSnapshotCache(
|
||||
}
|
||||
|
||||
// Reconstruct the dependency ordering before applying a possibly smaller budget.
|
||||
for (const reference of references) {
|
||||
for (const reference of entries) {
|
||||
if (reference.body === undefined) continue;
|
||||
const body = entries.find((entry) => entry.key === reference.body);
|
||||
if (!body) keysToRemove.push(reference.key);
|
||||
else if (body.writtenAt < reference.writtenAt) body.writtenAt = reference.writtenAt;
|
||||
@@ -200,7 +244,7 @@ export function createProviderSnapshotCache(
|
||||
for (const removedKey of keysToRemove) bodies.delete(removedKey);
|
||||
await storage.multiRemove(keysToRemove);
|
||||
}
|
||||
index = retainedEntries;
|
||||
await commitIndex(retainedEntries);
|
||||
}
|
||||
|
||||
async function ensureCacheIndex(): Promise<ProviderSnapshotIndexEntry[]> {
|
||||
@@ -235,7 +279,7 @@ export function createProviderSnapshotCache(
|
||||
value,
|
||||
};
|
||||
}
|
||||
const incoming = prepare(key, input);
|
||||
const incoming = { ...prepare(key, input), body: requiredBody?.key };
|
||||
// The index is committed last: membership proves a body was stored. Reusing it
|
||||
// needs only its byte count, not another parse, expansion, or storage write.
|
||||
const body = requiredBody
|
||||
@@ -265,29 +309,27 @@ export function createProviderSnapshotCache(
|
||||
const keysToRemove = [...replacedKeys].filter(
|
||||
(replaced) => !admitted.some((entry) => entry.key === replaced),
|
||||
);
|
||||
for (const candidate of [...retainedEntries].sort(oldestFirst)) {
|
||||
if (projectedBytes <= maxBytes) break;
|
||||
projectedBytes -= candidate.bytes;
|
||||
keysToRemove.push(candidate.key);
|
||||
if (projectedBytes > maxBytes) {
|
||||
for (const candidate of [...retainedEntries].sort(oldestFirst)) {
|
||||
if (projectedBytes <= maxBytes) break;
|
||||
projectedBytes -= candidate.bytes;
|
||||
keysToRemove.push(candidate.key);
|
||||
}
|
||||
}
|
||||
const removedKeys = new Set(keysToRemove);
|
||||
if (keysToRemove.length > 0) {
|
||||
for (const removedKey of keysToRemove) bodies.delete(removedKey);
|
||||
await storage.multiRemove(keysToRemove);
|
||||
}
|
||||
// Body, then reference, then in-memory index. A failed write can leave a reusable
|
||||
// Body, then reference, then index. A failed write can leave a reusable
|
||||
// orphan body; reconciliation never retains a reference without its body.
|
||||
for (const entry of admitted) {
|
||||
if (entry.value !== undefined) await storage.setItem(entry.key, entry.value);
|
||||
}
|
||||
index = [
|
||||
await commitIndex([
|
||||
...retainedEntries.filter((entry) => !removedKeys.has(entry.key)),
|
||||
...admitted.map(({ key: recordKey, bytes, writtenAt }) => ({
|
||||
key: recordKey,
|
||||
bytes,
|
||||
writtenAt,
|
||||
})),
|
||||
];
|
||||
...admitted.map(({ value: _value, ...entry }) => entry),
|
||||
]);
|
||||
}
|
||||
|
||||
async function readRecord(key: string): Promise<StoredProviderSnapshot | null> {
|
||||
@@ -302,7 +344,7 @@ export function createProviderSnapshotCache(
|
||||
if (!(error instanceof SyntaxError) && !(error instanceof RangeError)) throw error;
|
||||
bodies.delete(key);
|
||||
await storage.removeItem(key);
|
||||
index = currentIndex.filter((entry) => entry.key !== key);
|
||||
await commitIndex(currentIndex.filter((entry) => entry.key !== key));
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -65,7 +65,7 @@ const nativeRequire = createRequire(require.resolve("react-native/package.json")
|
||||
const { AbortController: NativeAbortController }: { AbortController: typeof AbortController } =
|
||||
nativeRequire("abort-controller/dist/abort-controller");
|
||||
|
||||
function createStorage(onWrite: () => void = () => {}) {
|
||||
function createStorage(onWrite: (key: string) => void = () => {}) {
|
||||
const values = new Map<string, string>();
|
||||
return {
|
||||
async getItem(key: string) {
|
||||
@@ -73,7 +73,7 @@ function createStorage(onWrite: () => void = () => {}) {
|
||||
},
|
||||
async setItem(key: string, value: string) {
|
||||
values.set(key, value);
|
||||
onWrite();
|
||||
onWrite(key);
|
||||
},
|
||||
async removeItem(key: string) {
|
||||
values.delete(key);
|
||||
@@ -164,7 +164,9 @@ describe.each([
|
||||
async ({ abortOnWrite, hasBody, hasReference }) => {
|
||||
const controller = new Controller();
|
||||
let writes = 0;
|
||||
const storage = createStorage(() => {
|
||||
const storage = createStorage((key) => {
|
||||
// The boundaries are the stored snapshots, not the cache's own index of them.
|
||||
if (!key.startsWith("@paseo/provider-snapshot/")) return;
|
||||
writes += 1;
|
||||
if (writes === abortOnWrite) controller.abort();
|
||||
});
|
||||
|
||||
@@ -5,23 +5,10 @@ import invariant from "tiny-invariant";
|
||||
import { BrowserPane } from "@/desktop/browser/pane";
|
||||
import { usePaneContext, usePaneFocus } from "@/panels/pane-context";
|
||||
import { definePanel, type PanelDescriptor, type PanelIconProps } from "@/panels/panel-registry";
|
||||
import { browserTabLabel } from "@/panels/tab-labels";
|
||||
import { useBrowserStore } from "@/desktop/browser/store";
|
||||
import { useWorkspaceDirectory } from "@/stores/session-store-hooks";
|
||||
|
||||
function getBrowserLabel(input: { title: string; url: string }): string {
|
||||
const title = input.title.trim();
|
||||
if (title) {
|
||||
return title;
|
||||
}
|
||||
|
||||
try {
|
||||
const parsed = new URL(input.url);
|
||||
return parsed.hostname || input.url;
|
||||
} catch {
|
||||
return input.url;
|
||||
}
|
||||
}
|
||||
|
||||
function createBrowserTabIcon(faviconUrl: string | null) {
|
||||
return function BrowserTabIcon({ size, color }: PanelIconProps) {
|
||||
const source = useMemo(() => (faviconUrl ? { uri: faviconUrl } : undefined), []);
|
||||
@@ -42,7 +29,7 @@ function useBrowserPanelDescriptor(target: {
|
||||
const browser = useBrowserStore((state) => state.browsersById[target.browserId] ?? null);
|
||||
const url = browser?.url ?? "https://example.com";
|
||||
const icon = createBrowserTabIcon(browser?.faviconUrl ?? null);
|
||||
const label = getBrowserLabel({ title: browser?.title ?? "", url });
|
||||
const label = browserTabLabel({ title: browser?.title ?? "", url });
|
||||
|
||||
return {
|
||||
label,
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
/** One workspace's file tree state, driven from inside and outside React. */
|
||||
import {
|
||||
loadExplorerDirectory,
|
||||
type DirectoryListingResult,
|
||||
} from "@/file-explorer/directory-listings";
|
||||
import { clearFileFilter } from "@/file-explorer/filter";
|
||||
import { useExplorerRevealStore } from "@/file-explorer/reveal-request";
|
||||
import { revealExplorerEntry } from "@/file-explorer/tree";
|
||||
import { i18n } from "@/i18n/i18next";
|
||||
import { usePanelStore } from "@/stores/panel-store";
|
||||
import { useSessionStore, type AgentFileExplorerState } from "@/stores/session-store";
|
||||
|
||||
export interface FileExplorerWorkspaceScope {
|
||||
workspaceId?: string | null;
|
||||
workspaceRoot?: string | null;
|
||||
}
|
||||
|
||||
/** The tree being driven: its host, its state key, and the directory it lists. */
|
||||
export interface WorkspaceFileTree {
|
||||
serverId: string;
|
||||
stateKey: string;
|
||||
workspaceRoot: string | null;
|
||||
}
|
||||
|
||||
function createExplorerState(): AgentFileExplorerState {
|
||||
return {
|
||||
listingGeneration: 0,
|
||||
directories: new Map(),
|
||||
isLoading: false,
|
||||
lastError: null,
|
||||
pendingRequest: null,
|
||||
currentPath: ".",
|
||||
history: ["."],
|
||||
lastVisitedPath: ".",
|
||||
selectedEntryPath: null,
|
||||
};
|
||||
}
|
||||
|
||||
export function normalizeWorkspaceValue(value: string | null | undefined): string | null {
|
||||
if (typeof value !== "string") {
|
||||
return null;
|
||||
}
|
||||
const trimmed = value.trim();
|
||||
return trimmed.length > 0 ? trimmed : null;
|
||||
}
|
||||
|
||||
export function buildWorkspaceExplorerStateKey(scope: FileExplorerWorkspaceScope): string | null {
|
||||
const normalizedWorkspaceId = normalizeWorkspaceValue(scope.workspaceId);
|
||||
if (normalizedWorkspaceId) {
|
||||
return `workspace:${normalizedWorkspaceId}`;
|
||||
}
|
||||
const normalizedWorkspaceRoot = normalizeWorkspaceValue(scope.workspaceRoot);
|
||||
if (!normalizedWorkspaceRoot) {
|
||||
return null;
|
||||
}
|
||||
return `root:${normalizedWorkspaceRoot}`;
|
||||
}
|
||||
|
||||
export function updateWorkspaceExplorerState(
|
||||
tree: Pick<WorkspaceFileTree, "serverId" | "stateKey">,
|
||||
updater: (prev: AgentFileExplorerState) => AgentFileExplorerState,
|
||||
): AgentFileExplorerState | null {
|
||||
let updated: AgentFileExplorerState | null = null;
|
||||
useSessionStore.getState().setFileExplorer(tree.serverId, (prev) => {
|
||||
const next = new Map(prev);
|
||||
const current = next.get(tree.stateKey) ?? createExplorerState();
|
||||
updated = updater(current);
|
||||
next.set(tree.stateKey, updated);
|
||||
return next;
|
||||
});
|
||||
return updated;
|
||||
}
|
||||
|
||||
export function listWorkspaceExplorerDirectory(
|
||||
tree: WorkspaceFileTree,
|
||||
path: string,
|
||||
options?: { recordHistory?: boolean; setCurrentPath?: boolean },
|
||||
): Promise<DirectoryListingResult> {
|
||||
const normalizedPath = path && path.length > 0 ? path : ".";
|
||||
return loadExplorerDirectory({
|
||||
path: normalizedPath,
|
||||
options,
|
||||
updateState: (updater) => updateWorkspaceExplorerState(tree, updater),
|
||||
fallbackError: i18n.t("workspace.fileExplorer.errors.failedToListDirectory"),
|
||||
listDirectory: async () => {
|
||||
if (!tree.workspaceRoot) {
|
||||
throw new Error(i18n.t("workspace.fileExplorer.states.unavailable"));
|
||||
}
|
||||
const client = useSessionStore.getState().sessions[tree.serverId]?.client;
|
||||
if (!client) throw new Error(i18n.t("workspace.terminal.hostDisconnected"));
|
||||
return client.listDirectory(tree.workspaceRoot, normalizedPath);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function showWorkspaceExplorerHiddenFiles(): void {
|
||||
const panel = usePanelStore.getState();
|
||||
if (!panel.explorerShowHiddenFiles) panel.toggleExplorerShowHiddenFiles();
|
||||
}
|
||||
|
||||
export function expandWorkspaceExplorerPaths(stateKey: string, paths: string[]): void {
|
||||
usePanelStore
|
||||
.getState()
|
||||
.setExpandedPathsForWorkspace(stateKey, (current) =>
|
||||
Array.from(new Set([...current, ...paths])),
|
||||
);
|
||||
}
|
||||
|
||||
/** Selects an entry the tree has expanded to, and asks the tree to scroll to it. */
|
||||
export function showWorkspaceExplorerEntry(
|
||||
tree: Pick<WorkspaceFileTree, "serverId" | "stateKey">,
|
||||
entryPath: string,
|
||||
): void {
|
||||
updateWorkspaceExplorerState(tree, (state) => ({ ...state, selectedEntryPath: entryPath }));
|
||||
useExplorerRevealStore.getState().request(tree.stateKey, entryPath);
|
||||
}
|
||||
|
||||
/** Expands to an entry, selects it, and asks the tree to scroll to it. */
|
||||
export async function revealWorkspaceExplorerEntry(
|
||||
tree: WorkspaceFileTree,
|
||||
entryPath: string,
|
||||
): Promise<boolean> {
|
||||
const found = await revealExplorerEntry({
|
||||
entryPath,
|
||||
requestDirectoryListing: (path) =>
|
||||
listWorkspaceExplorerDirectory(tree, path, { recordHistory: false, setCurrentPath: false }),
|
||||
showHiddenFiles: showWorkspaceExplorerHiddenFiles,
|
||||
expandPaths: (paths) => expandWorkspaceExplorerPaths(tree.stateKey, paths),
|
||||
});
|
||||
if (found) {
|
||||
clearFileFilter(tree.stateKey);
|
||||
showWorkspaceExplorerEntry(tree, entryPath);
|
||||
}
|
||||
return found;
|
||||
}
|
||||
@@ -155,14 +155,15 @@ function MountedFilePanel({
|
||||
revision: number;
|
||||
onModifiedChange: (modified: boolean) => void;
|
||||
}) {
|
||||
const { state, setCurrentTabState } = usePaneContext();
|
||||
const { tabId, state, setCurrentTabState } = usePaneContext();
|
||||
const tab = useMemo<PluginTab>(
|
||||
() => ({
|
||||
id: tabId,
|
||||
setModified: onModifiedChange,
|
||||
state,
|
||||
setState: setCurrentTabState,
|
||||
}),
|
||||
[onModifiedChange, state, setCurrentTabState],
|
||||
[tabId, onModifiedChange, state, setCurrentTabState],
|
||||
);
|
||||
useEffect(() => () => onModifiedChange(false), [onModifiedChange]);
|
||||
return <FilePanelView panel={panel} file={file} tab={tab} params={params} revision={revision} />;
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { useSessionStore, type WorkspaceDescriptor } from "@/stores/session-store";
|
||||
import { selectGitActionsWorkspace } from "./actions-workspace";
|
||||
|
||||
const SERVER_ID = "git-actions-server";
|
||||
|
||||
function createWorkspace(id: string, workspaceDirectory: string): WorkspaceDescriptor {
|
||||
return {
|
||||
id,
|
||||
projectId: "project-1",
|
||||
projectDisplayName: "Project 1",
|
||||
projectRootPath: workspaceDirectory,
|
||||
workspaceDirectory,
|
||||
projectKind: "git",
|
||||
workspaceKind: "worktree",
|
||||
name: id,
|
||||
status: "done",
|
||||
archivingAt: null,
|
||||
statusEnteredAt: null,
|
||||
diffStat: null,
|
||||
scripts: [],
|
||||
createdAt: null,
|
||||
lastUserMessageAt: null,
|
||||
};
|
||||
}
|
||||
|
||||
function seed(workspaces: WorkspaceDescriptor[]): void {
|
||||
const store = useSessionStore.getState();
|
||||
store.initializeSession(SERVER_ID, null);
|
||||
store.mergeWorkspaces(SERVER_ID, workspaces);
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
useSessionStore.getState().clearSession(SERVER_ID);
|
||||
});
|
||||
|
||||
describe("selectGitActionsWorkspace", () => {
|
||||
it("resolves the workspace the git actions belong to, not another one in the same directory", () => {
|
||||
seed([createWorkspace("ws-a", "/repo"), createWorkspace("ws-b", "/repo")]);
|
||||
|
||||
const workspace = selectGitActionsWorkspace(useSessionStore.getState(), {
|
||||
serverId: SERVER_ID,
|
||||
workspaceId: "ws-b",
|
||||
workspaceDirectory: "/repo",
|
||||
});
|
||||
|
||||
expect(workspace?.id).toBe("ws-b");
|
||||
});
|
||||
|
||||
// Each retained workspace subscribes through this selector. Returning the same descriptor when
|
||||
// another workspace on the host changes keeps hidden workspaces from re-rendering their git
|
||||
// actions on every workspace switch.
|
||||
it("keeps the descriptor reference when another workspace on the host changes", () => {
|
||||
seed([createWorkspace("ws-a", "/repo-a"), createWorkspace("ws-b", "/repo-b")]);
|
||||
const input = { serverId: SERVER_ID, workspaceId: "ws-a", workspaceDirectory: "/repo-a" };
|
||||
const before = selectGitActionsWorkspace(useSessionStore.getState(), input);
|
||||
|
||||
useSessionStore
|
||||
.getState()
|
||||
.mergeWorkspaces(SERVER_ID, [{ ...createWorkspace("ws-b", "/repo-b"), status: "running" }]);
|
||||
|
||||
expect(useSessionStore.getState().sessions[SERVER_ID]?.workspaces.get("ws-b")?.status).toBe(
|
||||
"running",
|
||||
);
|
||||
expect(before?.id).toBe("ws-a");
|
||||
expect(selectGitActionsWorkspace(useSessionStore.getState(), input)).toBe(before);
|
||||
});
|
||||
|
||||
it("falls back to the workspace in the checkout directory when the caller names no workspace", () => {
|
||||
seed([createWorkspace("ws-a", "/repo-a"), createWorkspace("ws-b", "/repo-b")]);
|
||||
|
||||
const workspace = selectGitActionsWorkspace(useSessionStore.getState(), {
|
||||
serverId: SERVER_ID,
|
||||
workspaceId: null,
|
||||
workspaceDirectory: "/repo-b",
|
||||
});
|
||||
|
||||
expect(workspace?.id).toBe("ws-b");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,38 @@
|
||||
import type { SessionsSnapshot } from "@/stores/session-store-hooks/selectors";
|
||||
import type { WorkspaceDescriptor } from "@/stores/session-store";
|
||||
import { resolveWorkspaceMapKeyByIdentity } from "@/utils/workspace-identity";
|
||||
|
||||
export interface GitActionsWorkspaceInput {
|
||||
serverId: string;
|
||||
/** The workspace that renders the git actions, or null when the caller has none. */
|
||||
workspaceId: string | null | undefined;
|
||||
/** The checkout directory, used to find the workspace when the caller names none. */
|
||||
workspaceDirectory: string | null | undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* The workspace descriptor the git actions archive. Returns the stored descriptor itself, so a
|
||||
* subscriber re-renders only when this workspace changes, not when another workspace on the host
|
||||
* does.
|
||||
*/
|
||||
export function selectGitActionsWorkspace(
|
||||
state: SessionsSnapshot,
|
||||
input: GitActionsWorkspaceInput,
|
||||
): WorkspaceDescriptor | null {
|
||||
const workspaces = state.sessions[input.serverId]?.workspaces;
|
||||
const workspaceKey = input.workspaceId
|
||||
? resolveWorkspaceMapKeyByIdentity({ workspaces, workspaceId: input.workspaceId })
|
||||
: null;
|
||||
if (workspaceKey) {
|
||||
return workspaces?.get(workspaceKey) ?? null;
|
||||
}
|
||||
if (!input.workspaceDirectory) {
|
||||
return null;
|
||||
}
|
||||
for (const candidate of workspaces?.values() ?? []) {
|
||||
if (candidate.workspaceDirectory === input.workspaceDirectory) {
|
||||
return candidate;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -1767,6 +1767,7 @@ export function ChangesSurface({
|
||||
);
|
||||
const { gitActions, branchLabel } = useGitActions({
|
||||
serverId,
|
||||
workspaceId,
|
||||
cwd,
|
||||
icons: GIT_ACTION_ICONS,
|
||||
});
|
||||
|
||||
@@ -28,14 +28,11 @@ import type { CheckoutPrMergeMethod } from "@getpaseo/protocol/messages";
|
||||
import { openExternalUrl } from "@/utils/open-external-url";
|
||||
import { useToast } from "@/contexts/toast-context";
|
||||
import { useSessionStore, type WorkspaceDescriptor } from "@/stores/session-store";
|
||||
import {
|
||||
useActiveWorkspaceSelection,
|
||||
type ActiveWorkspaceSelection,
|
||||
} from "@/stores/navigation-active-workspace-store";
|
||||
import { redirectIfArchivingActiveWorkspace } from "@/utils/sidebar-workspace-archive-redirect";
|
||||
import { getFocusedWorkspaceSelection } from "@/navigation/workspace-route-navigation";
|
||||
import { selectGitActionsWorkspace } from "@/git/actions-workspace";
|
||||
import { type WorktreeArchiveWarningLabels } from "@/git/worktree-archive-warning";
|
||||
import { useWorkspaceArchive } from "@/workspace/use-workspace-archive";
|
||||
import { resolveWorkspaceMapKeyByIdentity } from "@/utils/workspace-identity";
|
||||
import { readValidatedString } from "@/storage/validated-storage";
|
||||
|
||||
export type { GitActionId, GitAction, GitActions } from "@/git/policy";
|
||||
@@ -200,6 +197,8 @@ function deriveGitActionsState(args: DeriveGitActionsStateArgs): DerivedGitActio
|
||||
|
||||
interface UseGitActionsInput {
|
||||
serverId: string;
|
||||
/** The workspace these actions belong to; a retained, hidden workspace passes its own. */
|
||||
workspaceId: string | null | undefined;
|
||||
cwd: string;
|
||||
icons: {
|
||||
commit: ReactElement;
|
||||
@@ -222,38 +221,13 @@ interface UseGitActionsResult {
|
||||
|
||||
interface UseWorkspaceScreenArchiveControllerInput {
|
||||
serverId: string;
|
||||
activeWorkspaceSelection: ActiveWorkspaceSelection | null;
|
||||
workspaceId: string | null | undefined;
|
||||
workspaceDirectory: string | null | undefined;
|
||||
branchLabel: string;
|
||||
gitStatus: CheckoutStatusPayload | null;
|
||||
t: (key: string, options?: Record<string, unknown>) => string;
|
||||
}
|
||||
|
||||
function resolveArchiveWorkspaceDescriptor(input: {
|
||||
workspaces: Map<string, WorkspaceDescriptor> | undefined;
|
||||
activeWorkspaceSelection: ActiveWorkspaceSelection | null;
|
||||
workspaceDirectory: string | null | undefined;
|
||||
}): WorkspaceDescriptor | null {
|
||||
const activeWorkspaceKey = input.activeWorkspaceSelection
|
||||
? resolveWorkspaceMapKeyByIdentity({
|
||||
workspaces: input.workspaces,
|
||||
workspaceId: input.activeWorkspaceSelection.workspaceId,
|
||||
})
|
||||
: null;
|
||||
if (activeWorkspaceKey) {
|
||||
return input.workspaces?.get(activeWorkspaceKey) ?? null;
|
||||
}
|
||||
if (!input.workspaceDirectory) {
|
||||
return null;
|
||||
}
|
||||
for (const candidate of input.workspaces?.values() ?? []) {
|
||||
if (candidate.workspaceDirectory === input.workspaceDirectory) {
|
||||
return candidate;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function resolveWorkspaceArchiveRisk(
|
||||
workspace: WorkspaceDescriptor | null,
|
||||
gitStatus: CheckoutStatusPayload | null,
|
||||
@@ -284,23 +258,16 @@ function availableArchive(
|
||||
|
||||
function useWorkspaceScreenArchiveController({
|
||||
serverId,
|
||||
activeWorkspaceSelection,
|
||||
workspaceId,
|
||||
workspaceDirectory,
|
||||
branchLabel,
|
||||
gitStatus,
|
||||
t,
|
||||
}: UseWorkspaceScreenArchiveControllerInput) {
|
||||
const sessionWorkspaces = useSessionStore((state) => state.sessions[serverId]?.workspaces);
|
||||
const [isHidingWorkspace, setIsHidingWorkspace] = useState(false);
|
||||
const workspaceDescriptor = useMemo(
|
||||
() =>
|
||||
resolveArchiveWorkspaceDescriptor({
|
||||
workspaces: sessionWorkspaces,
|
||||
activeWorkspaceSelection,
|
||||
workspaceDirectory,
|
||||
}),
|
||||
[activeWorkspaceSelection, sessionWorkspaces, workspaceDirectory],
|
||||
const workspaceDescriptor = useSessionStore((state) =>
|
||||
selectGitActionsWorkspace(state, { serverId, workspaceId, workspaceDirectory }),
|
||||
);
|
||||
const [isHidingWorkspace, setIsHidingWorkspace] = useState(false);
|
||||
const archiveRisk = resolveWorkspaceArchiveRisk(workspaceDescriptor, gitStatus);
|
||||
|
||||
const controller = useWorkspaceArchive({
|
||||
@@ -313,7 +280,10 @@ function useWorkspaceScreenArchiveController({
|
||||
warningLabels: getWorktreeArchiveWarningLabels(t),
|
||||
onSetHiding: setIsHidingWorkspace,
|
||||
onArchiveStarted: (archived) => {
|
||||
redirectIfArchivingActiveWorkspace({ ...archived, activeWorkspaceSelection });
|
||||
redirectIfArchivingActiveWorkspace({
|
||||
...archived,
|
||||
activeWorkspaceSelection: getFocusedWorkspaceSelection(),
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
@@ -324,10 +294,14 @@ function useWorkspaceScreenArchiveController({
|
||||
};
|
||||
}
|
||||
|
||||
export function useGitActions({ serverId, cwd, icons }: UseGitActionsInput): UseGitActionsResult {
|
||||
export function useGitActions({
|
||||
serverId,
|
||||
workspaceId,
|
||||
cwd,
|
||||
icons,
|
||||
}: UseGitActionsInput): UseGitActionsResult {
|
||||
const { t } = useTranslation();
|
||||
const toast = useToast();
|
||||
const activeWorkspaceSelection = useActiveWorkspaceSelection();
|
||||
const [postShipArchiveSuggested, setPostShipArchiveSuggested] = useState(false);
|
||||
const [shipDefault, setShipDefault] = useState<"merge" | "pr">("pr");
|
||||
|
||||
@@ -646,7 +620,7 @@ export function useGitActions({ serverId, cwd, icons }: UseGitActionsInput): Use
|
||||
|
||||
const archiveController = useWorkspaceScreenArchiveController({
|
||||
serverId,
|
||||
activeWorkspaceSelection,
|
||||
workspaceId,
|
||||
workspaceDirectory: status?.cwd,
|
||||
branchLabel,
|
||||
gitStatus,
|
||||
|
||||
@@ -4,12 +4,14 @@ import { useGitActions } from "@/git/use-actions";
|
||||
|
||||
interface WorkspaceActionsProps {
|
||||
serverId: string;
|
||||
workspaceId: string;
|
||||
cwd: string;
|
||||
}
|
||||
|
||||
export function WorkspaceActions({ serverId, cwd }: WorkspaceActionsProps) {
|
||||
export function WorkspaceActions({ serverId, workspaceId, cwd }: WorkspaceActionsProps) {
|
||||
const { gitActions } = useGitActions({
|
||||
serverId,
|
||||
workspaceId,
|
||||
cwd,
|
||||
icons: GIT_ACTION_ICONS,
|
||||
});
|
||||
|
||||
@@ -166,7 +166,7 @@ describe("ensureAgentIsInitialized", () => {
|
||||
kind: "assistant_message",
|
||||
id: "canonical-item",
|
||||
text: "Canonical before restart",
|
||||
timelineCursor: { epoch: "epoch-1", seq: 12 },
|
||||
timelineCursor: { epoch: "epoch-1", seq: 12, anchorSeq: 12 },
|
||||
timestamp: new Date("2026-07-27T10:00:00.000Z"),
|
||||
},
|
||||
],
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
import { getHostRuntimeStore } from "@/runtime/host-runtime";
|
||||
import { useCallback, useMemo } from "react";
|
||||
import {
|
||||
useMutation,
|
||||
useQuery,
|
||||
useQueryClient,
|
||||
type MutationOptions,
|
||||
type QueryClient,
|
||||
type QueryKey,
|
||||
} from "@tanstack/react-query";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { i18n } from "@/i18n/i18next";
|
||||
import { useSessionStore } from "@/stores/session-store";
|
||||
import { agentHistoryQueryKey, allAgentHistoryQueryRootKey } from "./agent-history-query-key";
|
||||
|
||||
@@ -380,87 +380,95 @@ export function usePendingArchiveAgentIds(serverId: string): ReadonlySet<string>
|
||||
);
|
||||
}
|
||||
|
||||
export function useArchiveAgent() {
|
||||
const queryClient = useQueryClient();
|
||||
const { t } = useTranslation();
|
||||
|
||||
const pendingQuery = useArchiveAgentPendingQuery();
|
||||
|
||||
const archiveMutation = useMutation({
|
||||
mutationFn: async (input: ArchiveAgentInput): Promise<{ archivedAt: string }> => {
|
||||
const client = useSessionStore.getState().sessions[input.serverId]?.client ?? null;
|
||||
/**
|
||||
* Archives an agent: hides it right away, then asks the daemon, and puts it back if that fails.
|
||||
*/
|
||||
export async function archiveAgent(
|
||||
queryClient: QueryClient,
|
||||
input: ArchiveAgentInput,
|
||||
): Promise<void> {
|
||||
const options: MutationOptions<
|
||||
{ archivedAt: string },
|
||||
Error,
|
||||
ArchiveAgentInput,
|
||||
ArchiveAgentMutationContext
|
||||
> = {
|
||||
mutationFn: async (variables) => {
|
||||
const client = useSessionStore.getState().sessions[variables.serverId]?.client ?? null;
|
||||
if (!client) {
|
||||
throw new Error(t("common.errors.daemonClientUnavailable"));
|
||||
throw new Error(i18n.t("common.errors.daemonClientUnavailable"));
|
||||
}
|
||||
return await client.archiveAgent(input.agentId);
|
||||
return await client.archiveAgent(variables.agentId);
|
||||
},
|
||||
onMutate: (input) => {
|
||||
onMutate: (variables) => {
|
||||
const context: ArchiveAgentMutationContext = {
|
||||
agent: getStoredAgentSnapshot(input),
|
||||
lists: getArchivedAgentListCacheSnapshot(queryClient, input.serverId),
|
||||
agent: getStoredAgentSnapshot(variables),
|
||||
lists: getArchivedAgentListCacheSnapshot(queryClient, variables.serverId),
|
||||
};
|
||||
const archivedAt = new Date().toISOString();
|
||||
|
||||
applyArchivedAgentCloseResults({
|
||||
queryClient,
|
||||
serverId: input.serverId,
|
||||
results: [{ agentId: input.agentId, archivedAt }],
|
||||
serverId: variables.serverId,
|
||||
results: [{ agentId: variables.agentId, archivedAt }],
|
||||
invalidateQueries: false,
|
||||
});
|
||||
setAgentArchiving({
|
||||
queryClient,
|
||||
serverId: input.serverId,
|
||||
agentId: input.agentId,
|
||||
serverId: variables.serverId,
|
||||
agentId: variables.agentId,
|
||||
isArchiving: true,
|
||||
});
|
||||
return context;
|
||||
},
|
||||
onSuccess: (result, input) => {
|
||||
onSuccess: (result, variables) => {
|
||||
markAgentArchivedInStore({
|
||||
serverId: input.serverId,
|
||||
agentId: input.agentId,
|
||||
serverId: variables.serverId,
|
||||
agentId: variables.agentId,
|
||||
archivedAt: result.archivedAt,
|
||||
});
|
||||
},
|
||||
onError: (_error, input, context) => {
|
||||
onError: (_error, variables, context) => {
|
||||
if (!context) {
|
||||
return;
|
||||
}
|
||||
restoreAgentSnapshot({
|
||||
serverId: input.serverId,
|
||||
agentId: input.agentId,
|
||||
serverId: variables.serverId,
|
||||
agentId: variables.agentId,
|
||||
agent: context.agent,
|
||||
});
|
||||
restoreArchivedAgentListCacheSnapshot(queryClient, input.serverId, context.lists);
|
||||
restoreArchivedAgentListCacheSnapshot(queryClient, variables.serverId, context.lists);
|
||||
},
|
||||
onSettled: (_result, _error, input) => {
|
||||
onSettled: (_result, _error, variables) => {
|
||||
clearArchiveAgentPending({
|
||||
queryClient,
|
||||
serverId: input.serverId,
|
||||
agentId: input.agentId,
|
||||
serverId: variables.serverId,
|
||||
agentId: variables.agentId,
|
||||
});
|
||||
void queryClient.invalidateQueries({
|
||||
queryKey: ["sidebarAgentsList", input.serverId],
|
||||
queryKey: ["sidebarAgentsList", variables.serverId],
|
||||
});
|
||||
void queryClient.invalidateQueries({
|
||||
queryKey: ["allAgents", input.serverId],
|
||||
queryKey: ["allAgents", variables.serverId],
|
||||
});
|
||||
void queryClient.invalidateQueries({
|
||||
queryKey: agentHistoryQueryKey(input.serverId),
|
||||
queryKey: agentHistoryQueryKey(variables.serverId),
|
||||
});
|
||||
void queryClient.invalidateQueries({
|
||||
queryKey: allAgentHistoryQueryRootKey(),
|
||||
});
|
||||
},
|
||||
});
|
||||
};
|
||||
await queryClient.getMutationCache().build(queryClient, options).execute(input);
|
||||
}
|
||||
|
||||
const archiveMutateAsync = archiveMutation.mutateAsync;
|
||||
export function useArchiveAgent() {
|
||||
const queryClient = useQueryClient();
|
||||
const pendingQuery = useArchiveAgentPendingQuery();
|
||||
|
||||
const archiveAgent = useCallback(
|
||||
async (input: ArchiveAgentInput): Promise<void> => {
|
||||
await archiveMutateAsync(input);
|
||||
},
|
||||
[archiveMutateAsync],
|
||||
const archive = useCallback(
|
||||
(input: ArchiveAgentInput): Promise<void> => archiveAgent(queryClient, input),
|
||||
[queryClient],
|
||||
);
|
||||
|
||||
const isArchivingAgent = useCallback(
|
||||
@@ -475,7 +483,7 @@ export function useArchiveAgent() {
|
||||
);
|
||||
|
||||
return {
|
||||
archiveAgent,
|
||||
archiveAgent: archive,
|
||||
isArchivingAgent,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,61 +1,32 @@
|
||||
import { useCallback, useMemo } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useSessionStore, type AgentFileExplorerState } from "@/stores/session-store";
|
||||
import { usePanelStore } from "@/stores/panel-store";
|
||||
import { revealExplorerDirectory, revealExplorerEntry } from "@/file-explorer/tree";
|
||||
import { useExplorerRevealStore } from "@/file-explorer/reveal-request";
|
||||
import { revealExplorerDirectory } from "@/file-explorer/tree";
|
||||
import { clearFileFilter } from "@/file-explorer/filter";
|
||||
import {
|
||||
loadExplorerDirectory,
|
||||
type DirectoryListingResult,
|
||||
invalidateExplorerDirectoryListings,
|
||||
} from "@/file-explorer/directory-listings";
|
||||
import {
|
||||
buildWorkspaceExplorerStateKey,
|
||||
expandWorkspaceExplorerPaths,
|
||||
listWorkspaceExplorerDirectory,
|
||||
normalizeWorkspaceValue,
|
||||
revealWorkspaceExplorerEntry,
|
||||
showWorkspaceExplorerEntry,
|
||||
showWorkspaceExplorerHiddenFiles,
|
||||
updateWorkspaceExplorerState,
|
||||
type FileExplorerWorkspaceScope,
|
||||
type WorkspaceFileTree,
|
||||
} from "@/file-explorer/workspace-tree";
|
||||
import { parentExplorerPath } from "@/utils/explorer-paths";
|
||||
|
||||
function createExplorerState(): AgentFileExplorerState {
|
||||
return {
|
||||
listingGeneration: 0,
|
||||
directories: new Map(),
|
||||
isLoading: false,
|
||||
lastError: null,
|
||||
pendingRequest: null,
|
||||
currentPath: ".",
|
||||
history: ["."],
|
||||
lastVisitedPath: ".",
|
||||
selectedEntryPath: null,
|
||||
};
|
||||
}
|
||||
|
||||
export interface FileExplorerWorkspaceScope {
|
||||
workspaceId?: string | null;
|
||||
workspaceRoot?: string | null;
|
||||
}
|
||||
|
||||
function normalizeWorkspaceValue(value: string | null | undefined): string | null {
|
||||
if (typeof value !== "string") {
|
||||
return null;
|
||||
}
|
||||
const trimmed = value.trim();
|
||||
return trimmed.length > 0 ? trimmed : null;
|
||||
}
|
||||
|
||||
export function buildWorkspaceExplorerStateKey(scope: FileExplorerWorkspaceScope): string | null {
|
||||
const normalizedWorkspaceId = normalizeWorkspaceValue(scope.workspaceId);
|
||||
if (normalizedWorkspaceId) {
|
||||
return `workspace:${normalizedWorkspaceId}`;
|
||||
}
|
||||
const normalizedWorkspaceRoot = normalizeWorkspaceValue(scope.workspaceRoot);
|
||||
if (!normalizedWorkspaceRoot) {
|
||||
return null;
|
||||
}
|
||||
return `root:${normalizedWorkspaceRoot}`;
|
||||
}
|
||||
export { buildWorkspaceExplorerStateKey, type FileExplorerWorkspaceScope };
|
||||
|
||||
export function useFileExplorerActions(params: { serverId: string } & FileExplorerWorkspaceScope) {
|
||||
const { t } = useTranslation();
|
||||
const { serverId, workspaceId, workspaceRoot } = params;
|
||||
const client = useSessionStore((state) => state.sessions[serverId]?.client ?? null);
|
||||
const setFileExplorer = useSessionStore((state) => state.setFileExplorer);
|
||||
const normalizedWorkspaceRoot = useMemo(
|
||||
() => normalizeWorkspaceValue(workspaceRoot),
|
||||
[workspaceRoot],
|
||||
@@ -69,66 +40,28 @@ export function useFileExplorerActions(params: { serverId: string } & FileExplor
|
||||
[workspaceId, normalizedWorkspaceRoot],
|
||||
);
|
||||
|
||||
const tree = useMemo<WorkspaceFileTree | null>(
|
||||
() =>
|
||||
workspaceStateKey
|
||||
? { serverId, stateKey: workspaceStateKey, workspaceRoot: normalizedWorkspaceRoot }
|
||||
: null,
|
||||
[normalizedWorkspaceRoot, serverId, workspaceStateKey],
|
||||
);
|
||||
|
||||
const updateExplorerState = useCallback(
|
||||
(
|
||||
updater: (prev: AgentFileExplorerState) => AgentFileExplorerState,
|
||||
): AgentFileExplorerState | null => {
|
||||
if (!workspaceStateKey) {
|
||||
return null;
|
||||
}
|
||||
let updated: AgentFileExplorerState | null = null;
|
||||
setFileExplorer(serverId, (prev) => {
|
||||
const next = new Map(prev);
|
||||
const current = next.get(workspaceStateKey) ?? createExplorerState();
|
||||
updated = updater(current);
|
||||
next.set(workspaceStateKey, updated);
|
||||
return next;
|
||||
});
|
||||
return updated;
|
||||
},
|
||||
[serverId, setFileExplorer, workspaceStateKey],
|
||||
): AgentFileExplorerState | null => (tree ? updateWorkspaceExplorerState(tree, updater) : null),
|
||||
[tree],
|
||||
);
|
||||
|
||||
const requestDirectoryListing = useCallback(
|
||||
async (
|
||||
path: string,
|
||||
options?: { recordHistory?: boolean; setCurrentPath?: boolean },
|
||||
): Promise<DirectoryListingResult> => {
|
||||
if (!workspaceStateKey) {
|
||||
return null;
|
||||
}
|
||||
const normalizedPath = path && path.length > 0 ? path : ".";
|
||||
return loadExplorerDirectory({
|
||||
path: normalizedPath,
|
||||
options,
|
||||
updateState: updateExplorerState,
|
||||
fallbackError: t("workspace.fileExplorer.errors.failedToListDirectory"),
|
||||
listDirectory: async () => {
|
||||
if (!normalizedWorkspaceRoot)
|
||||
throw new Error(t("workspace.fileExplorer.states.unavailable"));
|
||||
if (!client) throw new Error(t("workspace.terminal.hostDisconnected"));
|
||||
return client.listDirectory(normalizedWorkspaceRoot, normalizedPath);
|
||||
},
|
||||
});
|
||||
},
|
||||
[client, normalizedWorkspaceRoot, t, updateExplorerState, workspaceStateKey],
|
||||
);
|
||||
|
||||
const showHiddenFiles = useCallback(() => {
|
||||
const panel = usePanelStore.getState();
|
||||
if (!panel.explorerShowHiddenFiles) panel.toggleExplorerShowHiddenFiles();
|
||||
}, []);
|
||||
|
||||
const expandPaths = useCallback(
|
||||
(paths: string[]) => {
|
||||
if (!workspaceStateKey) return;
|
||||
usePanelStore
|
||||
.getState()
|
||||
.setExpandedPathsForWorkspace(workspaceStateKey, (current) =>
|
||||
Array.from(new Set([...current, ...paths])),
|
||||
);
|
||||
},
|
||||
[workspaceStateKey],
|
||||
): Promise<DirectoryListingResult> =>
|
||||
tree ? listWorkspaceExplorerDirectory(tree, path, options) : null,
|
||||
[tree],
|
||||
);
|
||||
|
||||
const selectExplorerEntry = useCallback(
|
||||
@@ -141,50 +74,27 @@ export function useFileExplorerActions(params: { serverId: string } & FileExplor
|
||||
[updateExplorerState],
|
||||
);
|
||||
|
||||
/** Selects an entry the tree has expanded to, and asks the tree to scroll to it. */
|
||||
const showEntry = useCallback(
|
||||
(entryPath: string) => {
|
||||
if (!workspaceStateKey) return;
|
||||
selectExplorerEntry(entryPath);
|
||||
useExplorerRevealStore.getState().request(workspaceStateKey, entryPath);
|
||||
},
|
||||
[selectExplorerEntry, workspaceStateKey],
|
||||
);
|
||||
|
||||
/** Expands to a directory and into it. `select` also selects it and scrolls the tree to it. */
|
||||
const revealDirectory = useCallback(
|
||||
async (directoryPath: string, { select = false }: { select?: boolean } = {}) => {
|
||||
if (!workspaceStateKey) return;
|
||||
if (!tree) return;
|
||||
const listed = await revealExplorerDirectory({
|
||||
directoryPath,
|
||||
requestDirectoryListing,
|
||||
showHiddenFiles,
|
||||
expandPaths,
|
||||
showHiddenFiles: showWorkspaceExplorerHiddenFiles,
|
||||
expandPaths: (paths) => expandWorkspaceExplorerPaths(tree.stateKey, paths),
|
||||
});
|
||||
clearFileFilter(workspaceStateKey);
|
||||
if (listed && select) showEntry(directoryPath);
|
||||
clearFileFilter(tree.stateKey);
|
||||
if (listed && select) showWorkspaceExplorerEntry(tree, directoryPath);
|
||||
},
|
||||
[expandPaths, requestDirectoryListing, showEntry, showHiddenFiles, workspaceStateKey],
|
||||
[requestDirectoryListing, tree],
|
||||
);
|
||||
|
||||
/** Expands to an entry, selects it, and asks the tree to scroll to it. */
|
||||
const revealEntry = useCallback(
|
||||
async (entryPath: string): Promise<boolean> => {
|
||||
if (!workspaceStateKey) return false;
|
||||
const found = await revealExplorerEntry({
|
||||
entryPath,
|
||||
requestDirectoryListing: (path) =>
|
||||
requestDirectoryListing(path, { recordHistory: false, setCurrentPath: false }),
|
||||
showHiddenFiles,
|
||||
expandPaths,
|
||||
});
|
||||
if (found) {
|
||||
clearFileFilter(workspaceStateKey);
|
||||
showEntry(entryPath);
|
||||
}
|
||||
return found;
|
||||
},
|
||||
[expandPaths, requestDirectoryListing, showEntry, showHiddenFiles, workspaceStateKey],
|
||||
async (entryPath: string): Promise<boolean> =>
|
||||
tree ? revealWorkspaceExplorerEntry(tree, entryPath) : false,
|
||||
[tree],
|
||||
);
|
||||
|
||||
const requestFileDownloadToken = useCallback(
|
||||
|
||||
@@ -18,16 +18,22 @@ function useIsAgentUnarchiving({ serverId, agentId }: UnarchiveAgentTarget): boo
|
||||
export async function runAgentUnarchive(input: {
|
||||
serverId: string;
|
||||
agentId: string;
|
||||
client: { refreshAgent: (agentId: string) => Promise<unknown> } | null;
|
||||
client: {
|
||||
refreshAgent: (agentId: string) => Promise<{ historyDiverged?: boolean } | unknown>;
|
||||
} | null;
|
||||
isConnected: boolean;
|
||||
onRefreshed?: (result: { historyDiverged?: boolean }) => void;
|
||||
}): Promise<boolean> {
|
||||
const { serverId, agentId, client, isConnected } = input;
|
||||
const { serverId, agentId, client, isConnected, onRefreshed } = input;
|
||||
if (!client || !isConnected || isAgentUnarchiving({ serverId, agentId })) {
|
||||
return false;
|
||||
}
|
||||
const token = beginAgentUnarchive({ serverId, agentId });
|
||||
try {
|
||||
await client.refreshAgent(agentId);
|
||||
const refreshed = await client.refreshAgent(agentId);
|
||||
if (refreshed && typeof refreshed === "object" && "historyDiverged" in refreshed) {
|
||||
onRefreshed?.(refreshed as { historyDiverged?: boolean });
|
||||
}
|
||||
return true;
|
||||
} finally {
|
||||
finishAgentUnarchive({ serverId, agentId }, token);
|
||||
@@ -39,9 +45,20 @@ export function useUnarchiveAgent({ serverId, agentId }: UnarchiveAgentTarget) {
|
||||
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]);
|
||||
const unarchive = useCallback(
|
||||
async (options?: {
|
||||
onRefreshed?: (result: { historyDiverged?: boolean }) => void;
|
||||
}): Promise<void> => {
|
||||
await runAgentUnarchive({
|
||||
serverId,
|
||||
agentId,
|
||||
client,
|
||||
isConnected,
|
||||
onRefreshed: options?.onRefreshed,
|
||||
});
|
||||
},
|
||||
[agentId, client, isConnected, serverId],
|
||||
);
|
||||
|
||||
return {
|
||||
unarchive,
|
||||
|
||||
@@ -1,13 +1,12 @@
|
||||
import { PressHighlight } from "@/components/ui/press-highlight";
|
||||
import { useCallback, useMemo, useReducer, useRef, useState } from "react";
|
||||
import { useCallback, useMemo, useRef, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Alert, Text, View } from "react-native";
|
||||
import { Alert, Text, View, type LayoutChangeEvent } from "react-native";
|
||||
import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
||||
import { useIsCompactFormFactor } from "@/constants/layout";
|
||||
import { Check, ChevronDown, ChevronRight, Eye, EyeOff, Link2 } from "lucide-react-native";
|
||||
import { Check, Eye, EyeOff, Link2 } from "lucide-react-native";
|
||||
import type { HostProfile } from "@/types/host-connection";
|
||||
import { useHosts, useHostMutations } from "@/runtime/host-runtime";
|
||||
import { parseConnectionUri, serializeConnectionUri } from "@/utils/daemon-endpoints";
|
||||
import { buildConnectionFailureCopy } from "@/components/connection-failure-copy";
|
||||
import {
|
||||
AdaptiveModalSheet,
|
||||
@@ -15,24 +14,30 @@ import {
|
||||
type SheetHeader,
|
||||
} from "@/components/adaptive-modal-sheet";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { PairingTargetTracker } from "@/components/pair-link-credentials";
|
||||
import { buildDirectConnectionUri } from "@/components/direct-connection-host";
|
||||
import { SegmentedControl, type SegmentedControlOption } from "@/components/ui/segmented-control";
|
||||
import { useHardwareKeyboardPresent } from "@/keyboard/availability";
|
||||
import { getConnectionAuthFailureReason } from "@/utils/test-daemon-connection";
|
||||
import {
|
||||
canSwitchToForm,
|
||||
editForm,
|
||||
editHost,
|
||||
editPromptPassword,
|
||||
editUri,
|
||||
openDirectConnection,
|
||||
promptForPassword,
|
||||
resolveConnection,
|
||||
switchMode,
|
||||
type DirectConnectionForm,
|
||||
type DirectConnectionInput,
|
||||
type DirectConnectionMode,
|
||||
type DirectConnectionUri,
|
||||
type ResolvedDirectConnection,
|
||||
} from "./direct-connection";
|
||||
|
||||
const FLEX_ONE_STYLE = { flex: 1 } as const;
|
||||
|
||||
interface DirectConnectionDraft {
|
||||
host: string;
|
||||
port: string;
|
||||
useTls: boolean;
|
||||
password: string;
|
||||
}
|
||||
|
||||
interface PreparedDirectConnection {
|
||||
uri: string;
|
||||
endpoint: string;
|
||||
useTls: boolean;
|
||||
password?: string;
|
||||
}
|
||||
// The sheet's default first stop (65%) cuts off Password on phones about 690dp tall or shorter.
|
||||
// 80% fits the whole form above Cancel and Connect down to 640dp.
|
||||
const SNAP_POINTS = ["80%", "92%"];
|
||||
|
||||
interface DirectConnectionLabels {
|
||||
hostRequired: string;
|
||||
@@ -49,6 +54,9 @@ interface DirectConnectionLabels {
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
modeBody: {
|
||||
gap: theme.spacing[4],
|
||||
},
|
||||
field: {
|
||||
gap: theme.spacing[2],
|
||||
},
|
||||
@@ -114,26 +122,10 @@ const styles = StyleSheet.create((theme) => ({
|
||||
backgroundColor: theme.colors.accent,
|
||||
borderColor: theme.colors.accent,
|
||||
},
|
||||
advancedToggle: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: theme.spacing[2],
|
||||
alignSelf: "flex-start",
|
||||
paddingVertical: theme.spacing[1],
|
||||
},
|
||||
advancedText: {
|
||||
color: theme.colors.foreground,
|
||||
fontSize: theme.fontSize.base,
|
||||
fontWeight: theme.fontWeight.medium,
|
||||
},
|
||||
actions: {
|
||||
footer: {
|
||||
flex: 1,
|
||||
flexDirection: "row",
|
||||
gap: theme.spacing[3],
|
||||
marginTop: theme.spacing[2],
|
||||
},
|
||||
helper: {
|
||||
color: theme.colors.foregroundMuted,
|
||||
fontSize: theme.fontSize.base,
|
||||
},
|
||||
error: {
|
||||
color: theme.colors.destructive,
|
||||
@@ -141,33 +133,6 @@ const styles = StyleSheet.create((theme) => ({
|
||||
},
|
||||
}));
|
||||
|
||||
function prepareDirectConnection(
|
||||
draft: DirectConnectionDraft,
|
||||
labels: DirectConnectionLabels,
|
||||
): PreparedDirectConnection {
|
||||
const parsed = parseConnectionUri(buildDirectConnectionUri(draft, labels));
|
||||
const endpoint = parsed.isIpv6
|
||||
? `[${parsed.host}]:${parsed.port}`
|
||||
: `${parsed.host}:${parsed.port}`;
|
||||
|
||||
return {
|
||||
uri: serializeConnectionUri(parsed),
|
||||
endpoint,
|
||||
useTls: parsed.useTls,
|
||||
...(parsed.password ? { password: parsed.password } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function draftFromConnectionUri(uri: string): DirectConnectionDraft {
|
||||
const parsed = parseConnectionUri(uri);
|
||||
return {
|
||||
host: parsed.host,
|
||||
port: String(parsed.port),
|
||||
useTls: parsed.useTls,
|
||||
password: parsed.password ?? "",
|
||||
};
|
||||
}
|
||||
|
||||
export interface AddHostModalProps {
|
||||
visible: boolean;
|
||||
onClose: () => void;
|
||||
@@ -198,31 +163,19 @@ function AddHostModalContent({ visible, onClose, onCancel, onSaved }: AddHostMod
|
||||
const { probeAndUpsertDirectConnection, beginLinkPairing } = useHostMutations();
|
||||
const [linkPairing] = useState(() => beginLinkPairing());
|
||||
const isMobile = useIsCompactFormFactor();
|
||||
const keyboardPresent = useHardwareKeyboardPresent();
|
||||
|
||||
const [input, setInput] = useState<DirectConnectionInput>(openDirectConnection);
|
||||
const [isSaving, setIsSaving] = useState(false);
|
||||
const [errorMessage, setErrorMessage] = useState("");
|
||||
const [host, setHost] = useState("");
|
||||
const [port, setPort] = useState("6767");
|
||||
const [useTls, setUseTls] = useState(false);
|
||||
const [password, setPassword] = useState("");
|
||||
const [isPasswordVisible, setIsPasswordVisible] = useState(false);
|
||||
const [isAdvancedOpen, setIsAdvancedOpen] = useState(false);
|
||||
const [advancedUri, setAdvancedUri] = useState("");
|
||||
const [inputResetKey, bumpInputResetKey] = useReducer((key: number) => key + 1, 0);
|
||||
const advancedTarget = useRef(new PairingTargetTracker("", true));
|
||||
// Switching modes mounts the other mode's fields. They take focus when the user was typing
|
||||
// or has a keyboard, so a phone's keyboard stays up instead of closing on the switch.
|
||||
const [focusModeBody, setFocusModeBody] = useState(false);
|
||||
const fieldFocused = useRef(false);
|
||||
// URI mode keeps the Form body's height, so Cancel and Connect stay where they are.
|
||||
const [formBodyHeight, setFormBodyHeight] = useState<number | null>(null);
|
||||
|
||||
const connectIcon = useMemo(() => <ThemedLink2 size={16} />, []);
|
||||
const hostFieldStyle = useMemo(() => [styles.field, styles.hostField], []);
|
||||
const portFieldStyle = useMemo(() => [styles.field, styles.portField], []);
|
||||
const checkboxStyle = useMemo(
|
||||
() => [styles.checkbox, useTls ? styles.checkboxChecked : null],
|
||||
[useTls],
|
||||
);
|
||||
const passwordInputStyle = useMemo(() => [styles.input, styles.passwordInput], []);
|
||||
const useTlsAccessibilityState = useMemo(
|
||||
() => ({ checked: useTls, disabled: isSaving }),
|
||||
[isSaving, useTls],
|
||||
);
|
||||
const directConnectionLabels = useMemo<DirectConnectionLabels>(
|
||||
() => ({
|
||||
hostRequired: t("pairing.direct.errors.hostRequired"),
|
||||
@@ -241,6 +194,21 @@ function AddHostModalContent({ visible, onClose, onCancel, onSaved }: AddHostMod
|
||||
);
|
||||
const header = useMemo<SheetHeader>(() => ({ title: t("pairing.direct.title") }), [t]);
|
||||
|
||||
const formAvailable = canSwitchToForm(input);
|
||||
const modeOptions = useMemo<SegmentedControlOption<DirectConnectionMode>[]>(
|
||||
() => [
|
||||
{
|
||||
value: "form",
|
||||
label: t("pairing.direct.modes.form"),
|
||||
testID: "direct-mode-form",
|
||||
disabled: !formAvailable,
|
||||
...(formAvailable ? {} : { tooltip: t("pairing.direct.modes.uriOnlyLink") }),
|
||||
},
|
||||
{ value: "uri", label: t("pairing.direct.modes.uri"), testID: "direct-mode-uri" },
|
||||
],
|
||||
[formAvailable, t],
|
||||
);
|
||||
|
||||
// Each open mounts a fresh form (see AddHostModal), so closing needs no reset.
|
||||
const handleClose = useCallback(() => {
|
||||
if (isSaving) return;
|
||||
@@ -252,71 +220,37 @@ function AddHostModalContent({ visible, onClose, onCancel, onSaved }: AddHostMod
|
||||
(onCancel ?? onClose)();
|
||||
}, [isSaving, onCancel, onClose]);
|
||||
|
||||
const handleSaveRelay = useCallback(
|
||||
async (relayUri: string) => {
|
||||
try {
|
||||
setIsSaving(true);
|
||||
const commitInput = useCallback(
|
||||
(next: DirectConnectionInput) => {
|
||||
if (next.mode !== input.mode) {
|
||||
setFocusModeBody(keyboardPresent || fieldFocused.current);
|
||||
setErrorMessage("");
|
||||
const result = await linkPairing.submit(relayUri, password || undefined);
|
||||
if (result.status === "cancelled") return;
|
||||
const { profile, serverId, hostname } = result;
|
||||
const isNewHost = !daemons.some((daemon) => daemon.serverId === serverId);
|
||||
onSaved?.({ profile, serverId, hostname, isNewHost });
|
||||
handleClose();
|
||||
} catch (error) {
|
||||
setErrorMessage(
|
||||
error instanceof Error ? error.message : directConnectionLabels.invalidConnection,
|
||||
);
|
||||
} finally {
|
||||
setIsSaving(false);
|
||||
}
|
||||
setInput(next);
|
||||
},
|
||||
[
|
||||
daemons,
|
||||
directConnectionLabels.invalidConnection,
|
||||
handleClose,
|
||||
linkPairing,
|
||||
onSaved,
|
||||
password,
|
||||
],
|
||||
[input.mode, keyboardPresent],
|
||||
);
|
||||
|
||||
const handleSave = useCallback(async () => {
|
||||
if (isSaving) return;
|
||||
|
||||
const relayUri = isAdvancedOpen ? advancedUri.trim() : "";
|
||||
if (relayUri.startsWith("relay://") || relayUri.includes("#connect=")) {
|
||||
await handleSaveRelay(relayUri);
|
||||
return;
|
||||
}
|
||||
|
||||
let connection: PreparedDirectConnection;
|
||||
try {
|
||||
connection = prepareDirectConnection(
|
||||
{ host, port, useTls, password },
|
||||
directConnectionLabels,
|
||||
);
|
||||
} catch (error) {
|
||||
const message =
|
||||
error instanceof Error ? error.message : directConnectionLabels.invalidConnection;
|
||||
setErrorMessage(message);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
setIsSaving(true);
|
||||
setErrorMessage("");
|
||||
|
||||
const { profile, serverId, hostname } = await probeAndUpsertDirectConnection({
|
||||
const connect = useCallback(
|
||||
async (connection: ResolvedDirectConnection) => {
|
||||
if (connection.kind === "relay") {
|
||||
const result = await linkPairing.submit(connection.link, connection.password);
|
||||
return result.status === "cancelled" ? null : result;
|
||||
}
|
||||
return probeAndUpsertDirectConnection({
|
||||
endpoint: connection.endpoint,
|
||||
useTls: connection.useTls,
|
||||
...(connection.password ? { password: connection.password } : {}),
|
||||
});
|
||||
const isNewHost = !daemons.some((daemon) => daemon.serverId === serverId);
|
||||
},
|
||||
[linkPairing, probeAndUpsertDirectConnection],
|
||||
);
|
||||
|
||||
onSaved?.({ profile, serverId, hostname, isNewHost });
|
||||
handleClose();
|
||||
} catch (error) {
|
||||
const describeFailure = useCallback(
|
||||
(connection: ResolvedDirectConnection, error: unknown) => {
|
||||
if (connection.kind === "relay") {
|
||||
return error instanceof Error ? error.message : directConnectionLabels.invalidConnection;
|
||||
}
|
||||
const {
|
||||
title,
|
||||
detail,
|
||||
@@ -326,108 +260,224 @@ function AddHostModalContent({ visible, onClose, onCancel, onSaved }: AddHostMod
|
||||
error,
|
||||
labels: directConnectionLabels,
|
||||
});
|
||||
let combined: string;
|
||||
if (rawDetail && detail && rawDetail !== detail) {
|
||||
combined = `${title}\n${detail}\n${t("pairing.direct.errors.details", {
|
||||
detail: rawDetail,
|
||||
})}`;
|
||||
} else if (detail) {
|
||||
combined = `${title}\n${detail}`;
|
||||
} else {
|
||||
combined = title;
|
||||
return `${title}\n${detail}\n${t("pairing.direct.errors.details", { detail: rawDetail })}`;
|
||||
}
|
||||
setErrorMessage(combined);
|
||||
if (!isMobile) {
|
||||
Alert.alert(t("pairing.direct.errors.failedTitle"), combined);
|
||||
return detail ? `${title}\n${detail}` : title;
|
||||
},
|
||||
[directConnectionLabels, t],
|
||||
);
|
||||
|
||||
const handleSave = useCallback(async () => {
|
||||
if (isSaving) return;
|
||||
|
||||
let connection: ResolvedDirectConnection;
|
||||
try {
|
||||
connection = resolveConnection(input, directConnectionLabels);
|
||||
} catch (error) {
|
||||
setErrorMessage(
|
||||
error instanceof Error ? error.message : directConnectionLabels.invalidConnection,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
setIsSaving(true);
|
||||
setErrorMessage("");
|
||||
const result = await connect(connection);
|
||||
if (!result) return;
|
||||
const { profile, serverId, hostname } = result;
|
||||
const isNewHost = !daemons.some((daemon) => daemon.serverId === serverId);
|
||||
onSaved?.({ profile, serverId, hostname, isNewHost });
|
||||
handleClose();
|
||||
} catch (error) {
|
||||
const message = describeFailure(connection, error);
|
||||
setErrorMessage(message);
|
||||
// URI mode has no Password field, so a rejected password is asked for here.
|
||||
if (input.mode === "uri" && getConnectionAuthFailureReason(error)) {
|
||||
setInput((current) => promptForPassword(current));
|
||||
return;
|
||||
}
|
||||
if (connection.kind === "direct" && !isMobile) {
|
||||
Alert.alert(t("pairing.direct.errors.failedTitle"), message);
|
||||
}
|
||||
} finally {
|
||||
setIsSaving(false);
|
||||
}
|
||||
}, [
|
||||
advancedUri,
|
||||
connect,
|
||||
daemons,
|
||||
describeFailure,
|
||||
directConnectionLabels,
|
||||
handleClose,
|
||||
host,
|
||||
isAdvancedOpen,
|
||||
input,
|
||||
isMobile,
|
||||
isSaving,
|
||||
onSaved,
|
||||
password,
|
||||
port,
|
||||
probeAndUpsertDirectConnection,
|
||||
t,
|
||||
handleSaveRelay,
|
||||
useTls,
|
||||
]);
|
||||
|
||||
const handleSubmitEditing = useCallback(() => {
|
||||
const handleSubmit = useCallback(() => {
|
||||
void handleSave();
|
||||
}, [handleSave]);
|
||||
|
||||
const handleSavePress = useCallback(() => {
|
||||
void handleSave();
|
||||
}, [handleSave]);
|
||||
const handleModeChange = useCallback(
|
||||
(mode: DirectConnectionMode) => commitInput(switchMode(input, mode)),
|
||||
[commitInput, input],
|
||||
);
|
||||
|
||||
const handleChangeAdvancedUri = useCallback((next: string) => {
|
||||
if (advancedTarget.current.changeUrl(next)) {
|
||||
setPassword("");
|
||||
bumpInputResetKey();
|
||||
setErrorMessage("");
|
||||
}
|
||||
setAdvancedUri(next);
|
||||
const handleFieldFocus = useCallback(() => {
|
||||
fieldFocused.current = true;
|
||||
}, []);
|
||||
|
||||
const handleToggleUseTls = useCallback(() => {
|
||||
if (isSaving) return;
|
||||
setUseTls((current) => !current);
|
||||
}, [isSaving]);
|
||||
|
||||
const handleTogglePasswordVisibility = useCallback(() => {
|
||||
setIsPasswordVisible((current) => !current);
|
||||
const handleFieldBlur = useCallback(() => {
|
||||
fieldFocused.current = false;
|
||||
}, []);
|
||||
|
||||
const handleToggleAdvanced = useCallback(() => {
|
||||
if (!isAdvancedOpen) {
|
||||
advancedTarget.current = new PairingTargetTracker("", true);
|
||||
try {
|
||||
setAdvancedUri(
|
||||
buildDirectConnectionUri({ host, port, useTls, password }, directConnectionLabels),
|
||||
);
|
||||
} catch {
|
||||
setAdvancedUri("");
|
||||
}
|
||||
setErrorMessage("");
|
||||
setIsAdvancedOpen(true);
|
||||
return;
|
||||
}
|
||||
const handleFormBodyLayout = useCallback((event: LayoutChangeEvent) => {
|
||||
setFormBodyHeight(event.nativeEvent.layout.height);
|
||||
}, []);
|
||||
|
||||
try {
|
||||
const next = draftFromConnectionUri(advancedUri);
|
||||
setHost(next.host);
|
||||
setPort(next.port);
|
||||
setUseTls(next.useTls);
|
||||
setPassword(next.password);
|
||||
setErrorMessage("");
|
||||
bumpInputResetKey();
|
||||
} catch {
|
||||
setErrorMessage("");
|
||||
}
|
||||
setIsAdvancedOpen(false);
|
||||
}, [advancedUri, directConnectionLabels, host, isAdvancedOpen, password, port, useTls]);
|
||||
const uriBodyStyle = useMemo(
|
||||
() => [styles.modeBody, formBodyHeight === null ? null : { minHeight: formBodyHeight }],
|
||||
[formBodyHeight],
|
||||
);
|
||||
|
||||
const AdvancedIcon = isAdvancedOpen ? ThemedChevronDown : ThemedChevronRight;
|
||||
const PasswordIcon = isPasswordVisible ? ThemedEyeOff : ThemedEye;
|
||||
const fieldEvents = useMemo<FieldEvents>(
|
||||
() => ({
|
||||
autoFocus: focusModeBody,
|
||||
onFocus: handleFieldFocus,
|
||||
onBlur: handleFieldBlur,
|
||||
onSubmit: handleSubmit,
|
||||
}),
|
||||
[focusModeBody, handleFieldBlur, handleFieldFocus, handleSubmit],
|
||||
);
|
||||
|
||||
const footer = useMemo(
|
||||
() => (
|
||||
<View style={styles.footer}>
|
||||
<Button
|
||||
style={FLEX_ONE_STYLE}
|
||||
variant="secondary"
|
||||
onPress={handleCancel}
|
||||
disabled={isSaving}
|
||||
>
|
||||
{t("pairing.direct.actions.cancel")}
|
||||
</Button>
|
||||
<Button
|
||||
style={FLEX_ONE_STYLE}
|
||||
variant="default"
|
||||
onPress={handleSubmit}
|
||||
disabled={isSaving}
|
||||
leftIcon={connectIcon}
|
||||
testID="direct-host-submit"
|
||||
>
|
||||
{isSaving ? t("pairing.direct.actions.connecting") : t("pairing.direct.actions.connect")}
|
||||
</Button>
|
||||
</View>
|
||||
),
|
||||
[connectIcon, handleCancel, handleSubmit, isSaving, t],
|
||||
);
|
||||
|
||||
return (
|
||||
<AdaptiveModalSheet
|
||||
header={header}
|
||||
visible={visible}
|
||||
onClose={handleClose}
|
||||
footer={footer}
|
||||
snapPoints={SNAP_POINTS}
|
||||
testID="add-host-modal"
|
||||
>
|
||||
<Text style={styles.helper}>{t("pairing.direct.helper")}</Text>
|
||||
<SegmentedControl
|
||||
options={modeOptions}
|
||||
value={input.mode}
|
||||
onValueChange={handleModeChange}
|
||||
fill
|
||||
testID="direct-mode"
|
||||
/>
|
||||
|
||||
{input.mode === "form" ? (
|
||||
<View key="form" style={styles.modeBody} onLayout={handleFormBodyLayout}>
|
||||
<DirectFormFields
|
||||
input={input}
|
||||
isSaving={isSaving}
|
||||
fieldEvents={fieldEvents}
|
||||
onChange={commitInput}
|
||||
/>
|
||||
</View>
|
||||
) : (
|
||||
<View key="uri" style={uriBodyStyle}>
|
||||
<DirectUriFields
|
||||
input={input}
|
||||
isSaving={isSaving}
|
||||
fieldEvents={fieldEvents}
|
||||
onChange={commitInput}
|
||||
/>
|
||||
</View>
|
||||
)}
|
||||
|
||||
{errorMessage ? <Text style={styles.error}>{errorMessage}</Text> : null}
|
||||
</AdaptiveModalSheet>
|
||||
);
|
||||
}
|
||||
|
||||
interface FieldEvents {
|
||||
/** Whether the mode's first field takes focus when it mounts. */
|
||||
autoFocus: boolean;
|
||||
onFocus: () => void;
|
||||
onBlur: () => void;
|
||||
onSubmit: () => void;
|
||||
}
|
||||
|
||||
function DirectFormFields({
|
||||
input,
|
||||
isSaving,
|
||||
fieldEvents,
|
||||
onChange,
|
||||
}: {
|
||||
input: DirectConnectionForm;
|
||||
isSaving: boolean;
|
||||
fieldEvents: FieldEvents;
|
||||
onChange: (next: DirectConnectionInput) => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const [isPasswordVisible, setIsPasswordVisible] = useState(false);
|
||||
const hostFieldStyle = useMemo(() => [styles.field, styles.hostField], []);
|
||||
const portFieldStyle = useMemo(() => [styles.field, styles.portField], []);
|
||||
const passwordInputStyle = useMemo(() => [styles.input, styles.passwordInput], []);
|
||||
const checkboxStyle = useMemo(
|
||||
() => [styles.checkbox, input.useTls ? styles.checkboxChecked : null],
|
||||
[input.useTls],
|
||||
);
|
||||
const useTlsAccessibilityState = useMemo(
|
||||
() => ({ checked: input.useTls, disabled: isSaving }),
|
||||
[isSaving, input.useTls],
|
||||
);
|
||||
|
||||
const handleHostChange = useCallback(
|
||||
(host: string) => onChange(editHost(input, host)),
|
||||
[input, onChange],
|
||||
);
|
||||
const handlePortChange = useCallback(
|
||||
(port: string) => onChange(editForm(input, { port })),
|
||||
[input, onChange],
|
||||
);
|
||||
const handlePasswordChange = useCallback(
|
||||
(password: string) => onChange(editForm(input, { password })),
|
||||
[input, onChange],
|
||||
);
|
||||
const handleToggleUseTls = useCallback(() => {
|
||||
if (isSaving) return;
|
||||
onChange(editForm(input, { useTls: !input.useTls }));
|
||||
}, [input, isSaving, onChange]);
|
||||
const handleTogglePasswordVisibility = useCallback(() => {
|
||||
setIsPasswordVisible((current) => !current);
|
||||
}, []);
|
||||
|
||||
const PasswordIcon = isPasswordVisible ? ThemedEyeOff : ThemedEye;
|
||||
|
||||
return (
|
||||
<>
|
||||
<View style={styles.portRow}>
|
||||
<View style={hostFieldStyle}>
|
||||
<Text style={styles.label}>{t("pairing.direct.fields.host")}</Text>
|
||||
@@ -435,9 +485,11 @@ function AddHostModalContent({ visible, onClose, onCancel, onSaved }: AddHostMod
|
||||
testID="direct-host-input"
|
||||
nativeID="direct-host-input"
|
||||
accessibilityLabel={t("pairing.direct.fields.host")}
|
||||
initialValue={host}
|
||||
resetKey={`direct-host-${inputResetKey}`}
|
||||
onChangeText={setHost}
|
||||
initialValue={input.host}
|
||||
onChangeText={handleHostChange}
|
||||
onFocus={fieldEvents.onFocus}
|
||||
onBlur={fieldEvents.onBlur}
|
||||
autoFocus={fieldEvents.autoFocus}
|
||||
placeholder="localhost"
|
||||
style={styles.input}
|
||||
autoCapitalize="none"
|
||||
@@ -453,9 +505,10 @@ function AddHostModalContent({ visible, onClose, onCancel, onSaved }: AddHostMod
|
||||
testID="direct-port-input"
|
||||
nativeID="direct-port-input"
|
||||
accessibilityLabel={t("pairing.direct.fields.port")}
|
||||
initialValue={port}
|
||||
resetKey={`direct-port-${inputResetKey}`}
|
||||
onChangeText={setPort}
|
||||
initialValue={input.port}
|
||||
onChangeText={handlePortChange}
|
||||
onFocus={fieldEvents.onFocus}
|
||||
onBlur={fieldEvents.onBlur}
|
||||
placeholder="6767"
|
||||
style={styles.input}
|
||||
autoCapitalize="none"
|
||||
@@ -463,7 +516,7 @@ function AddHostModalContent({ visible, onClose, onCancel, onSaved }: AddHostMod
|
||||
keyboardType="number-pad"
|
||||
editable={!isSaving}
|
||||
returnKeyType="done"
|
||||
onSubmitEditing={handleSubmitEditing}
|
||||
onSubmitEditing={fieldEvents.onSubmit}
|
||||
/>
|
||||
</View>
|
||||
</View>
|
||||
@@ -475,11 +528,11 @@ function AddHostModalContent({ visible, onClose, onCancel, onSaved }: AddHostMod
|
||||
accessibilityRole="checkbox"
|
||||
accessibilityLabel={t("pairing.direct.fields.useSsl")}
|
||||
accessibilityState={useTlsAccessibilityState}
|
||||
aria-checked={useTls}
|
||||
aria-checked={input.useTls}
|
||||
testID="direct-ssl-toggle"
|
||||
>
|
||||
<View style={checkboxStyle}>
|
||||
{useTls ? (
|
||||
{input.useTls ? (
|
||||
<View testID="direct-ssl-toggle-checked">
|
||||
<ThemedCheck size={14} />
|
||||
</View>
|
||||
@@ -495,9 +548,10 @@ function AddHostModalContent({ visible, onClose, onCancel, onSaved }: AddHostMod
|
||||
testID="direct-password-input"
|
||||
nativeID="direct-password-input"
|
||||
accessibilityLabel={t("pairing.direct.fields.password")}
|
||||
initialValue={password}
|
||||
resetKey={`direct-password-${inputResetKey}`}
|
||||
onChangeText={setPassword}
|
||||
initialValue={input.password}
|
||||
onChangeText={handlePasswordChange}
|
||||
onFocus={fieldEvents.onFocus}
|
||||
onBlur={fieldEvents.onBlur}
|
||||
placeholder={t("pairing.direct.fields.optional")}
|
||||
style={passwordInputStyle}
|
||||
autoCapitalize="none"
|
||||
@@ -505,7 +559,7 @@ function AddHostModalContent({ visible, onClose, onCancel, onSaved }: AddHostMod
|
||||
secureTextEntry={!isPasswordVisible}
|
||||
editable={!isSaving}
|
||||
returnKeyType="done"
|
||||
onSubmitEditing={handleSubmitEditing}
|
||||
onSubmitEditing={fieldEvents.onSubmit}
|
||||
/>
|
||||
<PressHighlight
|
||||
style={styles.iconButton}
|
||||
@@ -523,63 +577,80 @@ function AddHostModalContent({ visible, onClose, onCancel, onSaved }: AddHostMod
|
||||
</PressHighlight>
|
||||
</View>
|
||||
</View>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function DirectUriFields({
|
||||
input,
|
||||
isSaving,
|
||||
fieldEvents,
|
||||
onChange,
|
||||
}: {
|
||||
input: DirectConnectionUri;
|
||||
isSaving: boolean;
|
||||
fieldEvents: FieldEvents;
|
||||
onChange: (next: DirectConnectionInput) => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const handleUriChange = useCallback(
|
||||
(uri: string) => onChange(editUri(input, uri)),
|
||||
[input, onChange],
|
||||
);
|
||||
const handlePromptPasswordChange = useCallback(
|
||||
(password: string) => onChange(editPromptPassword(input, password)),
|
||||
[input, onChange],
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
<View style={styles.field}>
|
||||
<PressHighlight
|
||||
style={styles.advancedToggle}
|
||||
onPress={handleToggleAdvanced}
|
||||
disabled={isSaving}
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={
|
||||
isAdvancedOpen ? t("pairing.direct.advanced.hide") : t("pairing.direct.advanced.show")
|
||||
}
|
||||
testID="direct-host-advanced-toggle"
|
||||
>
|
||||
<AdvancedIcon size={16} />
|
||||
<Text style={styles.advancedText}>{t("pairing.direct.advanced.label")}</Text>
|
||||
</PressHighlight>
|
||||
{isAdvancedOpen ? (
|
||||
<Text style={styles.label}>{t("pairing.direct.fields.connectionUri")}</Text>
|
||||
<AdaptiveTextInput
|
||||
testID="direct-host-uri-input"
|
||||
nativeID="direct-host-uri-input"
|
||||
accessibilityLabel={t("pairing.direct.fields.connectionUri")}
|
||||
initialValue={input.uri}
|
||||
onChangeText={handleUriChange}
|
||||
onFocus={fieldEvents.onFocus}
|
||||
onBlur={fieldEvents.onBlur}
|
||||
autoFocus={fieldEvents.autoFocus}
|
||||
placeholder="tcp://localhost:6767?ssl=true"
|
||||
style={styles.input}
|
||||
autoCapitalize="none"
|
||||
autoCorrect={false}
|
||||
keyboardType="url"
|
||||
editable={!isSaving}
|
||||
returnKeyType="done"
|
||||
onSubmitEditing={fieldEvents.onSubmit}
|
||||
/>
|
||||
</View>
|
||||
|
||||
{input.prompt ? (
|
||||
<View style={styles.field}>
|
||||
<Text style={styles.label}>
|
||||
{t("pairing.hostPassword.title", { host: input.prompt.host })}
|
||||
</Text>
|
||||
<AdaptiveTextInput
|
||||
testID="direct-host-uri-input"
|
||||
nativeID="direct-host-uri-input"
|
||||
accessibilityLabel={t("pairing.direct.fields.connectionUri")}
|
||||
initialValue={advancedUri}
|
||||
resetKey={`direct-host-uri-${inputResetKey}`}
|
||||
onChangeText={handleChangeAdvancedUri}
|
||||
placeholder="tcp://localhost:6767?ssl=true"
|
||||
style={styles.input}
|
||||
testID="direct-uri-password-input"
|
||||
accessibilityLabel={t("pairing.hostPassword.label")}
|
||||
placeholder={t("pairing.hostPassword.label")}
|
||||
initialValue={input.prompt.password}
|
||||
onChangeText={handlePromptPasswordChange}
|
||||
onFocus={fieldEvents.onFocus}
|
||||
onBlur={fieldEvents.onBlur}
|
||||
autoFocus
|
||||
secureTextEntry
|
||||
autoCapitalize="none"
|
||||
autoCorrect={false}
|
||||
keyboardType="url"
|
||||
editable={!isSaving}
|
||||
returnKeyType="done"
|
||||
onSubmitEditing={handleToggleAdvanced}
|
||||
onSubmitEditing={fieldEvents.onSubmit}
|
||||
style={styles.input}
|
||||
/>
|
||||
) : null}
|
||||
{errorMessage ? <Text style={styles.error}>{errorMessage}</Text> : null}
|
||||
</View>
|
||||
|
||||
<View style={styles.actions}>
|
||||
<Button
|
||||
style={FLEX_ONE_STYLE}
|
||||
variant="secondary"
|
||||
onPress={handleCancel}
|
||||
disabled={isSaving}
|
||||
>
|
||||
{t("pairing.direct.actions.cancel")}
|
||||
</Button>
|
||||
<Button
|
||||
style={FLEX_ONE_STYLE}
|
||||
variant="default"
|
||||
onPress={handleSavePress}
|
||||
disabled={isSaving}
|
||||
leftIcon={connectIcon}
|
||||
testID="direct-host-submit"
|
||||
>
|
||||
{isSaving ? t("pairing.direct.actions.connecting") : t("pairing.direct.actions.connect")}
|
||||
</Button>
|
||||
</View>
|
||||
</AdaptiveModalSheet>
|
||||
</View>
|
||||
) : null}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -587,14 +658,6 @@ const ThemedLink2 = withUnistyles(Link2, (theme) => ({ color: theme.colors.accen
|
||||
|
||||
const ThemedCheck = withUnistyles(Check, (theme) => ({ color: theme.colors.accentForeground }));
|
||||
|
||||
const ThemedChevronDown = withUnistyles(ChevronDown, (theme) => ({
|
||||
color: theme.colors.foregroundMuted,
|
||||
}));
|
||||
|
||||
const ThemedChevronRight = withUnistyles(ChevronRight, (theme) => ({
|
||||
color: theme.colors.foregroundMuted,
|
||||
}));
|
||||
|
||||
const ThemedEye = withUnistyles(Eye, (theme) => ({ color: theme.colors.foregroundMuted }));
|
||||
|
||||
const ThemedEyeOff = withUnistyles(EyeOff, (theme) => ({ color: theme.colors.foregroundMuted }));
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user